Correct way to massively change node author I want to change all the nodes where $user1 is author and set $user2 as author.
I use this PHP Code and it works, but is it the correct way to do it?
Or should I use a batch process and load each node to change the author?

   $num_updated = db_update('node')
      ->fields(array(
        'uid' => $user2->uid,
      ))
      ->condition('uid', $user1->uid, '=')
      ->execute();

It sounds like your Administering a Drupal site (not just a content moderator) -- but a site administration / developer.

Your code is fine. I recommend using Drush and calling your code as $ drush php-script massively-change-node-author.php from the command line. This way there is no timeout issues and you don't need to worry about using the Batch API and stuff like that.

Running code from php-script and drush performs a FULL BOOTSTRAP of drupal by default, and if needed you can pass a user argument to run the script as (faking a logged in user of $user) by using --user=1 for instance. For example: $ drush php-script --user=1 massively-change-node-author.php.

EDIT:

To avoid out-of-sync errors between node and node_revision table it's recommend to use node_load() and node_save() on the Nodes you want to update. Eg,

global $user;
foreach ($node_ids as $nid) {
  $node = node_load($nid);
  $node->uid = $user->uid;
  node_save($node);
}

Getting the list of node ids you want to affect, I leave as a task for you. The issues such as timeouts, using batch api etc -- are all still gone when using Drush. The logic is very similiar just using the better drupal API rather than direct database updates.


How do I structure a simple Drupal 7 site/theme? I'm coming from WordPress CMS and right now (to be honest) I'm a bit overwhelmed by the (seemingly) complex Drupal theming/content management system.

I have a website with the following pages (I've simplified it a bit but that shouldn't be a problem):

Home (contains 3 containers with text/lists that should be editable through the CMS)
About (editable text)
Jobs (lists all available job offers, also editable)

I want to start my theme from scratch. I have my html.tpl.php where I have title and meta stuff; then I have the page.tpl.php with my layout. That layout is the same for every one of my pages; the only thing that changes is the content inside my content-div.

How and where do I code the structure for my "Home" page? Is every editable text container a region to which I assign a block I created? Is my "Home" page basically a node whose code should be in a extra node--[home].tpl.php file?

I googled a lot, but I couldn't find good instructions on starting a theme from scratch. All the tutorials I found only changed some basic things in a theme or did sub-theming but there was nothing that could show me how to structure my site.

Maybe someone can help me or point me to a good tutorial; coming from a WordPress background i'm very confused right now.

It sounds like most of the things that you need to do (i.e. creating and placing content on the site) are not related to a theme, but rather related to site building. Folks coming over from Wordpress are usually confused by the split between theming and site building in Drupal, it's very different from Wordpress.

I would strongly recommend reading Drupal's Site Structure Guide. Your homepage and "about" page will most likely be a combination of node content and blocks, while your "jobs" page will involve creating a custom content type and a Views page listing the nodes of that content type.

The majority of your work to set up the content of the site and it's output can happen before you even begin theming. Theming is usually a later step in site building and should be considered a very superficial aspect of building the site. There are few situations where you would need custom templates for each page or node type, most of the arrangement of content and even layout can be handled via the Drupal UI.

Once you complete the site build in Drupal and move on to theming, the Drupal Theming Guide will be your starting resource for learning how the Drupal theme layer works.


How do I print the SQL query of a view in front end? I have installed latest Drupal 8.1.1 also Devel module installed there is no any option for Display query log on devel setting page while it's present on D7 Devel module.
I have created a view with relationship now I want to display SQL Query of that view at the front end.

How do I print the SQL query of a view in front end?

You can enable on "Show the SQL query" and "Show other queries run during render during live preview" on "www.example.com/admin/structure/views/settings"

Hope it will help you.


Drupal commerce - product display view replicates products I'm building a ecommerce for a fashion designer and of course every item has got variation such as color and size.
With line item it's fine, on the product display i've got the option to change color and size and with the fancy attribute module I can show a small box with the color instead of simple text.

Now I have to build a view of product display which contains title, 1 picture and price.
In order to get the price I create a relationship with the product reference but here comes the problem, it shows all the products, every variations so one item could be repeated several times in different color and different size.

I would like to show just one product of that group, then the user clicks on it and sees the product display and there he can choose the variation.

Of course I can delete the relationship, add a price field on the content type "product display" and show it in the view but I would like to know if there is another way to do it.

Thanks in advance.

This is known issue discussed in this issue. Setting the query to distinct in the queery settings under advanced within views worked for me, as described in comment 6.


Programmatically populate file field using Entity API I need to programmatically generate nodes using some data that I extract from different import files.
For the node creation I use Entity API.
I've written a simple function to which I pass the node data in a structured array and the function imports each field depending on how it's defined:

  function my_module_create_function($item, $node_type, $language) {
    $node = entity_create('node', array ('type' => $node_type));
    $entity = entity_metadata_wrapper('node',  $node);
    $entity->language = 'es';//LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
    //strings
    foreach ($item as $key=> $field) {
      switch ($field['field_type']) {
        case 'multiple-reference':
          if(is_array($field['value'])){
            $entity->$key = $field['value'];
          }else{
            //some alert log
          }
          break;
        case 'file':
          if (file_exists($field['value']) && isset($field['filename']))
          {
            $file = file_get_contents($field['value']);
            $filename = $field['filename'];
            if(isset($field['folder']) && file_exists($field['folder'])){
              $folder = $field['folder'];
            }else{
              $folder = "public://";
            }
            $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
            $entity->$key= (array)$file;
          }
          else
          {
            // some alert log
          }
          break;
        case 'long-text':
          $entity->$key->set(array(
            'value' =>  $field['value'],
            //'summary' => '',
            'format' => 'full_html',
          ));
          break;
        case 'geolocation':
          $entity->$key->set(array(
            'latitude' => $field['value']['latitude'],
            'longitude' => $field['value']['longitude'],
            //other elements added here (province, postal_code, country [es, en,...],additional, ...)
          ));
          break;
        default:
          $entity->$key= $field['value'];
        break;
      }
    }
    $entity->status = 1; //(1 or 0): published or not
    $entity->promote = 0; //(1 or 0): promoted to front page
    $entity->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write
    // Save the entity
    return $entity->save();
  }

This function works great except for the file field type. When I try to import a node with a file it gives me this error:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
  Column 'my_field_display' cannot be null

the thing is that I have used the same structure:

        $file = file_get_contents("file_path");
        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        $entity->$key= (array)$file;

for image fields (or multiple image fields using "[] =" instead of " = ") it works without any problem. Anyone knows if I'm doing anything wrong with this file field?

Any advice would be helpful

Ok, I found the answer to this question here.

Instead of:

        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        $entity->$key= (array)$file;

It should be:

        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        if($file !== false)
        {
          $entity->$key->file->set($file);
        }

This 'if($file !== false)' is optional just to be sure that we're passing a file object.

  *Note that the difference is that we're not passing the file object as an array and also we're passing it to a 'file' atribute instead of
  passing it directly to the field.


Why isn't this ajax form working? function ga_script_script_question($form, &$form_state) {
    $form['question'] = array(
        '#type' => 'fieldset',
        '#title' => t('Question'),
        '#collapsible' => FALSE,
        '#collapsed' => FALSE,
        '#prefix' => '
',
        '#suffix' => '
',
    );

    if(isset($form_state['storage']['myflag'])) {
        $form['question']['new_thing'] = array(
            '#markup' => "new thing",
        );
    }

    $form['question']['original_thing'] = array(
        '#markup' => "original thing",
    );

    $form['next_question'] = array(
        '#type' => 'submit',
        '#value' => t('Next question'),
        '#submit' => array('ga_script_script_next_question'),
        '#ajax' => array(
            'callback' => 'ga_script_script_callback',
            'wrapper' => 'question-wrapper',
        ),
    );

    return $form;
}

function ga_script_script_next_question($form, $form_state) {
    $form_state['storage']['myflag'] = 1;
    $form_state['rebuild'] = TRUE;
}

function ga_script_script_callback($form, &$form_state) {
    return $form['question'];
}

When I submit this form, nothing happens. I get the little spinning thing next to my submit button, but the contents of question-wrapper are unchanged. It seems like the form is not getting rebuilt.

What am I doing wrong?

I just realised I was missing the & in my submit function. It should have looked like this:

function ga_script_script_next_question($form, &$form_state) {
}

It works fine now.


Is site safe after a failed module installation? I was working on a site this morning, and I enabled a whole bunch of modules at the same time.  One of the modules threw a PDO exception during the process.

What state is the site in at this point?  Assuming the site still loads after the error, is it safe to use, or should I restore from a backup?

For the sake of this question, I am not concerned about the actual error or the module that threw the error (I would report this in the issue queue).  I am concerned about the general state of the site, and what may have happened to the installations of the other modules.

To make this more concrete, let's say I tried to enable ModuleA, ModuleB, ModuleC, and ModuleD.  After I clicked SUBMIT on the module page, ModuleC threw an uncaught PDO Exception and I didn't get the normal module enabled message.  Now, lets say that I can live without ModuleC on the site.  What can be said about the state of hpw the installation went for ModuleA, ModuleB, and ModuleD, and also dor Drupal in general?

Generally, it isn't. It may be, but it depends what's in module's hook_install.

First, most modules provide schema. The code of drupal_install_schema in 7 is currently:

function drupal_install_schema($module) {
  $schema = drupal_get_schema_unprocessed($module);
  _drupal_schema_initialize($schema, $module, FALSE);

  foreach ($schema as $name => $table) {
    db_create_table($name, $table);
  }
}

As you can see, no call to db_translation, and each table is created one at a time. Now, if module only provides own schema, you are left with some garbage in database, but it's a well isolated garbage. But if it implements hook_schema_alter it's pretty possible you are left with some tables already altered, bu no code to handle these alterations. Now, in theory installing schema should never fail with PDO error, but due to RDBMS configuration for example, it may happen.

Second problem is that module's author can write pretty much anything in it's install code, and you are not guaranteed it will get rolled back at failed install. If he decides his module needs to change variables provided by core or other modules (for example to allow apparent conditional content, like with translated variables), or if it redefines some fields to provide additional functionality, you may end up with some of your data converted to module's format, and no longer accessible without it, or without running code meant to uninstall it.

Note: Situations above from experience. Even if I miss some theoretical part that should make them impossible to happen, they both did happened to me in real life. With -dev versions, but module version depends solely on it's author, so there is no guarantee that it will not happen in stable versions some day, too.


How do I allow an entity reference to be null in my custom entity? I am working on adding taxonomy to the poll module. This is my  BaseFieldDefinition:
$fields['category'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Category'))
  ->setDescription(t('Section this poll is to appear on'))
  ->setSetting('target_type', 'taxonomy_term')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => -10,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
      'options_list_callback' => 'my_callback',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setRequired(FALSE);

However, I would like the category to be optional, but when creating a poll if it is left blank it returns an SQL error and this error appears on screen.

The website encountered an unexpected error. Please try again later.
Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'category' cannot be null: INSERT INTO  {poll_field_data} (id, langcode, uid, question, category, runtime,   anonymous_vote_allow, cancel_vote_allow, result_vote_allow, status, created, default_langcode) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,  :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4,  :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11); Array ( [:db_insert_placeholder_0] => 3  [:db_insert_placeholder_1] => en [:db_insert_placeholder_2] => 1  [:db_insert_placeholder_3] => TEST poll [:db_insert_placeholder_4] =>   [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => 0  [:db_insert_placeholder_7] => 1 [:db_insert_placeholder_8] => 0  [:db_insert_placeholder_9] => 1 [:db_insert_placeholder_10] => 1442410281 [:db_insert_placeholder_11] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 755 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

If ->setRequired(FALSE) doesn't allow null columns in the database what does?

The 'not null' instruction is automatically set to TRUE if that field is set in your entity's (entity_keys) annotations:

ex:

entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "uid" = "uid",
 *     "price" = "price",
 *     "langcode" = "langcode",
 *     "complete" = "complete",
 *   },

In this case ->setRequired(FALSE) will be ignored.
However, if you really have to, you can force it to FALSE if you provide your custom storage schema handler.

Todo so add the handler in your entity annotations:

handlers = {
 *     "storage_schema" = "Drupal\YOUR_MODULE\YourEntityStorageSchema",
...
}

And the create YourEntityStorageSchema.php file:

<?php

namespace Drupal\YOUR_MODULE;

use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema;
use Drupal\Core\Field\FieldStorageDefinitionInterface;

class YourEntityStorageSchema extends SqlContentEntityStorageSchema {

  protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
    $schema = parent::getEntitySchema($entity_type, $reset);

    //then target your annoying field and set the 'not null' key to FALSE!
    if (!empty($schema['rp_payment']['fields']['operator_id']))
      $schema['rp_payment']['fields']['operator_id']['not null'] = FALSE;

    return $schema;
  }
}

Hope it helps! ^^


Display definition of the term searched for - above search results Beginning a search on google with 'what is psych'... triggers auto completion with 4 suggested phrases - arrow down through each and you will see its definition appear above its pertaining results:

How can I add a definition of the terms (if available) above the results? Ideally would like to use auto complete. I've attempted to achieve this with the Google custom search engine and Google site search modules. Unfortunately, the Google Dictionary service appears to no longer be supported by Google.

I explored another option such as using Solr search api and coding a second custom call from a definition source such as Wordnik and then combining that result with the Solr results. I think this may be feasible but not sure yet how will combine the results.

How could I combine search results to include a definition and/or is there a better way to include a definition of what the user may be searching for, above the actual results?

It turned out it was necessary to use Wordnik api (or similar) to get the definition service that I required. So I've written a module to handle the api and show definition/image for the searched terms if available.

After talking to Google support and verifying my research that google no longer provides a definition service (they did back in 2011) to private websites, I realized it best to abandon the idea of using the google custom search engine. Instead I've setup Solr which is a bit more work but much more custom.


Editing the template for Comments editing page I've got my comments for my nodes looking good ON the node. However, as an admin, or using the permalink, if you go to the actual comment page (/comment/comment#) it looks funky. I'd like to format it so the sharebar doesn't appear, the whole node doesn't appear, all the rest of the comments don't appear, and the ability to add yet another comment doesn't appear. I JUST want the comment to appear on that page. Sort of like when you go to comments > edit (as an admin).

Does anyone know how to edit this page or what the template file is at least so I can edit that?

Thanks!

As the comment page does not use it's own theme so you probably have to do it as outlined in this question.

But, If you just want to redirect the comment page back to the original post, the latest dev version of the Global Redirect module has a setting for this. I recently did this on a site as the comment pages were causing SEO problems.


PHPUnit testing a method that changes an entity field Let's say I have an entity with certain fields and a method that does the following
public function changeEntityField(Entity $entity) {
  $entity->set('field_xyz', 20);
  $entity->save();
  return $entity;
}

I know how to mock an entity and set its field values via $entity->expects($this->any())->method('get')->with('field_xyz')->willReturn(10) etc. and pass it to the function to be tested.
What I don't get yet is how to test the function does really set the field_xyz to 20 ?
I tried
$entity = $this->getMockBuilder(Application::class)
  ->disableOriginalConstructor()
  ->getMock();
$field = $this->getMockBuilder(FieldItemListInterface::class)
      ->disableOriginalConstructor()
      ->getMock();
$field->expects($this->any())
      ->method('__get')
      ->with('value')
      ->willReturn(10);
$entity->expects($this->any())
  ->method('get')
  ->with('field_xyz')
  ->willReturn($field);
$result = $this->service->changeEntityField($entity);
$this->assertEqual($result->get('field_xyz')->value, 20);

but it returns 10. How do I mock the ->set() methods of the entity? Or do I have to work with real entities and not mocks in such cases?

You can't do that in a unit test, you have to work with real entities in a functional test since $entity->save(); needs the database to be loaded.
And as $result = $this->service->changeEntityField($entity); will return an entity there's no way $result can be equal to 10 or 20. It will be equal to an entity. But in a functional test you'll be able to load the entity and check if the field has the good value or not after your function has been called.


How to redirect all images in the files folder to a default file? Because we work with DTAP environments, our developers work on their own laptops. To get a good view of the live environment, we copy the PROD database and the files to our own laptop. However, this takes up a lot of space because of all the files directories.

What I'd love to have is a simple .htaccess or Apache redirect rule that points all files in the files directory to one default image, so that we don't have to copy the files directory contents (which can be gigabytes sometimes).

There is one exception though for JS/CSS files and files in the files/styles directory. Those callbacks must keep working.

Any thoughts on if and how this would be achievable?

You could use the stage_file_proxy module or cdn module


How db_set_active works with other db? Is db_set_active() need to work with a Drupal database or can I use it with a database that doesn't contain any drupal tables ?

db_set_active() is used for connecting to another database. The other database does not need to be Drupal at all.

Just don't forget to switch back to default DB when you are done. If you don't, Drupal will try to perform all subsequent queries in the other database, which will result in a lot of errors and potentially mess up the data in the other database.

Here's example code:

// Connect to your other database.
db_set_active('your_other_db');
// Run any queries you want.
db_query("...");
// Switch back to the default database of your installation.
db_set_active();

You can read more about db_set_active() here.

Another note, per Neograph734's reminder: the argument you would pass to the db_set_active() needs to be the same key you used for adding another DB access info in settings.php file.

Here's an example:

$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'your_default_database',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'your_other_db' => array (
    'default' => array (
      'database' => 'your_other_database',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);


Where to place JS code to be used by Admin? I have a simple requirement that I want to implement JS on couple of fields. Through JS, I want to hide few fields by default and show them when a checkbox is clicked.

The problem is where to keep this JS for admin. Below is the JS which is working. Weirdly, when I paste in the console of Chrome, the JS then works.

JS

jQuery('input#edit-field-mine-und').change(function() {
        if(jQuery(this).is(":checked")) {
            alert("Checked");
        }
        else {
            alert ("Not Checked");
        }
        //$('#textbox1').val($(this).is(':checked'));
});

Any help where I can place this JS so that it can be used in admin drupal pages?

You have to put that either in an administrative theme or in a custom module.

It's a good idea generally to have a child theme based on the administrative theme you are already using.
This means that you can override most of the things (e.g. styles, labels, etc.) in the admin while still being able to update the parent theme.

Here's how you would do it if you are using Seven for example:

Create a new folder named seven_custom
Inside create a new file named seven_custom.info and copy all the regions from seven.info file
Copy the screenshot.png and logo.png from Seven
Create a new file named custom.js for example
Add that file under scripts[] in seven_custom.info, like so:

scripts[] = custom.js

Edit your JS file to extend Drupal behaviors and use Drupal.t() for making strings translatable:

(function ($) {
  Drupal.behaviors.UltimaTheme = {
    attach: function (context, settings) {
      $('input#edit-field-mine-und').change(function() {
        if($(this).is(':checked')) {
          alert(Drupal.t('Checked'));
        }
        else {
          alert(Drupal.t('Not Checked'));
        }
      });
    };
  };
})(jQuery);

I wrote this without testing, but should work fine. Let me know if it doesn't.


Search user's all fileds in drupal 7 I want to make a text fields that will make user able to search all the fields. I have tried few modules but nothing is working for me the way i want.

You can combine multiple field values into one (hidden) field using Computed Field. Be sure to save the value to the database, so that it can be used as a Views exposed filter. You'll also need to re-save each existing node in order to populate the computed field (VBO can do that in bulk).

This is another interesting idea (I haven't tried it): http://drupal.org/node/732458#comment-4750574


How to expose Profile2 fields in Services? Is there a good solution to CRUD a user's Profile2 fields via Services? I assume this can be done with Services Entity API, but I wonder if there is a more direct integration?

With Services Entity API, I enabled the entity_profile2 resource and can load an index of profiles. I need to disable the ability to index the profiles but allow a user to retrieve their own profile.

From the docs, this URL should be able to find user with uid=296's profile:

api/entity_profile2.json?parameters[uid]=296

But the result is an empty page.

I found that I had to use pid: /api/entity_profile2?parameters[pid]=1


Composer updating to 8.9.0beta2 instead of 8.9.0 I'm currently using the drupal/core-recommended project and I'm having issues updating to 8.9.0.

Some reason composer is updating it to 8.9.0-beta2.

Steps I took to update was go into my composer.json file and changed:
"drupal/core-composer-scaffold": "^8.8",
"drupal/core-recommended": "^8.8",

TO
"drupal/core-composer-scaffold": "^8.9",
"drupal/core-recommended": "^8.9",

Then ran composer install

Then it just downloads the beta version instead of the stable version.

Anyone know why?

This and similar dependency conflicts can typically be solved by asking composer to also update symfony packages as described in Drush blocks update from 8.9.0-beta2 to 8.9.2.
composer update drupal/core-recommended symfony/* --with-all-dependencies


How to set shorter caching time for a paragraph I have made a paragraph that shows social media wall (based on PHP Social Stream-module). The problem is that the wall isn't updated except when the global cache is recycled.

I have tried (in vain so far) to find out what is the correct way to make the caching "more agile" for that paragraph.

The paragraph is only using the paragraph twig and a a small MYTHEME_preprocess_paragraph__PARAGRAPH_NAME-function.

As it is placed on the front page on a site under quite a heavy load, I would prefer it not to be un-caching the whole page (not even talking about whole site).

Any suggestions?

wbr

hank


On content edit, how can I check/select a bool field based on which tab is active? I have a content type with a paragraph that has two fields, each field inside its own tab controlled by the form display like so:

Here is what the set of tabbed fields looks like when editing a piece of content of the content type:

The paragraph also has a bool field called field_active_callout_tab with two values: 'Single' and 'Multi', same as the tabs.

If the 'Single' tab is clicked, I want the bool to be checked. If the 'Multi' tab is selected, I want the bool to be unchecked.

I tried to use the Conditional Fields module, but it will not allow control by tab label. How can I establish this dependency between the tab and the bool?

You can do it with jQuery, something like this should do it:

$('.single-class').click(function () {
    $('.bool-class').prop('checked', true);
});
$('.multi-class').click(function () {
  $('.bool-class').prop('checked', false);
});


drupal_add_js and inline code I am trying to use inline javascript, added with hook_alpha_preprocess_page, to add support to IE.

drupal_add_js('
jQuery(document).ready(function () {
    if (jQuery.browser.msie && jQuery.browser.version < 10) {
            $("li#megamenu-mlid-774 .megamenu-items, li#megamenu-mlid-842 .megamenu-items").columnize({
                width: 420,
                columns: 3
            });
        }
  });', 'inline');

While this loads on the page, nothing is happening. Is this because my selector starts with $? What should I change it to for this to work?

First of all you need to replace $ with jQuery and secondly you also need to put the width and coulmn properties inside double quotes. i.e,

drupal_add_js('
jQuery(document).ready(function () {
    if (jQuery.browser.msie && jQuery.browser.version < 10) {
            jQuery("li#megamenu-mlid-774 .megamenu-items, li#megamenu-mlid-842 .megamenu-items").columnize({
                "width": "420",
                "columns": "3"
            });
        }
  });', 'inline');


How can I remove the "The image was resized to fit within the maximum allowed dimensions..." message without hacking core? By default, Drupal prints out a notification message that images exceeding the maximum dimensions were resized.  I want to disable this message.

The relevant line is located in file_validate_image_resolution():

  drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));

Obviously, the quick way to do this is to put two little slashes right before the line.  But I am trying to do this without hacking core.  I copied the entire function into MYMODULE_file_validate_image_resolution(), then commented the lines out, but this had no effect.  What's the right way to do this?

Disable Messages module helps you to disable any type of message in drupal.

It module has following features.

Filter out messages that match a full text string exactly.
Filter out messages that match a regular expression.
Permissions to specifically hide all messages of a given type from
any role.
Disable all filtering for specific users.
Disable all filtering for specific paths.
Apply filtering only for specific paths.
Debug system to get messages in the HTML without showing it to the
end users.

Once you install the module you can see the configuration options at admin/config/development/disable-messages.

For your requirement just enter following text in "Messages to be disabled:" textarea.

The image was resized to fit within the maximum allowed dimensions of .*? pixels.

Note : Make sure necessary permission to be set like below.


Devel kpr, dpr, dpm, etc. only print after cache flush I'm writing a small module and using the Devel print functions (dpr, kpr, dpm, etc.) to print out some values.

However, I only see the values in the page after I flush certain caches. if I just reload the page or go to it I see nothing. This is true for both the message-area and the regular debug print functions. Is this expected?

I am logged in as admin so I'd think ordinary page caching is off.

(This is in D7.)

hook_field_widget_info_alter() is cached.  Follow these steps to Suppress caching (for development) or to use an external page cache

  when developing for Drupal you might want to suppress all caching of
  data to make sure new hooks, theme functions, etc are recognized
  immediately.

  This will have performance detriments, of course, so must not be used
  in production. To turn on this development mode, add the following to
  your Drupal 7 settings.php file:


Is it possible to rewrite the output of this CSV item with Feeds Tamper? I have a feed set up to use the HTTP Fetcher with CSV Parser to download my content from a URL using the Feeds module (7.x-2.0-alpha8+84-dev) and Feeds Tamper module (7.x-1.0). I've mapped out my fields appropriately, but I'm having difficultly with the instance.

In my CSV source, there's one field where the information source outputs:
[[u'short', u'introduced', u'Solar Energy and Energy Conservation, Bank Reauthorization Act of 1983'], [u'official', u'introduced', u'A bill to amend the Solar Energy and Energy Conservation Bank Act to authorize appropriations for the provision of financial assistance under such Act through fiscal year 1990, and for other purposes.']]

However, I only really need the official title pulled into my content, which should be "A bill to amend the Solar Energy and Energy Conservation Bank Act to authorize appropriations for the provision of financial assistance under such Act through fiscal year 1990, and for other purposes."

Is it possible to rewrite this with Feeds Tamper, and if so, which plugin would you use/how would you set this up? In this instance, I don't believe explode would work because I do not want both items in my content and I would like the brackets '[]' and such removed. If not possible, how would you suggest accomplishing my goal?

I'm happy to provide more information, and I very much appreciate any assistance. tia

Here's the link to the source location. I've limited the results to 1 as to not overwhelm :)

I agree with MPD. Plugins are easy to write. That looks like a serialised Python object. Is that right?

If you want to avoid that then I think your only option is the regular expression tamper. Use a site that allows you too test your expression on your sample string to help get it right while being fuzzy enough to handle edge cases. Here's one.

https://regex101.com

This seems to work though I'm not 100% on why it only returns the last match so use with caution. Match is in $2.

\[{2}.+?\],\s*\[(u'(.+?)'\,*\s*)+\]{2}

Actually this might be more robust. Match is in $1.

\[{2}.+?\],\s*\[.+\,\s{0,1}u'(.+?)'\]{2}$

https://regex101.com/r/qQ0cC0/3


How to collect payments for the missed periods with the hard decline status? Scenario: A user's credit card expires and he misses to pay his recurring monthly fee. Two months later he updates his credit card and because the license never expired the system picks it up and continues to successfully charge his card on file for consequent periods, but unfortunately not for the previous.

And it's not clear how to charge for the missed payments with the "Payment failed (hard decline)" status. Any suggestions?

Edit: I had to delete my own answer:

  It was not obvious for me that I needed to use Commerce Dunning module
  to re-charge for the missed payments.

after trying the Commerce Dunning module, because unfortunately for hard declines it only sends notifications without attempting to re-charge for the missed period even if a customer updated his credit card. Per description on https://www.drupal.org/project/commerce_dunning:

  If it was a hard decline that led to the failure, the customer needs
  to update their credit card, so notifications regarding that are also
  scheduled.

So unfortunately it is still not clear how to collect payments for the missed period.

If a customer has a hard decline, they'll need to log in and create a new stored payment option. They can create new stored payments via their account dashboard:

If memory serves, it should then be used by default.


Which event should we subscribe to if we want code to be triggered when a new user registers? I noticed that account.set is the event invoked for a user account.
I want to create an event subscriber which adds a callback invoked when a new user registers on the site. I am not sure whether account.set is the correct event.
Are there other better events for this?

AccountEvents::SET_USER isn't the event for user registration. Per the docs:

  This event allows modules to perform an action whenever the current user is
  set. The event listener receives an \Drupal\Core\Session\AccountSetEvent
  instance.

The event is fired when Drupal initializes the user object for the current request, not when new users are created.

For responding to new user creation, you can still use hook_user_insert().


Drupal how create alias I am looking to create aliases.

My url is user/uid/edit and I want panel/your-edit or panel/uid/your-edit
How can i do that? How create alias?

When i try create alias in admin panel I have an error:
Path user/[user:uid]/edit is incorrect or user do not have access.

Hope this will  help you,

In Drupal 7 you can use these modules for your requirement

Extended path aliases
Sub-pathauto (Sub-path URL Aliases)


How to get drush to work with xdebug -- may have recently broken I've been using drush with xdebug for years.  It looks like it broke in the last two weeks, possibly due to modifications made to the core "drush" script (Split 'drush' script into finder, wrapper and launcher stages.). It now dispatches via "pcntl_exec" on Ubuntu, and xdebug never gets control back thereafter.

I've tried reverting drush to the previous commit ("8ab7ad9... Make uli test more resiliant vis-a-vis html tags that may be injected into log messages."), which fixes the xdebug problem, but does not appear to be compatible with RC1 :-(.  So I strongly suspect the addition of pcntl_exec.

Anyone know how to get around this, or do I need to log an issue against drush on their github site?

The former drush script is still available as drush.launcher. I would recommend making this your entrypoint when using Drush with xdebug, and omit the drush "finder" script (called simply "drush") altogether.

If this does not work for you, you should make a report in the Drush issue queue on GitHub.


How do I show in the home page the facets shown in the product page? I'm working on the http://drupal.org/project/commerce_kickstart distribution.

You can see that the products pages shows the search facets: http://demo.commerceguys.com/ck/products

How do I do to show these facets in the First Sidebar of the front page?

If this can't be done, then I think theres a main part missing in this distribution.

Imho the facets search in the products page are great but users are very used to see a main navigation in the left side of the home page, like: http://www.amazon.com/ , http://store.apple.com/us

How can I get this feature? Maybe there is module for this?

I've found this one http://drupal.org/project/commerce_catalog but it seems to be the placeholder for a project...

Facets are built inside blocks. Just go to the admin/structure/block and search for Facet API, click configure on the Facet you would like to display on the front page, scroll to the end of the page and you will see a section Visibility options > Pages and on the right a selection named Show this block under the following pages.

You just have to add the pages where you want the selected Facet API block to appear. For instance if you type collection/*, the Facet will appear under every collection for the user to filter.


Use jCarousel with an Image field? The jCarousel plugin looks like it's mostly used with Views, but I'd like to use it (or something like it) for a simple Image field which has multiple images in it.

Do you know of a way to do this or another module which behaves this way?

For nodes image field you can use Field Slideshow module with your JCarousel
it solves your problem


How to improve the clarity of hierarchical taxonomy terms in edit forms? I have a hierarchical taxonomy vocab. When I go to -say- a node edit form that uses this, with checkboxes, the hierarchy is represented simply by prepending a - for every level of depth. This really does not represent the hierarchy very well - it's hard to see, and ideally it would be semantic (nested list), or at least add a class on the container elements like taxonomy-level-N.

Is there a module for this? Or some other hack?

One way you could approach this is to use select boxes with an 'add more items' button.

I use Simple Hierarchical Select for single value selections in a taxonomy with levels, but there's no reason you can't use it for multiple selections.

If that module doesn't make an 'add more items' button pop up then put the field in a Field Collection, yes even by itself.  I know for a fact that you can have multiples of those.


How can I embed view results right in the content region as if it's part of the content? I have a node type with some entity reference fields that displays teasers.  I also have a block view that takes a URL component to display related nodes that are not referenced on the node's entity reference field.  What I want is for the view results to display right under the entity reference results display as if they were nodes being referenced on the field.  The site is using display suite so there is a two column display.

Try adding Entity Views Attachment (EVA) in your view, then use it as a block-field in DS.


How do I access the user email? I am using Drupal 8 to create a website for training purposes. The user roles are Trainer, Trainee. I have content type session where I get to allocate the trainer for a particular date. It is done by user reference.

By using rules I want to sent notifications to the trainer regarding the scheduled session. But I am not able to achieve this.

Is there any other way I can sent notifications to the trainer other than using Rules module? Please help.

I am not sure if you can send a mail without any custom coding, but you can definitely do this via custom code.
Refer examples module, which has an example on how to send mail.


How to send email to submitter anytime webform modified I have a webform page to submit data from authentic users. The moderator should see this to verify the data. When the moderator changes the submitted data, I want the system send an email to the submitter notifying the data has been changed.

How Can I do that. Is that any additional module(s) to handle that task?

Finally I can send an email to the submitter by using webform rules module.
Event:
After a webform submission has been updated
Condition:
Data selector: form-id
Webforms: select the webform that i use
Action:
Send email:
To: <?php print $data['components']['email']['value'][0]; ?>
From: ...just leave it blank


db_update with a hook Have a field called url_time in the users table.
I have this function in place, though it does not update the table on the else part.

Does this code look correct?

function my_module_form_submit($form,$form_state)
{
global $user;
$account = user_load($user->uid);
$op = $form_state['values']['op'];

if ($op == $form['linkedin']['reset']['#value']) {
    if (db_field_exists('users', 'url_time')) {
        db_update('users')
            ->condition('uid', $account->uid)
            ->expression('url_time', 0)
            ->execute();
    }
}
else {
    $date = time();
    if (db_field_exists('users', 'url_time')) {
        db_update('users')
            ->condition('uid', $account->uid)
            ->expression('url_time', $date)
            ->execute();
    }
}
}

This is the linkedin function that I am trying to implement, so when the user authorities, the "else" will write a date.

function linkedin_user_enable_form($form, $form_state, $uid) {
$form = array();
$form['#user'] = $uid;
$form['#action'] = url('linkedin/token/' . $uid);
$form['submit'] = array(
 '#type' => 'submit',
 '#value' => t('Go to LinkedIn'),
'#suffix' => '
' . t('You will be taken to the LinkedIn website in order to complete the process.') . '
',
);
return $form;
}

This wouldn't delete just the field, it would delete the row for a user whose uid equals $account->uid. The ->expression() and subsequent ->execute() as @kiamlaluno points out, wouldn't work right anyway.

If you want to simply delete the value, you are better off doing something like this:

// $account is defined up ^^ there somewhere.
$account->url_time = '';
user_save($account);


How can I render an entity in a string? Is it possible? To use the viewBuilder of an entity to generate the complete html and save that output into a string instead of sending it to a browser.

It would open the possibility to have email messages render using twig templates.

I have been poking around the different services and using the renderer service I can render the page-specific output as html but I can't find a way to get the complete HTML code into a string.

Matt.

Your question is "render a drupal 8 entity in a string". This is an example how to do this. Get an entity. Get a view builder for the entity node and us it to build your render array with the display mode "full". Render this with renderRoot to the string $html.

$node = \Drupal::entityManager()->getStorage('node')->load($nodeid);
$view_builder = \Drupal::entityManager()->getViewBuilder('node');
$renderarray = $view_builder->view($node, 'full');
$html = \Drupal::service('renderer')->renderPlain($renderarray);

You can do this for any entity. By default this will use the node.html.twig as configured in your theme. But you can change your render array before rendering.

Edit:
For emails use renderPlain().


How to override ViewsExposedFilterBlock with my own class? I want to add an additional form element in the configuration form for core/modules/views/src/Plugin/Block/ViewsExposedFilterBlock.php by adding

public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildConfigurationForm($form, $form_state);
  $form['my_new_form_element'] = [...];

  return $form;
}

If I hack core and add that code in the file, it does what I want. But of course I don't want to hack core. So I'm trying to figure out how to make it so that my custom module's block class is used instead of ViewsExposedFilterBlock.php.

So how do I alert Views to use my class, ExposedFilterImagesBlock.php?

Information that I've found that might help you help me:

ViewsExposedFilterBlock.php has deriver = "Drupal\views\Plugin\Derivative\ViewsExposedFilterBlock" in its annotation. So I'm assuming the deriver plays an important role...just one that is unclear to me.

Thanks in advance for any help you can provide!

Thanks to @4k4 (here) and @nikathone and @dorf (via Slack), I was able to arrive at this, placed in exposed_filter_images.module (all caps should be replaced with a machine name):

function exposed_filter_images_block_alter(&$plugins) {
  if (isset($plugins['views_exposed_filter_block:VIEW_NAME-DISPLAY_NAME'])) {
    $plugins['views_exposed_filter_block:VIEW_NAME-DISPLAY_NAME']['class'] = \Drupal\exposed_filter_images\Plugin\Block\ExposedFilterImagesBlock::class;
  }
}


How to programmatically clear library info definition? Created a dynamic library which attaches some external CSS & JS thru hook_library_info_build hook and this depends on a dynamic config values set by a config form. So whenever that config form saved, how can I make sure the library info is up to date and latest? and users don't have to always do a complete cache rebuild.
Additionally is it possible to clear(or rebuild) just one library definition?

Okay, searching thru core services found this. We can clear all the library definitions like this.
\Drupal::service('library.discovery')->clearCachedDefinitions();

See Drupal Reference of this method: Reference
Calling this function Clears static and persistent library definition caches.


How to make two vocabularies works as section and category for article? So basically i want terms from first vocabulary to work as sections that users can add (movies, for example), and terms from second vocabulary to be fixed amount of categories (like actors, info, screenshots etc), that users can only choose from.

I already made two fields with both vocabularies, but they works separate (site.com/section and site.com/category). Obviously, i want path to look like site.com/section/category. Tried Pathauto, but it works in a different way and can't do such things.

Any suggestions?

I think you can use views with arguments to create this pages.

you should create links manually with l('title', "/{$vocab1_term}/{$vocab2_term}"); in your .tpl.php files associated with this views


Page View not showing on path'd page I'm using Drupal 6 and I'm pretty sure I'm using Views 3. I created a page called All Events (alias: all-events) and created a view that displays as a page. Under Page Settings for the path option I put all-events.

My problem is that I can see the view results in the preview, but whenever I go to the all-events page it is blank save for the title and the one tag I put on there.

If you first created a node whose path is all-events and then created a page view whose path is all-events then the page and the view are competing of the same alias. Just delete your node and your view should display fine.


Load the node as EntityInterface not NodeInterface hook_node_insert(NodeInterface $node) gets a NodeInterface parameter. I need to pass it to
mymodule_node_operations(EntityInterface $entity) which accepts an EntityInterface parameter.
How do I load this node as EntityInterface type? Basically I need to downcast to the parent class which is Entity.
This is the error I get when attempting to pass $node to the function as NodeInterface.

TypeError: Argument 1 passed to mymodule_node_operations() must be an instance of EntityInterface, instance of Drupal\node\Entity\Node given

Node has EntityBase in its hierarchy. EntityBase implements EntityInterface. This means you can pass a Node to a function that expects EntityInterface, since Node extends a class that implements that interface. This is how OOP works, and why classes are type hinted with interfaces (eg. EntityInterface) rather than a specific class (eg. EntityBase).


Headless Web Browser During Cron? I need a headless web browser with JS support to use during cron. It seems like the simpletest module does what I need, but how could one initiate a browser and hand it a DOM?

Outside the context of Drupal cron, it would go like this:

require_once('simpletest/browser.php');

$browser = &new SimpleBrowser();
$browser->get('http://php.net/');

But, is there a way I can use the code that the simpletest module already provides?

If you want a PHP headless web browser, you might look at Mink.

Gherkin/Behat seem to be getting some traction in the Drupal community and in the PHP community more broadly for Behavioral Driven Development.  Mink also supports browser emulation systems (like Selenium), which you typically need in order to interact with Javascript.


Theme shown without styles I executed the config:import: import successfully, but now it seems that the theme settings are no longer found.
The site is now seen as in the attached image

How can I solve the problem?

Note: I don't use bootstrap theme. I imported the configuration I had previously exported from another machine on Ubuntu. This problem is on a Windows machine.

Double check and confirm that the theme files are exactly were they should be.
Make sure the /files directory exists and writable (NOT 777 permissions though)
Double check and confirm that Drupal can access the files directory via configurations
Clear the Drupal cache

If the theme is using external CSS or JavaScript files, make sure they are accessible. (most cases its an internet connection especially for front-end  frameworks like Bootstrap)


Can I add CSS to a YAML generated page ? (Sorry if that's Drupal 101, but I'm still at the very bottom of the learning curve ..)

I have a custom module, with a routing file that redirects to a path that I have chosen arbitrarily :

grefsearch:
  path: 'solr-search/content'
  defaults:
    _controller: '\Drupal\gref\Controller\GrefSearchController::search'
  requirements:
    _permission: 'use gref search'

I have another YAML config which describes the View that must be rendered when accessing to solr-search/content :

langcode: en
status: true
dependencies:
...
page_1:
    display_plugin: page
    id: page_1
    display_title: Page
    position: 1
    display_options:
      display_extenders: {  }
      path: solr-search/content
      cache:
        type: none
      defaults:
        cache: false
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
      cacheable: false
      max-age: -1
      tags:
        - 'config:field.storage.node.body'

Since the page is completely YAML-based, I do not have a Twig template that is linked to it, and because of that, I cannot use hooks like template_preprocess_page because I cannot name the function properly.

I'm a bit lost. Should I change the structure I have, and render the page in a Twig template anyway ?
Thanks !

You can still use the hook_preprocess_page for a specific path like this:

/**
 * Implements hook_preprocess_HOOK().
 * Implements hook_preprocess_page().
 *
 * @param $variables
 */
function mymodule_preprocess_page(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  if ($current_path === '/solr-search/content') {
    $variables['#attached']['library'][] = 'my_module/my-css-library';
  }
}


Add Taxonomy ID class to the body tag (D8) I have a taxonomy vocabulary whose various parents and children need to have different styles. I would need the tid of the every taxonomy page to appear as a class in the body tag in order to make CSS selectors.

I tried using this to work out a solution, but it appears to work only for nodes. I get a class called path-taxonomy for every taxonomy term and that's it.

I would prefer not to install any modules. Thank you

The linked example gets the path. Here better use routing. Check the name of the matched route and then get a parameter which is defined in the route. Normally you use getParameter() to get the loaded entity, in this case it's getRawParameter() for the id:

mytheme.theme:

function mytheme_preprocess_html(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $variables['term_id'] = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
  }
}

html.html.twig:

{%
  set body_classes = [
    term_id ? 'term-id-' ~ term_id,
  ]
%}
<body{{ attributes.addClass(body_classes) }}>


How to add Main Menu to Menu Bar area? This may sound a stupid question but as I have upgraded to D7, my main menu has disappeared and I could not figure out how to move it to corolla's 'Menu Bar' area (or anywhere else) . So appreciate your help.

Menus are not blocks, and as such cannot be placed in regions. Some themes don't render menus on their own, expecting you to place them in a region you prefer. Sounds counter-intuitive, but it can be solved.

To make menu a block, you can use Menu block module.

  It provides configurable blocks of menu trees starting with any level of any menu. And more!

Alternatively, you could use Nice Menus module:

  Nice Menus creates blocks that may be associated with any existing site menu which can be placed wherever normal blocks can be placed in a theme

Blocks the two modules are generating are different, but both can do the job. Test which one is better handled by your theme, and if both are good, use the one you simply prefer.


Connect multiple AD's to one site Is it possible to connect 2 AD's to drupal intranet to have single sign on (with the LDAP module)?

thank you in advance

Yes you can. After installing the ldap module:

Set up the two servers via: admin/config/people/ldap/servers
Set up authentication via: admin/config/people/ldap/authentication. Make
sure to "Check all LDAP server configurations to use in authentication."
Do your other settings as per your requirements.


How to print a block inside the node body? I need to insert a block(webform) inside basic page nodes (wysiwyg body).
How can do it?

Try to use Insert Block module. It has Drupal 8 version


How to add a new CSS class to a Drupal7 ? Hello I created the following form iterating for each node:

...
$render['my_list'][] = drupal_get_form('shop_form_item_'.$node->nid, $node->nid);
...

$render will output the form on the page. The forms will be shop-form-item-20, shop-form-item-21 etc...

function shop_forms($form_id, $args) {
  $forms = array();
      if(strpos($form_id, 'shop_form_item_') === 0) {
        $forms[$form_id] = array('callback' => 'shop_form',);
      }
  return $forms;
}

function shop_form($form, &$form_state, $nid) {
  $form = array();

    $form['my-item-name'] = array(
    '#type' => 'hidden',
    '#title' => t('Name'),
    '#value' => isset($node->title) ? $node->title : '',

  );

  return $form;
}

Now I need to add a class: <form method="post" action="" class="cart">
How do I insert it?

Thanks

You need to add it to the #attributes key of the $form array:

function shop_form($form, &$form_state, $nid) {
  $form['#attributes']['class'][] = 'cart'; // Classes are added to an array and internally converted to a single string by Drupal later on

  $form['my-item-name'] = array(
    '#type' => 'hidden',
    '#title' => t('Name'),
    '#value' => isset($node->title) ? $node->title : '',
  );

  return $form;
}


When should field_attach_load be called manually? I'm trying to use the module ClosedQuestion together with EntityCache.
When I enable EntityCache, then the fields on my CQ nodes becomes duplicated. I believe the cause is that both EntityCache, and ClosedQuestion, calls field_attach_load on the nodes.

There's a specific issue here, about this problem, but I'm looking for more general information, about what is the intended usage of field_attach_load? I've never seen a module doing it manually before, and don't think it's supposed to be used like this.

api.drupal.org says:

  field_attach_load() is automatically called by the default entity
  controller class, and thus, in most cases, doesn't need to be
  explicitly called by the entity type module.

Basically only call it if you're implementing an entity type and don't want to use the default entity controller. I'm pretty sure ClosedQuestion is in the wrong, since it's only making a node type. All fields should be attached by the time hook_load() comes along.


How to override "action" of a form? after a form submission I want to redirect to an url. The "action" attribute of the form is ['#action']=homepage. How can I override this?

I have used this code

function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='views-exposed-form-job-search-search-page') {
    global $base_url;
    $form['#action'] = $base_url.'/search/job';
  }
}

However it doesn't work, it still redirects me to /homepage. What am I missing?
Thanks

The $form_id argument is the internal form ID, not the CSS ID. For views exposed forms it'll always be views_exposed_form.

I think this is the easiest way to target a specific exposed form:

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $view = $form_state['view'];
  if ($view->name == 'foo' && $view->current_display == 'bar') {
    // Alter the form...
  }
}


How to activate "Add existing field"? In the section called Manage fields within a content type, there is an option called Add an existing field. How this field is activated?

Some time ago I installed Drupal 7.38 and I worked with such option. This option was there. I never knew how it appeared there.

Now, I have two new Drupal installations (7.38 and 7.40). None of them shows by default the option called "Add an existing field".

Does the option "Add an existing field" belong to Drupal core or to some contributed module?

Add an existing field is belong to Drupal core only.

You are not getting the option to Add an existing field because you have not created any field as of now. You cannot add an existing field until you have created it as a new field first. After you have created the new field, you can attach that field to multiple content types using Add an existing field

The Drupal.org documentation does not recommend that you re-use fields:

  "It is recommended to create new fields, rather than reusing existing
  ones, unless you have a clear reason to do so".


standalone rsync and ssh work, but drush gets me a "Permission denied (publickey)" I've got a production site (on shared hosting for now) of which I just want to have backups at this stage. and I've got a backup instance which I want to overwrite with the prod site.

This is my /etc/drush/aliases.drushrc.php:

<?php
$aliases['bak'] = array(
        'root' => '/var/www/',
        'uri' => 'testvm',
        'db-url' => 'mysql://user:pass@localhost/drupal',
        'path-aliases' => array(
        '%dump' => '/var/bak.sql',
        '%files' => '/var/drupal_files',
      )
);

$aliases['prod'] = array(
        'root' => 'livesite.com:/home1/ruser/public_html/',
        'uri' => 'livesite.com',
        'db-url' => 'mysql://ruser:pass@localhost/drupal_drp3',
        'remote-user' => 'ruser',
        'path-aliases' => array(
        '%dump' => '/home1/ruser/prod.sql',
        '%files' => '/home1/ruser/drupal_files',
      )
);
?>

And all I'm getting through drush is:

Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [Receiver]
rsync error: error in rsync protocol data stream (code 12) at io.c(605) [Receiver=3.0.9]
Could not rsync from livesite.com:/home1/ruser/public_html// to /var/www/        [error]

Even though I can rsync/ssh/scp with no issue to and from the live site. Certificates are in place, and working fine, but not for drush...

What I'm not seeing here???

PS I've seen What could cause remote drush commands to fail with ssh errors when ssh works in all other cases?, but the accepted answer does not make any difference for me.

Update:

I was using drush as root, so I tried creating a local user with same name as the remote user. I chowned the backup instance to the remote user.

ruser@drupal:~/.drush$ drush -v rsync @prod @bak
$options['ssh-options'] = '-o PasswordAuthentication=no -i /home/ruser/.ssh/id_rsa';

Loaded alias @prod from file /etc/drush/aliases.drushrc.php [notice]

Loaded alias @bak from file /etc/drush/aliases.drushrc.php [notice]
You will destroy data from /var/www/ and replace with data from livesite.com:/home1/ruser/public_html//
Do you really want to continue? (y/n): y
Calling system(rsync -e 'ssh ' -akzv --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --exclude="settings.php" --stats --progress livesite.com:/home1/ruser/public_html// /var/www/);
receiving incremental file list
rsync: failed to set permissions on "/var/www/.": Operation not permitted (1)
rsync: failed to set permissions on "/var/www/.htaccess": Operation not permitted (1)
./

Number of files: 14547
Number of files transferred: 0
Total file size: 92209263 bytes
Total transferred file size: 0 bytes
Literal data: 0 bytes
Matched data: 0 bytes
File list size: 313420
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 1017
Total bytes received: 316801

sent 1017 bytes  received 316801 bytes  42375.73 bytes/sec
total size is 92209263  speedup is 290.13
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1536) [generator=3.0.9]
Could not rsync from livesite.com:/home1/ruser/public_html// to /var/www/ [error]
Command dispatch complete

This user has certificates in place in the live site as well. But still no luck...

You are not specifying a remote-user on @bak so who are you performing operations as on the server at @bak? You are also not specifying any ssh config options. In this case, you are asking @bak to authenticate with @prod via ssh/rsync but you are not using agent forwarding so @prod can't see your private key. Try specifying something like

'remote-user' => 'user_on_bak',
'ssh-options' => '-T',

So that drush will execute as 'user_on_bak' and ssh will pass along your local key to @bak so when it opens a session with @prod it will have a key to pass along.


Feeds Importer Filters I would like to import some nodes from csv file using feed_import module in Drupal 7.
The original CSV file has around 500k entries and I have to do some filtering before importing. (the result will be under 40k).

Now, I have seen on drupal.org that feed_import has the possibility of adding some filters, but I cannot find the way to apply them.

Anyways I haven't seen nothing about the lenght of the field or about the type of content (numeric, alphanumeric, letters only), and I have to filter on these criteria.

Can that be made? Or should I try to do the filtering in PHP before using feed_importer?

You can create a new module and implement the hook_feeds_presave() function like the following example:

function hook_feeds_presave(FeedsSource $source, $entity, $item) {
  // create your filter conditions here
  if ($entity->feeds_item->entity_type == 'node') {
    // Skip saving this entity.
    $entity->feeds_item->skip = TRUE;
  }
}


Print admin toolbar icon in custom module How can I print the admin toolbar icon for my module?

I created a module and it has a menu in the admin toolbar. I want to show an icon (module/costum_module/image/00/icon.svg) in this path for my admin toolbar tab.

I created a CSS style for that, but it doesn't work.

Module path :

/module/my module/css/styles.css   =>

.toolbar-icon-mymodule-list:before {
    background-image: url(../icons/787878/icon.svg);
}
.toolbar-icon-mymodule-list:active:before,
.toolbar-icon-mymodule-list.active:before {
    background-image: url(../icons/000000/icon.svg);
}

/module/my module/mymodule.libraries.yml   =>

mymodule.styles:
  css:
    theme:
      css/styles.css: {}

If you want to add svg icon for your menu link item in admin toolbar, you have to alter toolbart.

In your mymodule.libraries.yml file

toolbar:
  version: VERSION
  css:
   theme:
    css/styles.css: {}

And you need to implement hook_toolbar_alter() in your mymodul.module

function mymodule_toolbar_alter(&$items) {
  $items['administration']['#attached']['library'][] = 'mymodule/toolbar';
}


Attach different CSS styles on a node basing on publishing date or other PHP properties I want to attach a different CSS style to a node, basing on the node publishing date or some PHP properties.
What would be the best way to do this?

You are asking the wrong question. The question you should have asked is "how do I add a class on a node depending on some properties?". Using different set of CSS files to control styling a an element is just a no-no.

The answer to the correct question depends on whether you are targeting Drupal 6 or Drupal 7:

On Drupal 6, you will generally have to implement the logic your own node template;
On Drupal 7 (or on Drupal 6 if you are using an intelligent base theme like Zen), you would implement a hook_preprocess_node() in your theme and add classes to the 'classes_array' variable


How can I remove Javascript files? I wanted to remove some JavaScript files, since they conflict with my custom JavaScript on my mobile theme.

I tried with the following code, but it is not working in hook_preprocess_page(), which I think it really works in the first place; it's just that the original initialization of $scripts in page.tpl.php loads after hook_preprocess_page() alteration.

// Load all js scripts
    $scripts = drupal_add_js();

  // Unset all unnecessary scripts
    unset($scripts['module']['sites/all/modules/ajax/ajax.js']);
    unset($scripts['module']['sites/all/modules/contribs/mollom/mollom.js']);
    unset($scripts['module']['sites/all/modules/contribs/views_slideshow/js/jquery.cycle.all.min.js']);
    unset($scripts['module']['sites/all/modules/contribs/views_slideshow/contrib/views_slideshow_singleframe/views_slideshow.js']);
    unset($scripts['module']['sites/all/modules/contribs/views_slideshow/contrib/views_slideshow_thumbnailhover/views_slideshow.js']);
    unset($scripts['module']['sites/all/modules/quicktabs/js/quicktabs.js']);
    unset($scripts['module']['sites/all/modules/panels/js/panels.js']);
    unset($scripts['module']['sites/all/modules/tipsy/javascripts/jquery.tipsy.js']);
    unset($scripts['module']['sites/all/modules/tipsy/javascripts/tipsy.js']);
    unset($scripts['module']['sites/all/modules/boxes/boxes.js']);

    // Recreate the template variables

    $vars['scripts'] = drupal_get_js('header', $scripts);

How can I remove JavaScript files from the list of JavaScript files load when my theme is used?

This how solved my problem.

Found out that jquery_update uses hook_theme_registry_alter() to unset jquery in Drupal core and replace a new version of Jquery. So this preprocess function is being load after everything all. What I did is I created a hook_theme_registry_alter() and update the weight of the module higher than jquery_update module so I can override the jquery_update_theme_registry_alter().

This jquery_update_theme_registry_alter() prevents any alteration in javascript which a big headache if you're working on some adjustments like in my case.

Code:

function my_module_theme_registry_alter(&$theme_registry) {
    global $theme;

    // Only apply this code in mobile theme
    if($theme == 'myTheme') {
    //Attach the my_module_preprocess_page in the theme registry preprocess functions
      $theme_registry['page']['preprocess functions'][] = 'my_module_preprocess_page';
    }
}

function my_module_preprocess_page(&$variables) {

    // Perform the logic if either jQuery Update's jquery.js is newer than core's.
    if (variable_get('jquery_update_replace', TRUE)) {
        // Get an array of all the JavaScript files loaded by Drupal on this page.
        $scripts = drupal_add_js();

        // Replace jquery.js first.
        $new_jquery = array(jquery_update_jquery_path() => $scripts['core']['misc/jquery.js']);
        $scripts['core'] = array_merge($new_jquery, $scripts['core']);
        unset($scripts['core']['misc/jquery.js']);

        // Loop through each of the required replacements.
        foreach (jquery_update_get_replacements() as $type => $replacements) {
            foreach ($replacements as $find => $replace) {
                // If the file to replace is loaded on this page...
                if (isset($scripts[$type][$find])) {
                    // Create a new entry for the replacement file, and unset the original one.
                    $replace = JQUERY_UPDATE_REPLACE_PATH .'/'. $replace;
                    $scripts[$type][$replace] = $scripts[$type][$find];
                    unset($scripts[$type][$find]);
                }
            }
        }
        // Unset javascripts that is/are not needed in mobile theme
        unset($scripts['module']['sites/all/modules/boxes/boxes.js']);

            .....

        // Recreate the scripts variable
        $variables['scripts'] = drupal_get_js('header', $scripts);
    }
}

Hope this will help others. Please let me know if this approach is a violation. Thanks


How can I access a node's menu link and weight through EntityFieldQuery In D7, I'm trying to set up a custom menu that is ordered by the weight of the node->path ("weight" field in table menu_links). How can I access the node's path's weight value in my query so it can be ordered correctly? This is what I had but was shot down very quickly:

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_meeting', 'value', $meetid, '=')
    -> propertyOrderBy('weight','ASC')
    ->addMetaData('account', user_load(1)); // Run the query as user 1.
    $result = $query->execute();

I ended up using db_query JOIN to get the info straight from the database:

$sql = "SELECT menu_links.link_path, menu_links.link_title, menu_links.weight, node.nid
        FROM menu_links
        JOIN node.nid
        ON menu_links.link_path LIKE CONCAT('node/', node.nid)
        ORDER BY menu_links.weight ASC";
$result = db_query($sql);


Drupal 7 update field programatically and generate field names I'm here still learning with drupal 7 but now I have a new question about a node create programmatically,I hope you can help me.

I want to generate all node fields names programmatically and then set a lavue on each one.

To store each field from node I generate the names of the field witn an array with each name, this is because I want to make  function to indicate the names of the fields of the node that I want to fill.

The problem is that my code is not working to fill the nodes, maybe because my fields names are bad generated. I generate and fill them this way:

    $nodefields = array('areaid', 'areaname');

    foreach ($nodefields as $fieldname) {
            $node->$fieldname['und'][0]['value'] = $row->$fieldname;
            }
    node_save($node);

The rows are obtained by a query to a external db (column has the same name as the field), that's fine, the records are ok, if I fill them manually like:

$node->areaname['und'][0]['value'] = $row->$areaname;

Works ok, but I can't make it work with a loop to generalize that part.

Your problem is that below code does not work as you probably expect.

$node->$fieldname['und'][0]['value'] = $row->$fieldname;

You expect this to work like this:

$fieldname = 'name';
$node->name['und'][0]['value'] = $row->name;

but PHP will probably do something like this:

$fieldname = 'name';
$fieldname['und'][0]['value'] = $row->name;
$node->$row->name;

Instead, try to wrap your variable name in curly brackets to have it replaced first:

$node->{$fieldname}['und'][0]['value'] = $row->$fieldname;


How to add a functionality to views bulk operations? I want to use Views bulk operations to be able to change all my products' taxonomy terms at once.

I have my product managing view with views bulk operations set up and working but there is no operation for editing taxonomy terms under "Modify entity values".

I assume it is possible to add this functionality, but I'm not sure how, any suggestions?

VBO comes, out of the box, with some predefined (hardcoded) operations that can be applied to each row selected in the view. The available operations are shown within "Selected bulk operations" when configuring the VBO field. Obviously, something like Edit taxonomy terms isn't one of them.

However using Rules (Conditions and/or Actions) you can execute a VBO operation which you define using a Rules Component. To get the idea, have a look at the video about Using Rules components with VBO" uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video. This video actually shows how to (also) add a term to a node, so it should be pretty forward to use a similar technique.

For an example in which this technique is used, refer to the answer to "How to implement the mass operations on the Group's members page using Views?".

Note: to process thousands of nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!


Add class to content field (link) I want to add a class to the <a> tag of a field that consists of a link and  text. (It's a field of type Link.) The name of the field is content.field_c_button_link.

In the template file, I want to add something like the following.

{{ content.field_c_button_link.0.addClass('button blue') }}

How can I add a class properly?

According to Patrick Scheffer's answer, I looked at the settings for a field where I can add extra CSS classes, but I could not find any. This is a screenshot of what I can edit in the link field.

This is a solution I found, but it isn't really handy to use... I really want a better solution, like something directly from twig templates.

function template_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  if ($element['#name'] == 'field_c_button_link') {
    $variables['items'][0]['content']['#options']['attributes']['class'][] = 'button';
  }
}


How do I access the configuration variables present in settings.php through my code? I want to access the variables present in the settings.php in my custom module. For example, if the settings.php file contains the $config['test']['uid'] = 'ABC'; line, I want to access the content of $config['test']['uid'] in a controller.

How can I achieve this?

You can only override configuration values in settings.php, you cannot introduce new configuration. So the values you have tried to set there cannot be accessed, unless you happen to have configuration named test.uid. But I suspect that probably does not exist.


How to bulk update text filter format on fields in drupal 7 I have multiple fields across my site, and multiple text filters. I need to delete one of the filters, but I know that it will result in users getting that whacky permission denied error when they try to edit the field.

Is there a way to bulk update all fields input filters? I started looking at field_update_field in the field CRUD api, but I'm at a loss.

Turns out this was solved in a different question, the answer is below:

Try this way, by making a loop for all nodes of certain type:
$node = node_load(nid);
$node->body[$node->language][0]['format'] = 'full_html'; // plain_text
node_save($node);

Kudos to Ek Kosmos for sorting this out.


How do I render my module content? I have followed the "hello world" module tutorial at https://www.drupal.org/developing/modules/8.  At the end of the tutorial, you create a custom page which gets generated from a render array you created in the module's controller.  The content is a single line of text, contained in the #markup field in the render array.

Now I'm trying to go beyond and create a more complex page, with some ajax-enabled elements.  Hard-coding a bunch of HTML and Javascript into the #markup field does not seem to be the way to go.  And looking through other modules, I see that most do not have a #markup field, but a bunch of other fields, some of which seem to be custom fields (possibly adhering to an unknown naming convention), and others which appear to be defined by Drupal core.  But in some cases it's not clear which are which, and after hours of searching the Drupal documentation and the wider internet, I cannot find a clear explanation of how the different fields in the array are interpreted and translated into HTML.  (It seems that "theme hooks" may be involved somehow, but it's not clear to me which hooks are needed or where those hooks should be defined)

Can someone provide or point me towards an explanation of how to get to a desired HTML layout and set of javascript behaviors using render arrays?

Drupal is build and designed around the idea that the markup produced by a module is themable (ie. it can be changed by a theme independently of the module). Which mean that markup for a page is usually build using Drupal theming system. Basically, you define templates then use them in your render arrays. In your render arrays, #theme define the used templates, almost ever other entries are specific to the templates and used to inject variables into the template or its preprocess functions.

To add CSS and JavaScript you need to attach them to your render arrays with #attached as assets libraries, see the Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module documentation for details. This is used to allow Drupal core and other module to optimize inclusion of the CSS and JS files into your page.


Scald: themable atom reference – where to find image path etc.? I can't find a way how to get an atom reference's values (image path etc.) into my theme template. When printing the node array I do get the SID for the referenced image, but I just don't know how to load the actual details.

Or is it possible by simply using node_load or entity_load or the like? Any pointers gladly appreciated.

Found the answer to my question one of scald's issue pages – and it's not really complicated. Either it's just not well documented, or I just didn't see it:

This gets the SID from the node's array:

$img = $vars['node']->field_teaser_image['und'][0]['sid'];

And this fetches the atom reference's object:

$atom = scald_atom_load($img);

This is how I then load the title of the atom reference image inside template.php:

$vars['img_title'] = $atom->title;

And the actual filename is inside another object base_entity:

$vars['img_filename'] = $atom->base_entity->filename;

Hope this may help somebody some day.


Making sure edits work as intended before publishing I just wanted to pre-empt a situation that is highly likely to occur at some point in the future. I am going to be hosting a small online business using shared hosting. Obviously, once the website (which uses Drupal) is finalized and I take it out of maintenance mode, I want to keep it usable 99.99%. However at some point of time, I'll  probably wish to make some edit, add content or even make some reforms that will need some thorough testing. I know that there is a preview button but for some alterations this may not be enough, but I'd still like to avoid putting the site in maintenance. (Although for fixing bugs and critical updates I obviously would).

I'd appreciate your suggestions on how I could do this please. I assume it must be a common issue among online businesses?

The more or less standard solution is to maintain a so-called staging site (i.e. a mirror of your production site, but in a protected environment), and make all changes to the staging site before committing them to the production site.

The use of a staging site is not only limited to edits, but is also very useful when making more substantial changes, such as updating a module or adding a new module.  The staging site let you run detailed tests to make sure that changes does not "break" anything before committing to the main site.

You can use drush to simplify syncing content and configuration between the staging and production site.

Edit: By "protected environment", I mean some computer that is not available to outsiders on the Internet. It is typically only available for use by yourself (and your team if you're not working alone, but manage a team of developers). The standard way of protecting it is to use a firewall and only allow connections from the IP-addresses belonging to you (and your team members)


How do you use forms to populate content type fields? Drupal 7. Custom module.
I have a content type 'RFI' with a handful of fields I created with Drupal UI. I want a user to: fill out a form & click submit while drupal: saves fields to database, creates a new node of 'RFI' and populates the fields of the node with the content provided by the form's corresponding fields.

From what I understand:

Build a form with fields (taking from the 'DBTNG examples' module just for clarity):

function rfi_build_form($form, &$form_state) {
$form = array();

$form['add'] = array(
'#type'  => 'fieldset',
'#title' => t('Add a person entry'),
);
$form['add']['name'] = array(
'#type'  => 'textfield',
'#title' => t('Name'),
'#size'  => 15,
);
$form['add']['surname'] = array(
'#type'  => 'textfield',
'#title' => t('Surname'),
'#size'  => 15,
);
$form['add']['age'] = array(
'#type'  => 'textfield',
'#title' => t('Age'),
'#size'  => 5,
'#description' => t("Values greater than 127 will cause an exception. Try it - it's a    great example why exception handling is needed with DTBNG."),
);
$form['add']['submit'] = array(
'#type'  => 'submit',
'#value' => t('Add'),
);
return $form;
}

Here the form fields are saved to database with database API.

function rfi_build_submit($form, &$form_state) {
global $user;

// Save the submitted entry.
$entry = array(
'name'    => $form_state['values']['name'],
'surname' => $form_state['values']['surname'],
'age'     => $form_state['values']['age'],
'uid'     => $user->uid,
);
$return = dbtng_example_entry_insert($entry);
if ($return) {
drupal_set_message(t("Created entry @entry", array('@entry' => print_r($entry, TRUE))));
}
}

Now here is how I know how to create a node of RFI type. How do I take the values of the fields above [name], [surname], [age] and have them related to corresponding fields in my content type?

function rfi_build_type($form, &$form_state){
$node = new stdClass();
$node->type = 'rfi';
$node->name = '';
$node->surname = '';
$node->age = '';
$node->language = 'en';
$node->uid = 1;
node_save($node);
}

I was thinking that since the fields have been saved already, that I could use a database query to get these values, but intuition tells me I'm overlooking something.

Thank you!

You seem to be going in a slightly wrong direction with this (until I'm missing or not understanding something). If your goal is to create a node based on the data users send via a custom form then it can be done in the form submit handler. Fields added via the GUI don't need separate handling. For example if you are using node_save() then adding a custom field value could look similar to this:

$node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled.
$node->field_name[$node->language][0]['value'] = $form_state['values']['name'];

and with drupal_form_submit():

$new_form_state['values']['field_name'][$node->language][0]['value'] = $form_state['values']['name'];

There's a solid amount of information available about this on the web that you might want to check out for further assistance (like this, this and this).


How to change values views exposed filter based upon view results? I have a view which, in addition to showing event nodes, also shows "fake" event nodes.  The "fake" event nodes are inserted in hook_views_pre_render().

The view also has an exposed filter to filter out content tagged with a certain term ID on the event_type field.  The exposed filter list has gotten too large so now it would make sense to only show the terms in the list that can filter out the view results (including the "fake" events).

Now I tried this with hook_form_alter(), but the problem is that the "fake" event nodes aren't available by using views_get_view_result() and I'm not sure what other function could be used to do that here.

I tried using dpm($view); in hook_views_pre_render(), hook_views_pre_build(), and hook_views_pre_view(), but I could not find how to change values in the exposed filter in any of those.

Where can I see the values of the view result at the same time as the value options in the exposed filter?

Here is sample exposed filters form altering: http://www.tylerfrankenstein.com/code/drupal-alter-views-exposed-filter-form

Maybe you can call a function which returns fake nodes twice?

So in hook_views_pre_render():

$fake_events = get_fake_events();
add_fake_events_to_rows($view->result);

and calling it in hook_form_alter() too:

$fake_events = get_fake_events();

Any problems with working that way?


Meta tags aren't saved with all content types I use the module Meta Tags for adding meta data to my nodes. And it works like a charm. It's super easy to add meta tages like title, keywords, description,... even our IT-noob marketing team can do so. It's awesome.

However, not all content types seems to be able to save those meta data. I've got 12 content types and 3 of them don't display the meta data. Although I add them like on the other nodes...

Here is the source code of a node without any meta:

And here with meta:

So correct me if I'm wrong, but I don't see any meta data in the first example.

Strange part, all the data is present in the database (table metatag), so all nodes does save the meta data, but for some reason, some content types aren't displaying the meta data.

What could be the cause of this "bug". Could it be something like hiding certain content in the template files since they all have a separate .tpl.php file? Or what other causes are you thinking of?

There is an issue with the module.

Try the following code in node.tpl.php.

render($content['metatags']);

Alternatively, try with the following code in page.tpl.php.

print render($page['content']['metatags']);


Make label translatable in Global: Custom Text field I'm using Drupal 7 and I have a Global: Custom Text in my view

Label

[title]

[category]

When I try to translate the 'Label' from

`Configuration » Regional and language » Translate interface`

I get an error 'The submitted string contains disallowed HTML'.
That is because the label is wrapped in a div. I could add the div in include/locale.inc in the function

`locale_string_is_safe($string)`

but I don't think is a good idea to edit the Drupal core.

Do you have any better solution?

Use hook_views_pre_view and set your global header programmatically.
E.g.

$view->set_item_option($view->current_display, 'header', 'area_text_custom', 'content', $header);


How does data propagate from the formElement of a Widget to the properties of a FieldItem? Here is my custom Widget:

<?php

namespace Drupal\scripture\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

use Drupal\my_module\Plugin\Field\FieldType\MyFieldItem;

/**
 * Plugin implementation of my custom widget.
 *
 * @FieldWidget(
 *   id = "my_widget",
 *   label = @Translation("My Widget"),
 *   description = @Translation("A Widget belonging to me"),
 *   field_types = {
 *     "my_field_type"
 *   },
 *   multiple_values = FALSE,
 * )
 */
class MyWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $element['#type'] = 'fieldset'; // just to show the title and put a nice frame around it

    $element['verse'] = array(
      '#type' => 'verse_picker', // This is a custom Element defined elsewhere.
    );

    /** @var MyFieldItem $item */
    $item = &$items[$delta];

    // If the item is not empty, populate the form element
    if (!$item->isEmpty()) {
      // ...
    }

    return $element;
  }

}

And here is my custom FieldType:

<?php

namespace Drupal\scripture\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of my field type.
 *
 * @FieldType(
 *   id = "my_field_type",
 *   label = @Translation("My field Type"),
 *   description = @Translation("A FieldType belonging to me."),
 *   default_widget = "my_widget",
 *   default_formatter = "my_formatter"
 * )
 */
class MyFieldItem extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    // Prevent early t() calls by using the TranslatableMarkup.
    $properties['from'] = DataDefinition::create('integer')
      ->setRequired(TRUE);

    $properties['to'] = DataDefinition::create('integer')
      ->setRequired(TRUE);

    $properties['abbr'] = DataDefinition::create('string')
      ->addConstraint('Length', [
        'max' => 8,
      ])
      ->setRequired(FALSE);

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = [
      // ...
    ];
    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    return empty($this->get('from')->getValue()) || empty($this->get('to')->getValue());
  }

}

Whenever I save a field, the properties stay NULL. Even when I use xdebug to inspect every call to isEmpty(), $this never has any populated properties. How does the user input get from the form element to the field item's properties? I could not find Drupal documentation on the matter.

submitForm() of the content entity form calls via several other methods (which you find in the call stack) this method of the field widget, which then sets the values of the field items.

WidgetBase::extractFormValues():

  public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state) {
    $field_name = $this->fieldDefinition->getName();

    // Extract the values from $form_state->getValues().
    $path = array_merge($form['#parents'], [$field_name]);
    $key_exists = NULL;
    $values = NestedArray::getValue($form_state->getValues(), $path, $key_exists);

    if ($key_exists) {
      // Account for drag-and-drop reordering if needed.
      if (!$this->handlesMultipleValues()) {
        // Remove the 'value' of the 'add more' button.
        unset($values['add_more']);

        // The original delta, before drag-and-drop reordering, is needed to
        // route errors to the correct form element.
        foreach ($values as $delta => &$value) {
          $value['_original_delta'] = $delta;
        }

        usort($values, function ($a, $b) {
          return SortArray::sortByKeyInt($a, $b, '_weight');
        });
      }

      // Let the widget massage the submitted values.
      $values = $this->massageFormValues($values, $form, $form_state);

      // Assign the values and remove the empty ones.
      $items->setValue($values);
      $items->filterEmptyItems();

      // Put delta mapping in $form_state, so that flagErrors() can use it.
      $field_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
      foreach ($items as $delta => $item) {
        $field_state['original_deltas'][$delta] = isset($item->_original_delta) ? $item->_original_delta : $delta;
        unset($item->_original_delta, $item->_weight);
      }
      static::setWidgetState($form['#parents'], $field_name, $form_state, $field_state);
    }
  }


How do I create custom regions in a theme? I want to add a new area which will be site wide. Describe the process of getting this new region into my theme, if possible generalize it for adding any new, custom region.

You define regions in your theme .info file. See: Structure of the .info file

You then need to put the relevant template tags in your page.tpl.php file.

So for example if you defined the region sidebar in your themes .info file, you would then add: <?php print render($page['sidebar']); ?> to the relevant place in your page.tpl.php.


Are ids strictly sequential i.e. does later added content always have higher id? I thought that ids (user id, node id, ...) are strictly sequential which ensures that later added content has always higher id that a previously added one. So that when I have a hierarchy (lower element has a reference to its parent) and the 'reference' is not editable (set on creation) I can safely assume that a child has higher id that a parent.

The problem is that in this question @berdir (who I believe knows a few things about Drupal) says that it does not have to be the case...

I know that gaps might appear in the sequence (e.g. when an entity is deleted) but I'm not sure that he meant just that (and I'd rather be sure).

So my question is, how is in reality and when can I not the sentimentality of ids?

//DISC: The hierarchy system is quite complex and (of course) doesn't rely on ids comparison, the aforementioned concept is used just in one case due to optimization.

User IDs and Node IDs are automatically incrementing (mysql, postgresql, sqlite) fields. Once an id has been used, it should not be used again (in the case of deleted content).

The higher the number, the later it was inserted into the database.

You could always end up with imported content that is older, but now has a higher Node/User ID because it was inserted at a later time.

You may want to look to the Relation module, or even Drupal's own menu system to define hierarchies.  This depends completely on your use case of course.


File widget custom upload location I am working on a custom module (based on Model project) with a file field attached to my custom entities, now I would like to save files in certain directories according to entity id eg:

public://files/my_custom_entity_ID/filename

I've tried with hook_file_insert but can't get the entity id in order to use it later in file_move.

Which hook (if any) should I use? Or I am missing the whole approach?

Assuming D8

If this is part of a "BaseFieldDefinition" of your own entity, you may set a lot of options like so:

// create photo
$fields['photo'] = BaseFieldDefinition::create('image')
    ->setLabel("Photo")
    ->setDescription('Ein Photo')
    ->setSettings(array(
        "file_directory" => 'profilbilder/[date:custom:Y]-[date:custom:m]',
        "file_extensions" => 'png gif jpg jpeg',
        "max_filesize" => '600 KB',
        "max_resolution" => '600x800',
        "min_resolution" => '30x40',
        "alt_field" => false,
        "alt_field_required" => false,
        "title_field" => false,
        "title_field_required" => false,
    ))
    ->setDisplayOptions('form', array(
        'type' => 'image_image',
        'weight' => 5,
    ))
    ->setDisplayOptions('view', array(
        'type' => 'image',
        'weight' => 1,
        'label' => 'hidden',
        'settings' => array(
            'image_style' => 'thumbnail',
        ),
    ));

As you see, you can use tags in the file_directory setting.
If you craft your fields using the Drupal 8 field UI, you can also use tags in the UI field.

If it's D7, you should change to D8 :-)