Language switching does not work when browser language is configuired in drupal 8.3.7 Language switching fails after enabling browser on  Detection and selection

  /admin/config/regional/language/detection

Exisiting :

On switching language from the browser the url changes but the content remains the same

E.g, Default language browser is Germen.

mywebsite.com mywebsite.com/about etc shows German content.

While swiched to English url changes to mywebsite.com/en mywebsite.com/en/about etc

It shows Germen content instead of English.

Expected

On browser configured with Germen as default language, the site url should be mywebsite.com/de.

When I swich to the English website, it should show English content

Please find the configuration.

It is very obvious why this is happening. Language selection process the language detection systems from top to bottom. (Top has highest priority.) Your configuration means that the browser will always be selected first and that url and user settings are ignored.

If you move browser below user (drag with the arrows icon), the processing order will be:

url
user (if url resolved no language)
browser (if user had no language configured)

I have fixed the  issue with htaccess.Please refer this code,it may be helpful for similar issues.

  ## On frontpage redirect to /de if the browser language start with de
  RewriteCond %{HTTP:Accept-Language} ^de.*$ [NC]
  RewriteCond %{REQUEST_URI} ^/$ [NC]
  RewriteCond %{QUERY_STRING} !(^q\=) [NC]
  RewriteRule ^(.*)$ /de [L,R=302]

  ## On frontpage redirect to /en if the browser language start with en
  RewriteCond %{HTTP:Accept-Language} ^en [NC]
  RewriteCond %{REQUEST_URI} ^/$ [NC]
  RewriteCond %{QUERY_STRING} !(^q\=) [NC]
  RewriteRule ^(.*)$ /en [L,R=302]

  ## To make all other requests (that is, URLs not starting with /en/ or /de/) redirect to a default language (say en)
  RewriteCond %{HTTP:Accept-Language} () [NC]
  RewriteCond %{REQUEST_URI} ^/$ [NC]
  RewriteCond %{QUERY_STRING} !(^q\=) [NC]
  RewriteRule ^(.*)$ /en [L,R=302]


User's homepage depending on their organic group Is there a way to set the homepage of a user depending on their organic group. So when a user clicks the site logo, they will be redirected to something like /test-page/%group. When I created a panel page it specified that I could not use % which would have been perfect.

I am using Drupal 7.

There is a module (Frontpage) that allows to set a different front page for anonymous users, and authenticated users.

The module allows third-party modules to alter the page to which the users are instead redirected, or to alter the structure array used to render the page.

As alternative, you can create a custom module that, using code similar to the one used by Frontpage, redirect users to a specific page, basing on specific criteria.

The module should implement hook_menu() and associate a menu callback to, for example, http://example.com/frontpage; the page callback of that menu item should simply verify a condition is verified, and then redirect the users to a specific URL.

The code skeleton could be something similar to the following:

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  $items['frontpage'] = array(
    'page callback' => 'mymodule_frontpage_view',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function mymodule_frontpage_view() {
  // These variables can be useful to redirect the users
  // to specific pages, basing on the language currently set for
  // the content, or on the fact the user is logged in.
  $langcode = $GLOBALS['language_content']->language;
  $logged_in = user_is_logged_in();
  $usergroups = og_get_groups_by_user($user);
  $group = og_load($gid);
  $groupnode = $group->etid;
  $redirectpath = 'node/'.$groupnode->nid;
  drupal_goto($redirectpath);

}

There is programmatical way to do this and even more :) Drupal 7, actual code called from page.tpl.php

    //get unique user id
    $user_id = $user -> uid;
    //get id-s of groups where user is a member, from og_membership drupal table
    $og_check = db_select('og_membership', 'n')
            ->fields('n')
            ->condition('etid', $user_id, '=')
            ->execute()
            ->fetchCol($index = 4);

  //if user is multiple group member, use first index [0], 1 is GID
 // (group id, it is defined in OG table in drupal database
    if ($og_check[0]==1) {
    $logo_link = 'http://your-site.com/whatever-start-page-for-group';
    } else {
     $logo_link =  'http://your-site.com/normal-start-page';
    }

and then print $logo_link inside a href that surrounds logo...
it is pretty specific case, but i need to do this way because targeted group page has nothing to do with actual group page of type group... hope it helps someone


Managed file validation on first upload only In D7,I have new_form with a managed_file field to allow my user to upload documents to public://. I'm trying to prevent my user from uploading a document if the file name they are trying to upload already exists in the system. So far I've been successful using this:

function mymodule_file_validate($file) {
  $filename = $file->filename;
  $errors = array();
  if (file_exists('public://' . $filename)) {
    $errors[] = t("File exists already!.");
  }
  return $errors;
}

This displays an error if the user browses for the file and presses upload, even before the file submission, which is exactly what I need.

However, I also have another form modify_form in this module that allows users to modify the document and in that case it's okay to upload the document with the same name even though the file name exists already. BUT... the function above blocks my modify_form too.

Any suggestions how to make the function apply only to my new_form? Or another way to prevent upload if file exists already only on new_form? Thanks!

I ended up adding a custom validator only to the new_form file upload field:

'#type' => 'managed_file',
'#upload_validators' => array(
      'file_validate_unique' => array($file),
)

and then added a function:

function file_validate_unique($file) {
   $errors = array();
   $filename = $file->filename;
   if (file_exists('public://' . $filename)) {
         $errors[] = t('The file could not be uploaded because a file by that name already exists in the destination directory.');
   }
   return $errors;
}

now it only validates the new_form and outputs an error right when the user tries to upload the managed_file, before the form is even submitted.

Instead of putting it into hook_file_validate try attaching a form
validation handler through hook_form_alter or hook_FORMID_form_alter.
Add your validation handler with $form['#validate'][] =
'my_module_my_form_validation_function'
And then just write the code in the condition:

function my_module_my_form_validation_function(&$form) {
 if(form_id == 'your_form_id') {
 $filename = $file->filename;    // fetch filename through $form
 $errors = array();
 if (file_exists('public://' . $filename)) {
   $errors[] = t("File exists already!.");
  }
  return $errors;
 }
}


How do I configure a Kernel test? Currently I am able to run the Unit test from the below command

C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\bin>phpunit -c
 ../../core/phpunit.xml.dist ../../modules/custom/lse_demo/tests/src/Unit

PHPUnit 6.5.0 by Sebastian Bergmann and contributors.
......                                                              6 / 6
(100%)
Time: 10.62 seconds, Memory: 6.00MB
OK (6 tests, 12 assertions)

But When I tried to do the same with Kernel test I get below error

C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\bin>phpunit -c ../../core/phpunit.xml.dist ../../modules/custom/lse_demo/tests/src/Kernel
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

EEEEEE                                                              6 / 6 (100%)

Time: 11.43 seconds, Memory: 6.00MB

There were 6 errors:

1) Drupal\Tests\lse_demo\Kernel\DefaultControllerKernelTest::testDefaultController with data set #0 ('work', 'User', 'Welcome User to Work')
PHPUnit\Framework\Exception: PHP Fatal error:  Uncaught PHPUnit\Framework\Exception: Could not read "../../core/phpunit.xml.dist".

  thrown in C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\phpunit\phpunit\src\Util\Configuration.php on line 189

Fatal error: Uncaught PHPUnit\Framework\Exception: Could not read "../../core/phpunit.xml.dist".

  thrown in C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\phpunit\phpunit\src\Util\Configuration.php on line 189

PHPUnit\Framework\Exception: Could not read "../../core/phpunit.xml.dist". in C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\phpunit\phpunit\src\Util\Configuration.php on line 189

Ensure  your connection string in the phpunit.php.dist is correct. The correct format is:

mysql://username:password@localhost/databasename#table_prefix

example

put phpunit.xml.dist to root directory

path inside the above file name is

      ./core/tests/TestSuites/UnitTestSuite.php

      ./core/tests/TestSuites/KernelTestSuite.php

      ./core/tests/TestSuites/FunctionalTestSuite.php

./vendor/bin/phpunit --no-coverage UnitTest ./modules/custom/helloworld/tests/src/Unit/helloWorldTest.php

try the same for kernelTest

my test file starts

=====================

namespace Drupal\Tests\helloworld\Unit;

use Drupal\Tests\UnitTestCase;
use Drupal\helloworld\Helloworld;


Form Alter Foreach Loop changes not sticking I'm trying to modify my exposed filter block to put each of the controls inside fieldsets, and make other modifications to them.

However, when I try to utilize a foreach loop to do this, none of my changes are 'sticking'.

foreach($form_state['input'] as $delta => $input) {
    $collapsed = (empty($input) ? TRUE : FALSE);

    $form[$delta . '_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t($form['#info']['filter-' . $delta]['label']),
        '#collapsible' => TRUE,
        '#collapsed' => $collapsed,
    );

    $form[$delta . '_fieldset'][$delta] = $form[$delta];
    unset($form[$delta]);
    unset($form['#info']['filter-' . $delta]);

}

This wont work, but this will:

$delta = 'field_resource_type_tid';
$collapsed = (empty($form_state[$input][$delta]) ? TRUE : FALSE);

$form[$delta . '_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t($form['#info']['filter-' . $delta]['label']),
    '#collapsible' => TRUE,
    '#collapsed' => $collapsed,
);

$form[$delta . '_fieldset'][$delta] = $form[$delta];
unset($form[$delta]);
unset($form['#info']['filter-' . $delta]);

I've been trying to find out why this wont work, but I can't for the life of my figure out what the form modifications wont stick when done inside this foreach loop.

I've finally managed to resolve my issue, but I'm not sure why. I decided to change what array I was using to iterate through the filter fields on my form. By switching to iterating through the form array instead of form_state, any changes I make to it now are sticking.

foreach($form['#info'] as $delta => $input) {
    $filtername = $input['value'];
    $collapsed = (empty($form_state['input'][$filtername]) ? TRUE : FALSE);

    $form[$filtername . '_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t($form['#info']['filter-' . $filtername]['label']),
        '#collapsible' => TRUE,
        '#collapsed' => $collapsed,
    );

    $form[$filtername . '_fieldset']['' . $filtername] = $form[$filtername];
    unset($form[$filtername]);
    unset($form['#info']['filter-' . $filtername]);

}

Try passing the $vars by reference by prefixing with "&":

foreach(&$form_state['input'] as $delta => $input)


Jquery into Drupal 7 I'm trying to get this: http://jsfiddle.net/SgHJ5/
to work in Drupal 7.

For some reason, when I paste it into my front--page.tpl (footer) it doesnt work.

I've also tried including a JS file into my template.php.

jQuery in D7 is in noConflict mode. You need to use jQuery instead of $, or a closure.
See http://drupal.org/node/171213

Try in this way: create your script example.js that have this code for example:

**var $ob= jQuery.noconflict();
$ob(function(){

$ob("a").fadeOut();
});**


How to incorporate AMP in an existing theme? Is there a way to incorporate AMP into my Porto Theme?

The AMP project for Drupal has three parts. The AMP module, the AMP PHP Library, and the AMP Theme work together to provide valid AMP markup for nodes with AMP-enabled content types at paths with ?amp at the end of the URL.

From the AMP module page:

  The AMP module is designed to convert Drupal pages into pages that comply with the AMP standard. When the AMP module is installed, AMP can be enabled for any node type. At that point, AMP content becomes available on URLs such as node/1?amp or node/article-title?amp.

  The AMP PHP Library analyzes HTML entered by users into rich text fields and reports issues that might make the HTML non-compliant with the AMP standard. The library does its best to make corrections to the HTML, where possible, to make it more compliant with the AMP HTML standard.

From the AMP Theme page:

  The AMP Theme is designed to produce the very specific markup that the AMP HTML standard requires. The AMP theme is triggered for any node delivered on an ?amp path.

Some additional reading, an article describing the three in more detail on the official AMP blog: AMPing up Drupal.

To answer your question, you need to create a sub-theme bu using amptheme as the base theme. The AMP module will take care of switching the theme for AMP enabled pages along with AMP library.

You need to know that AMP is a separate spec of HTML, it wont support all the HTML tags, also there are restrictions in terms of CSS and JS. for ex: you cannot use !important in CSS.

Check the docs here https://www.ampproject.org/


How to show the body field in a custom template? I'm stuck with this problem. In the following code, I want to replace the "field_portfolio_categories" by the "body field" in a custom tpl file.

<?php print $title; ?>

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

So I change it to:

<?php print $title; ?>

<?php print $body; ?>

In the node, instead of body content, I see "Array"
And this is the error message:

Notice : Array to string conversion in include() (ligne 41...

Any idea what's wrong?

Here is the complete template code:

    <?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
hide($content['body']);
//$original_image = file_create_url($node->field_portfolio_images['und'][0]['uri']);
$lightboxrel = 'portfolio_' . $nid;
$portfolio_images = field_get_items('node', $node, 'field_image');
$first_image = '';
if ($portfolio_images) {
  foreach ($portfolio_images as $k => $portfolio_image) {
    if ($k == 0) {
      $first_image = file_create_url($portfolio_image['uri']);
    } else {
      $image_path = file_create_url($portfolio_image['uri']);
      print '&nbsp;';
    }
  }
}
?>
<div id="node-<?php print $node->nid; ?>" class="portfolio-text <?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php print render($title_suffix); ?>
<div class="ImageWrapper content"<?php print $content_attributes; ?>>

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

                   <a href="<?php print $first_image;?>" rel="prettyPhoto[<?php print $lightboxrel;?>]" data-toggle="tooltip" data-original-title="<?php print t('View Image');?>" data-placement="bottom" class="zoom dtooltip">

<?php print $title; ?>

    <?php print_r($content['body']); ?>
    <?php //print render($content['body']); ?>

<?php //print render($content['links']); ?>
<?php //print render($content['comments']); ?>

Your code should be:

    <?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
//$original_image = file_create_url($node->field_portfolio_images['und'][0]['uri']);
$lightboxrel = 'portfolio_' . $nid;
$portfolio_images = field_get_items('node', $node, 'field_image');
$first_image = '';
if ($portfolio_images) {
  foreach ($portfolio_images as $k => $portfolio_image) {
    if ($k == 0) {
      $first_image = file_create_url($portfolio_image['uri']);
    } else {
      $image_path = file_create_url($portfolio_image['uri']);
      print '&nbsp;';
    }
  }
}
?>
<div id="node-<?php print $node->nid; ?>" class="portfolio-text <?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php print render($title_suffix); ?>
<div class="ImageWrapper content"<?php print $content_attributes; ?>>

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

                   <a href="<?php print $first_image;?>" rel="prettyPhoto[<?php print $lightboxrel;?>]" data-toggle="tooltip" data-original-title="<?php print t('View Image');?>" data-placement="bottom" class="zoom dtooltip">

<?php print $title; ?>

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

<?php //print render($content['links']); ?>
<?php //print render($content['comments']); ?>

The "problem" comes from manage display. Besides the default tab, there are 3 other tabs where I can click to show/hide fields. In order to see the body text, I had to click on Teaser text and show the body tag.


When should I use user_load($user->uid) when do we need to load user using  user_load($user->uid) after global $user. Why do we need to load a user because we can access user data after declaring it global. I am adding a commerce customer to his billing and shipping profiles, should I use user_load?

The global $user object is just the bare data received from the users table for the associated user. It doesn't have any field, or other module-added data, attached to it by default.

For example, if you have a field attached to your user accounts called 'field_nickname', and you want to inspect the value of that field for the current user in code, you would need to call user_load() for the data to be available.

// Might work, but it's not guaranteed - depends on the modules
// you have installed and what's happened in the page build so far
$account = $GLOBALS['user'];
if ($items = field_get_items('user', $account, 'field_nickname')) {
  // ...
}

// Will always work.
$account = user_load($GLOBALS['user']->uid);
if ($items = field_get_items('user', $account, 'field_nickname')) {
  // ...
}

There are situations when other modules will load the field and other module data onto the global $user object, so depending on what modules you have installed you call to user_load() might not strictly be necessary.

However, it's good practice to make sure you load the object yourself; if another module has already run it for the current user then that data is statically cached, so you don't get a performance hit.

You don't need to do user_load() on global $user.

global $user is already a loaded user (the current user).

use user_load() when you want to load users other than the current user. for example, if you have a uid for the author of a node or comment, or a uid from a commerce order, then you use user_load() to load the user object.

Unless (as Clive mentioned), you need to access fields attached to the user, in which case you should load it.

Also, if you want profile2 fields you will need to do

$profile = profile2_load_by_user($user, 'PROFILE_NAME');


Publish node link to social media on content creation I'm looking for a way to publish the node link to social media (Facebook, Twitter and Linkedin) on the creation of the node.

So what I would like is a little checkbox saying: publish to facebook on the node edit page.
Does anyone know a module that could help me achieve this?
Thanks !

Take a look at the twitter module:
https://drupal.org/project/twitter

You should be able to then use twitter to send that story to Facebook by hooking up your twitter account to your Facebook account. I'm not sure if the same is possible with linked in though.

Try social media module as well.

  The social media module helps integrate your website with social media
  sites such as Twitter, Facebook and Google+. It provides an
  centralized way of managing social media profile information and
  plug-in widgets such as follow and share buttons.


Sync +- 70 000 records from CSV into drupal I have a CSV file with approx. 70.000 records that I want to import into Drupal 7. Once this is done the client will provide a new CSV file on a daily base that has to sync the updated rows to Drupal.

I wrote a import with Feeds and the Migrate module, but in both cases it takes like forever to import the 70.000 rows. Is there any other solution to import the data faster in Drupal 7?

If you need an update feature of your records i'm not sure how you'd get around scanning for Diffs to find changes -- this takes time.

I've used Migrate to upload simple CSV files and tables. Have you looked at Migrate 2.6 Hash() function to track data changes in stuff to perform only updates from your source data?
http://www.acquia.com/blog/migrate-26-framework-changes

  With Migrate 2.6, we have introduced the 'track_changes' option to
  MigrateSource. If you pass 'track_changes' => 1 in your options array
  on your source constructor, Migrate will hash the source data after
  prepareRow() is called and save the hash in the map table on initial
  import. On subsequent imports, it will again hash the incoming source
  data and compare it to the saved hash - if the hashes don't match, the
  object will be reimported and the new hash saved, otherwise it will be
  skipped. Of course, this is a slower method than highwater marks, but
  when you must pick up changed records and don't have a good highwater
  mark field in the source data, this is the way to go.

Is there any reason you cannot import your CSV file into MySQL tables and then import your data from there using Migrate or a Drush script? Once in tables you could partition the data/tables easily to run the inserts more concurrently for a speedup.

EDIT:

I hit a .NET webservice for 100,000s of records for campus data at an EDU. I found that parsing the data linearly took me on the order of an 1 hour from top of the XML file to the bottom. By requesting each department individually at-the-same-time (get ~60 XML files at once instead of 1 big xml file) and processing in parallel up to 8 threads (via Ultimate Cron) the same process now takes ~5 minutes.

At some point linear processing of data simply fails and you have to find other means.

I am not sure what "forever" means in terms of actual time spent. However, i have used the user import framework and user import framework plus module and it works fine.


How do I trigger an AJAX submit button on page load? I am attempting to trigger a form (to get live data) on a page load. So far, I have this code I have found from bits and pieces and digging around the net, but unfortunately not a lot of people actually appear to have needed to do this.

jQuery(document).ready(function($) {
  var element_settings = {};
  var element = {};
  element_settings.progress = { 'type' : 'throbber' };
  element_settings.submit = { js: true };
  var ajax = new Drupal.ajax($('#edit-ratessubmit'), element, element_settings);
  element.form.clk = element;

  ajax.form.ajaxSubmit(ajax.options);
});

This currently complains that element_settings doesn't contain a URL, but when it does contain a URL, I get some random "b is undefined" error.

This was a simple case of targeting the correct element using the code below.

$(document).ready(function() {
    $('#edit-submit').trigger('click');
}


Add access code per page I need to create 10 or so pages that are linked in a specific order but can only be accessible when the user enters the correct access code.

The first page would be open and "unlocked" - but the user will need to enter some details before being able to see the next page, they would be presented with the access code for the 2nd page and this would be added to their user profile as their current access code level.

To see the next page, the user would require to enter a specific code to unlock that page.

How would I go about getting this to work? From what I know, webforms would be useful for "linking the pages in order" but I haven't found a way where you must enter a "password" access the next page of the form.

The idea is that the 10 pages would act as 10 different levels for a simple learning "game."

My first reaction would be to create 10 roles (Level 0 to 9) and to restrict access to the pages using Content Access to control access to the pages by role. Then use Rules to assign roles based on the tasks you set out in the learning game.

You could use workflow for this.

  This module allows you to create arbitrary Workflows, and assign them
  to Entities.

  Workflows are made up of workflow states. Transitions between states
  can be allowed per role. For example, a workflow with the states
  Draft, Review, and Published could be assigned to the Story node type.
  Only users with role 'chief editor' can set Stories to the published
  state. You can set up the Workflow to alter states from form, page,
  comment and a special workflow tab.

  Transitions between workflow states can have actions assigned to them.
  In our example, we could assign an action so that when the story moves
  from the Draft state to the Review state an email is sent out. Another
  action could be assigned to the transition from Review to Published so
  that the node's status is set to Published (and becomes visible on
  your website).


Change Views Handler for entity schema field I want to have a numeric value in my db treated as boolean by drupal.

the field is defined in the hook_schema like this

    'myfield'  => array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => FALSE,
    'default' => NULL,
    'description' => "a field",

So Drupal Views module rightfully detects and displays it as a number.
However i want it to be a Boolean, so in my hook_entity_info i have

'views controller class' => 'StrutturaViewsController',

and then

class StrutturaViewsController extends EntityDefaultViewsController {

  public function views_data() {
    $data = parent::views_data();

    $data['struttura']['myfield']['field']['handler'] = 'views_handler_field_boolean';

    return $data;
  }
}

'struttura' is the name of the entity that i created, and the name of the table with the 'myfield' coloumn

My problem is that Drupal is still treating the value as numeric.

Am i missing something?

Sure. Adding a new answer to clarify.

To my knowledge (and by that i mean my "very limited Drupal Knowledge") there are 2 ways of mapping the information between schemas and Druapl handlers: by using a custom view controller as i tried to do in the first post, and by implementing the hook_entity_property_info_(). I still don't know why the former approach didn't work but the solution for me was to go with the latter. That is, i had to write

'myfield' => array(
  'type'  => 'boolean',
  'label' => t('clever label'),
  'description' => t('clever description'),

  // Map here the field from hook_schema().
  'schema field' => 'insert_name_of_schema_field_here',
),

Mind that you will have to map EVERY AND EACH of your fields in the schema once you start with this approach.

I also noticed that sometimes doing stuff (like changing ajax config) on the view rendering my entity seems to break the mappings, and i have to clear all caches to bring back my settings.

You can find more information Here

I implemented hook_entity_property_info_() instead of changing the view controller, and everything went fine


Custom forms for custom post types in D7 I am sub-theming Bartik and have a content type called "support_query" with 3 fields... "title" (which comes with all content types), "field_support_body" and "field_support_date" (which is a simple date field from the Date module).

I would like to create a custom form so users can send me queries of this custom post type... what's a good way to do something like that?

You should use your content type's form, customized to suit the basic user.

You'll have to give the allowed users role the right permission (like `Create the content type').

Then you'll have to change the form to mask all irrelevant information. There are many ways to do this :

Implement a module with a `hook_form_alter'. Flexible but involves coding.
Use a module or a combination to achieve the same goal. This one for example seems to be interesting.

Use Webform module

  Webform is the module for making surveys in Drupal. After a
  submission, users may be sent an e-mail "receipt" as well as sending a
  notification to administrators. Results can be exported into Excel or
  other spreadsheet applications. Webform also provides some basic
  statistical review and has and extensive API for expanding its
  features.


how to do addition of two field values in drupal 7during node_presave? I had made two content types
content type 1 - 'product' with field name 'product_stock' and
content type 2 - 'Add stock' with field name 'stock_value'. It also contains a node reference to product content type.
I want to add the value of product stock and stock value during node_presave.

For Example: product stock = 10 and stock value = 14, then both should be added to give 24.

function my_module_node_presave($node){  // implementation of hook_node_presave
  if($node->type == 'add_stock') {
    $product = $node->field_stock_value['und'][0]['value']; //get data value of field
    drupal_set_message('product :'.$product); // print data value for checking
    $nid = $node->field_reference['und'][0]['nid']; //get nid of reference field
    drupal_set_message('nid :'.$nid); // print nid
    $p_node = node_load($nid); // implemenet node_load and get in $p_node
    $stock = $p_node->field_product_stock['und'][0]['value']; //get data value of field
    drupal_set_message('stock :'.$stock); // print value

    $stock = $product + $stock; // addition of both value
    drupal_set_message('Stock :'.$stock);
    $p_node->field_product_stock['und'][0]['value'] = $stock; // updating the product field with updated value
    node_save($p_node); // implement node_save
  }
}


Altering body text of a node before the page is rendered I am using the Zen theme. I want to alter the body text before it is rendered as a page. In particular, I want to replace a string with another string. I thought that the general solution for this would be to place the code in the the theme_preprocess_node hook in my sub-theme's template.php. Here is the code that I've got so far:

<?php
function mytheme_preprocess_node(&$variables) {
    if ((isset($variables['body'][0]['value'])) && (preg_match('/suppose/i', $variables['body'][0]['value']))) {
        dpm('string was found in "value"');
        $variables['body'][0]['value'] = preg_replace('/suppose/i', 'new tring', $variables['body'][0]['value']);
    }
    if ((isset($variables['body'][0]['safe_value'])) && (preg_match('/suppose/i', $variables['body'][0]['safe_value']))) {
        dpm('string was found in "safe_value"');
        $variables['body'][0]['safe_value'] = preg_replace('/suppose/i', 'new tring', $variables['body'][0]['safe_value']);
    }
}
?>

However, this has no effect what so ever. I do get a positive match - this I can verify by the debug dpm() display.

Am I simply trying to rewrite the wrong sub-array?

Thanks in advance,
Valera Rozuvan

Try this in mytheme_preprocess_node:

function mytheme_preprocess_node(&$vars) {
  // Collect / create / adjust new body content
  $new_body = 'xyz';
  // Assign to output
  $vars['content']['body'][0]['#markup'] = $new_body
}

After looking through the vars array a bit, I'm a little surprised at the amount of redundant data there.  There are a few different places where the body text is recorded, usually as an array.

Note that the node body will likely have a 'safe value' and a 'value'.  You'll probably want to use safe almost all the time, but it might be good to check on the filter type selected in $vars['body'][0]['format'] to select which of the body values you'll want to output and display.

This is not a good solution but it works fine.

In node.tpl.php

<?php print hide($content['body']); ?>
<?php print render($content); ?>
<?php print $newbody; ?>

In template.php

function mytheme_preprocess_node(&$variables) {
 if ((isset($variables['body'][0]['value'])) && (preg_match('/suppose/i', $variables['body'][0]['value']))) {
   $variables['newbody'] = str_replace('suppose', 'new string', $variables['body'][0]['value']);
 }
}

As I've said this is a patch solution and I don't recommend this.


How can I change the front-page title when front page is not /node? I changed the site's front page from /node to another page. However, now the title of the front page is page name | site name. To clear up any confusion, by "title," I mean the phrase entered between the HTML <title> tags.
I tried this SO answer, but it had no effect. How can I declaratively change the name of the site's main page?

You can use the Metatag module. It has a section for front page metatags, where you can set the title.

It's not possible to change the front page title declaratively without adding a new module, such as the Metatag module. Drupal's core does not have this functionality. However, you can achieve this with a few lines of code implementing template_preprocess_html in your custom theme.
To achieve this dynamically in a subtheme, add this code to your preprocess_html function of your theme file or add if it doesn't exist.
function MYTHEME_preprocess_html(&$variables) {
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $variables['head_title'] = [t('Hello World')];
  }
}

Note: Credit to @leymanx for the basis for the above code, which just needed a slight modification to update the title as originally asked, rather than just the portion of the before name of the site.


Play Buttons of SoundManager2 are disabled in Ajax o JS I have a views that call a content type with soundmanager fields (360 style) with pager.

On the first page show 3 soundmanager fields and play ok, but in the second page by ajax the no longer played in the input play btn.

In the second page the input play not function.

I tested with 3 options:
Infinite scroll module.
Custom js code for the scroll in the same page.
Views Module load more.

In all feel the same, in the second page loaded in ajax or js buttons play of SoundManager are disabled.

appreciate your help

Add below script in Ajax call

<script>
soundManager.reboot();
</script>


Loading nodes from another Drupal database using Views I'm trying to use Views to load nodes from another Drupal database defined in settings.php with a key of 'cms'. Both sites are Drupal 7. The other database is a different Drupal install which is acting as a content repository or centralized CMS. My goal is to create a new view type/group on the destination site, so when creating a view the site build can choose "CMS Content" instead of "Content". I'm hoping a site builder would then be able to build a view normally based on content types and content from the centralized CMS site, even if I have to tell views about all the fields in each content type.

In my hook_views_data() implementation I've set the 'database' key, but can't figure out how to read from the node table without overriding $data['node'].

function cms_connector_views_data() {
  $data['cms_connector']['table']['group'] = t('CMS Content');
  $data['cms_connector']['table']['base'] = array(
    'field' => 'nid',
    'title' => t('CMS Content'),
    'help' => t('Content from the centralized CMS.'),
    'database' => 'cms',
  );

  return $data;
}

Of course this doesn't look for a node table, it looks for a cms_connector table in my cms database, which doesn't exist.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cms.cms_connector' doesn't exist

http://views-help.doc.logrus.com/help/views/api-tables says that the key within $data…

  should be the actual database name of the table (not including
  prefix), but it can be an alias as long as the join information
  (explained later) contains the real name of the table.

I don't actually want to do a join, I want to create a base table from the other database's node table. But I tried this anyway (even though it doesn't really make sense) after seeing http://drupal.org/node/1713010#comment-6310438:

$data['cms_connector']['table']['join'] = array(
  'node' => array(
    'left_field' => 'nid',
    'left_table' => 'node',
    'field' => 'nid',
    'table' => 'node',
  ),
);

I've searched around here, d.o, and Stack Overflow, but most of what I'm finding is Some-other-database-to-Drupal, not Drupal-to-Drupal.

I found the https://drupal.stackexchange.com/questions/12736/using-nodes-from-another-site-database question here, but it's about node references, and is unanswered.

I thought about using Services to read XML/JSON from the centralized site, but there are too many hurdles to that approach. I don't really want to synchronize nodes either.

Consider looking at the Forena module. It can be used to query (not update) the data in other databases. Various DBMS formats are supported, such as another Drupal database also.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports. For more details about Forena, 2 types of documentation are available:

Community documentation.
Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

Forena documentation - use the link 'Reporting documentation' or visit relative link /reports/help.
Forena samples - use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.

Check this modules:

EntityFieldQuery Views Backend
or
Web Service Data


How to add js file in only 1 node? I made a custom js script for a little calculator. I want to use this in only 1 node (article or page) so I do not want to load it via tpl files etc because I do not need it sitewide. And also: if every custom script (that I use only in 1 node) has to be loaded sitewide I would get an immense head section after some time. Does anyone have experience with how to do this in a simple and safe way?

Thanks.
Frank

In the template.php you will write this small piece of code:

function MYTHEME_preprocess_node($vars) {
 if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'yournid') {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . "/script/js");
 }
}

Replace foo with values related to your need.

you need to use php filter or need to create tpl file for single node to accomplish this. With php filter or tpl you need to put only this code.

<?php
  drupal_add_js('jQuery(document).ready(function () {
    jQuery("p").hide();
    jQuery("p").fadeIn("slow");
  });', 'inline');
?>


how can I debug theme.theme file in my theme using phpstorm? I want to set breakpoints in the theme.theme file and debug some variables but I cannot do that as this file isn't a php file. How can I debug this file?

Go to Preferences -> Editor -> File Types
Scroll down the Recognized File Types list until you find PHP; select it
In Registered Patterns add *.theme
Save

You can now set breakpoints in *.theme files.

Actually you may want full drupal integration with phpstorm. Here you can read how to achieve this.


How do I hide the submission button basing on some conditions? I have a webform with a mandatory Yes/No button. I want to hide the submission button if No is selected.
How can I set up the logical condition for achieving this?

I just figured out that there is the 'Submit' element at the end of the webform elements under webform build tab and I can apply the conditions on that 'Submit' element.

If I were you I'd make it easier for myself and leave it as is.
Because if the answer is no and you don't want him to submit at all so bother to make him do it from the first place!
But: if you need this to happen it is possible to have a little JavaScript doing that for you, see this Example


Custom Module not showing up Playing around with Drupal 8 and trying to create a custom module with a custom block:

I have a module.info.yaml file:

name: Custom Module
description: Description Here
package: Custom Module
type: module
core: 8.x

dependencies:
  - block

I have a src/Plugin/CustomBlock/CustomBlock.php file:

<?php

/**
 * Provides a 'Custom' Block
 *
 * @Block(
 *   id = "custom_block",
 *   admin_label = @Translation("Custom Block"),
 * )
 */

namespace Drupal\custom_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class CustomBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}

The module is in /modules/custom/module. I have installed contrib modules in /modules/contrib with no issue.

If I go to the Extend page, my module is not listed.

Please let me know what I am missing here?

Typo on the module file name:

module.info.yaml

Should be

module.info.yml

Web server permissions may indeed be the issue, especially if everything else seems fine.
https://www.drupal.org/docs/security-in-drupal/securing-file-permissions-and-ownership
I constantly run this set of commands because my Windows ftp client sets ownership to my-user:my-user.  Your web server might not be apache.
(requires a symlink to your drupal root folder from the server root)
cd /drupal9
sudo chown -R my-user:apache .
sudo find . -type d -exec chmod 750 '{}' \;
sudo find . -type f -exec chmod 640 '{}' \;
cd web/sites
sudo find . -type d -name files -exec chmod 770 '{}' \;
for d in ./*/files
do
   sudo find $d -type d -exec chmod 770 '{}' \;
   sudo find $d -type f -exec chmod 660 '{}' \;
done


Must new tables be created in hook_update_N()? When you create a new table in hook_schema(), should that table be added in a hook_update_N() as well? Or is there some trick, or something I missed, to have databae-updates automatically add tables?

The documentation of hook_update_N() does not explain anything about introducing new tables, whereas the documentation of hook_schema() says:

  The tables declared by this hook will be automatically created when the module is first enabled, and removed when the module is uninstalled.

(Highlight is mine)

And if so, how to best avoid duplicating the schema definitions for the new table in both hook_update_N() and hook_schema(). Simply referring to the schema as follows:

 function hook_update_N(&$sandbox) {
   $schema = hook_schema();
   $name = "foo";
   $table = $schema["foo"];
   db_create_table($name, $table);
 }

Seems to work, but on changing the table again, will fail if a user runs the updates and gets to run two or more hook_update_N()s. After all: the first hook_update_N will then already install the correct database and the second hook_update_M() will try to add/change/alter columns that were already up-to-date.

How do you deal with this?

So just a copy paste from drupal.org. You also need to add the schema definition to hook_schema.

/**
 * Create new database table {mytable2}.
 */
function mymodule_update_7101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  db_create_table('mytable2', $schema['mytable2']);
}

mymodule_update_7101() is good, along with this hook if we add a hook_install() to execute the same while module installation instead of the hook_schema() definition is also works for me.

/**
 * Implements hook_install().
 */
function mymodule_install() {
  // Change the update number accordingly for more updates.
  for ($i = 7101; $i < 7102; $i++) {
    $update_func = 'mymodule_update_' . $i;
    if (function_exists($update_func)) {
      $update_func();
    }
  }
}


Create a menu item with subitems How can I create a menu link for main-menu which has related subitems?

For example in main-menu I have Home  About  Products and for the Products menu item I want it to put all categories as subitems: Products -> Shoes -> Shirts ...

Is there a hook or an example so you can achieve this?

You can create a menu programatically through menu hooks, and a great source for sample code and explanation is the menu_example portion of the Examples Module. You can also set up new menu items and strcutre through Drupal's admin menus management (admin/structure/menus)

Why you want to do it programmatically? You can use GUI for it and use Superfish or similar module to display drop down menu and subitems?


How to add CSS class to password-strength and password-confirm on /user/register page? I want to add a class to password-strength and password-confirm on /user/register page? I tried to alter the form but as these are made with js I could not change or add anything to them.
How can I alter these?

Trying to explain, first you need to implement hook_theme(), in this case, you have to implement the function in your template.php file, that is located in the folder that contains the theme you are using (sites/all/themes/your_theme_folder).

function yourThemeName_theme()
{
$items = array();
$items['user_register_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'yourTheme') . '/templates',
        'template' => 'user-register',
);
return $items;
}

After implementing the function, you have to create the template file, in the example, the template file is called user-register.tpl.php and it's located inside the "yourThemeFolder/template" folder.

In the user-register.tpl.php file you define your custom html, for the form, the code that will be rendered inside the <form></form>.
I can't test this now, but if I'm not wrong you can use the debug function to output the form array and check the fields names of your form.

debug($form);

Your template file would look like this:

<fieldset class="form-wrapper" id="edit-account">
        <legend><?php print t('User Account'); ?></legend>

                <?php
                // print render($form['account']);
                print render($form['account']['name']);
                print render($form['account']['mail']);

                ?>

                <?php
                print render($form['account']['pass']);
                print render($form['account']['pass2']);
                ?>

    </fieldset>

For a more detailed example, check the following link:
https://www.drupal.org/node/350634


What plugin control html_attributes? The html.html.twig template contains the following line.

<html{{ html_attributes }}>

On my site, it outputs the following markup.

<html lang="ru" dir="ltr" xmlns:article="http://ogp.me/ns/article#" xmlns:book="http://ogp.me/ns/book#" xmlns:product="http://ogp.me/ns/product#" xmlns:profile="http://ogp.me/ns/profile#" xmlns:video="http://ogp.me/ns/video#" prefix="content: http://purl.org/rss/1.0/modules/content/  dc: http://purl.org/dc/terms/  foaf: http://xmlns.com/foaf/0.1/  og: http://ogp.me/ns#  rdfs: http://www.w3.org/2000/01/rdf-schema#  schema: http://schema.org/  sioc: http://rdfs.org/sioc/ns#  sioct: http://rdfs.org/sioc/types#  skos: http://www.w3.org/2004/02/skos/core#  xsd: http://www.w3.org/2001/XMLSchema# ">

What plugin or core function controls it?

They're added in template_preprocess_html:

$variables['html_attributes'] = new Attribute();

To alter them, you can implement hook_preprocess_html in your theme or module.

I think it is a result of working "Metatag" module (your attributes contain some w3c validation errors). I used this patch to change depreciated metatags.


How and where is the $variables variable used in templates etc. generated in Drupal? How and where is the $variables variables that is used in templates and theme functions generated in Drupal?

Is there documentation anywhere that defines $variables?

The $variables associated array that are passed into functions such as MYTHEME_item_list($variables) are initialized by the caller of that function.

You can use associated array $variables that are taken from template.php or yourmodule.module so that, you can pass that variables to page of your theme.

 $imageOutputinner = “You can have  images variable here”;
$vars['innerImages'] = $imageOutputinner;
//you can print this variables to page of  theme as
print_r($innerImages);


Cannot uninstall modules anymore Why do I get the following message when trying to uninstall a module with Drupal 8?

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

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;pantheon.aggregator_feed&#039; doesn&#039;t exist: SELECT base_table.fid AS fid, base_table.fid AS base_table_fid

FROM
{aggregator_feed} base_table

LIMIT 1 OFFSET 0; Array()
in Drupal\Core\Entity\EntityStorageBase-&gt;hasData()</em> (line 588 of core/lib/Drupal/Core/Entity/EntityStorageBase.php).
Drupal\Core\Database\Statement-&gt;execute(Array, Array) (Line: 631)
Drupal\Core\Database\Connection-&gt;query(&#039;SELECT base_table.fid AS fid, base_table.fid AS base_table_fid

FROM
{aggregator_feed} base_table
LIMIT 1 OFFSET 0&#039;, Array, Array) (Line: 358)
Drupal\Core\Database\Driver\mysql\Connection-&gt;query(&#039;SELECT base_table.fid AS fid, base_table.fid AS base_table_fid

FROM
{aggregator_feed} base_table
LIMIT 1 OFFSET 0&#039;, Array, Array) (Line: 510)
Drupal\Core\Database\Query\Select-&gt;execute() (Line: 267)
Drupal\Core\Entity\Query\Sql\Query-&gt;result() (Line: 83)
Drupal\Core\Entity\Query\Sql\Query-&gt;execute() (Line: 588)
Drupal\Core\Entity\EntityStorageBase-&gt;hasData() (Line: 56)
Drupal\Core\Entity\ContentUninstallValidator-&gt;validate(&#039;aggregator&#039;) (Line: 573)
Drupal\Core\Extension\ModuleInstaller-&gt;validateUninstall(Array) (Line: 99)
Drupal\Core\ProxyClass\Extension\ModuleInstaller-&gt;validateUninstall(Array) (Line: 121)
Drupal\system\Form\ModulesUninstallForm-&gt;buildForm(Array, Object)
call_user_func_array(Array, Array) (Line: 519)
Drupal\Core\Form\FormBuilder-&gt;retrieveForm(&#039;system_modules_uninstall&#039;, Object) (Line: 276)
Drupal\Core\Form\FormBuilder-&gt;buildForm(Object, Object) (Line: 93)
Drupal\Core\Controller\FormController-&gt;getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-&gt;Drupal\Core\EventSubscriber\{closure}() (Line: 582)
Drupal\Core\Render\Renderer-&gt;executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-&gt;wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-&gt;Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel-&gt;handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel-&gt;handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session-&gt;handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle-&gt;handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache-&gt;pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache-&gt;handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware-&gt;handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware-&gt;handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel-&gt;handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel-&gt;handle(Object) (Line: 19)

As @codesmith mentioned it looks like you have some issue with the Aggregator module but, usually you might also see other problems once you fix the aggregator module issue. The reason you see the issue on aggregator_feed is that it is the first table in your table list.

In case you are lucky and the issue is only on the aggregator module use the query below to recreate the missing tables (I am providing the two tables that are created when you install aggregator module).

CREATE TABLE `aggregator_feed` (
`fid` int(10) UNSIGNED NOT NULL,
`uuid` varchar(128) CHARACTER SET ascii NOT NULL,
`langcode` varchar(12) CHARACTER SET ascii NOT NULL,
`title` varchar(255) NOT NULL,
`url` varchar(2048) NOT NULL,
`refresh` int(11) DEFAULT NULL,
`checked` int(11) DEFAULT NULL,
`queued` int(11) NOT NULL,
`link` varchar(2048) DEFAULT NULL,
`description` longtext,
`image` varchar(2048) DEFAULT NULL,
`hash` varchar(255) CHARACTER SET ascii DEFAULT NULL,
`etag` varchar(255) DEFAULT NULL,
`modified` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='The base table for aggregator_feed entities.';

and the second table

   CREATE TABLE `aggregator_item` (
  `iid` int(10) UNSIGNED NOT NULL,
  `langcode` varchar(12) CHARACTER SET ascii NOT NULL,
  `fid` int(10) UNSIGNED DEFAULT NULL COMMENT 'The ID of the target entity.',
  `title` varchar(255) DEFAULT NULL,
  `link` varchar(2048) DEFAULT NULL,
  `author` varchar(255) DEFAULT NULL,
  `description` longtext,
  `timestamp` int(11) NOT NULL,
  `guid` longtext
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='The base table for aggregator_item entities.';

I think that table is part of the core Aggregator module. Looks like Drupal thinks the module is installed but one or more of the module's database tables are missing. Try enabling/disabling the module.


Add image at form submit I have created a form that has a submit button.

$form['products_submit'] = array(
    '#type' => 'submit',
    "#id"  => "submit_first",
    '#value' => t('Submit'),
    '#ajax' => array(
                'callback' => 'products_submit_driven_callback',
                'method' => 'replace',
                'effect' => 'fade',
                'progress' => array('type' => 'none'),
            ),
            '#prefix' => '
',
        '#suffix' => '
'
    );

  return $form;

And I want to add an image inside the button, at the left of 'Submit' text. I tried to add the img tag inside the t function but it just showed the code and not the image. Does anyone know how can I manage this?

You can handle this from CSS.

Like :

.button-logged-in.input{
    background-image: url(/images/buttons/submit.png);
}

Example : https://stackoverflow.com/questions/2920076/html-css-how-to-add-image-icon-to-input-type-button


Drupal Commerce Hook - Extra validation before adding to cart I was looking for a hook that will fire after a user hits the add to cart button.
The commerce api isn't very clear about this.

What I'm trying to is:
Add an extra validation for a customized product (date field).
So basically I want to interrupt the adding to the cart process and proceed if validation is ok, and lead the user back if not.

Thanks!

Seems like hook_commerce_cart_product_add is what you're after. I couldn't find any examples for preventing the line item being added to the cart but at the very least you should be able to use drupal_goto to interupt the process. You might also want to look at the Rules events\actions provided by Commerce.

Maybe this post can help you.
https://www.drupal.org/node/1292742


Services 3: Setting taxonomy terms on node creation/update For a custom node type, I have defined a field that is to hold an unlimited number of values from a taxonomy vocabulary that I defined.

This is what it looks like:

[field_taxonomy] => Array
  ( [und] => Array
      [0] => Array
        ( [tid] => 13 )
      [1] => Array
        ( [tid] => 14 )
      [2] => Array
        ( [tid] => 15 )
  )

This is the JSON I pass to the server during node creation (as per [1]):

'field_taxonomy':
  { '11':
    { 'tid': '11'} }

This format is accepted (i.e. no 406, which I get if I try to mirror the above structure), but when I look at the node on the server, the field does not contain any terms.

What does my request have to look like so I can succesfully set taxonomy terms on a node?

[1] What will be the post parameter when specifying vocabulary term?

Your request should use the following:

"field_taxonomy":{ "und": { "values": "14" }  }

I used a string as tag values:

"field_tags": {
   "und": "term 1, term 2"
 }


Commerce rule for total of product lines only (not shipping as well) I have a requirement to add an amount to the total of all Commerce product lines items in a users cart and then add that amount to the shipping amount.

The rule I currently have uses the "calculating a shipping rate" event. The element on the rule uses "Calculate a value" with the input value as commerce-line-item:order:commerce-order-total:amount. However, this value also takes into account the shipping. I only want to apply the calculation to the ordered items in the cart - not shipping as well.

Does anyone know how I can access just the subtotal for the cart?

Thanks!

Using [site:current-cart-order:commerce-order-total:amount] seems to do the trick.


D8 HTML tags from field converted to special characters when printing variables I have WYSWYG editor enabled on my fields when there is html in these fields. When I print out the variables in my template, the html gets converted to special characters.

for example my print statement

{{ node.field_hours.value }}

My full HTML in the field becomes this.

Camping : &lt;p&gt;&lt;strong&gt;Equestrian, Group and Primitive Sites:&lt;/strong&gt;&lt;/p&gt;
46 miles of marked multiuse trails.

Florida law requires bicyclists under 16 to wear helmets.

Bird Watching :    Site 64 on western section of

&lt;ul&gt;

It is unsafe to print raw data from a field value.

Instead of using {{ node.field_hours.value }} put this in your node template:

{{ content.field_hours }}

This will print out the field as configured in the view mode. In the view mode you can select a text filter that matches the allowed tags of the ckeditor. In Drupal 8 all necessary text formats are predefined to be used together with ckeditor.

it was autoescaped so |raw filter worked http://twig.sensiolabs.org/doc/tags/autoescape.html


Update Drupal Core from 6.26 to 6.36 using update.php gave no errors, but Drupal still reports that it is on version 6.26 I've followed all of the steps on https://www.drupal.org/upgrade/running-update-php to upgrade my Drupal Core.

I put the site into maintenance mode.
I disabled all modules except the core required modules.
I used FTP to delete all of the folders associated with the upgrade.
I copied the entire directory of contents except .htaccess and robots.txt and part of my sites directory
I navigated to subsite.site.com/update.php
I ran the update
The update indicated that it performed 0 / 0 tasks and said it completed
I navigated to the administration page
I cleared cache
I reenabled modules
I checked the current upgrade status

Result: It still read that I was on 6.26
Expected result: It reads that I'm on 6.36

Quite confused about this. I have successfully upgraded my modules using the update.php script with no problems.  Any thoughts?

Thanks!

Have you manually brought your codebase up to version 6.36 by overlaying 6.24 with 6.36?

The update.php will only update the database to the latest version of Drupal installed.  So if it's still 6.24, it makes sense to me that it is applying 0 of 0.

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


Site not working after the database update I cloned a repo of a site to my local computer, imported the database and ran "Composer install --with-dependencies" after the installation had been done I entered the local site and it worked, then I ran "drush updb -y" and it showed a couple of errors and warnings:

    The following module is missing from the file system: aspambot       [warning]
bootstrap.inc:268
The following module is missing from the file system: phpmailer      [warning]
bootstrap.inc:268

...

PHP  27. include() /home/www/sites/zb/web/vendor/composer/ClassLoader.php:444
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Interface 'Doctrine\Common\Reflection\ClassFinderInterface'
not found in
/home/www/sites/zb/web/core/lib/Drupal/Component/Annotation/Reflection/MockFileFinder.php,
line 14
The external command could not be executed due to an application     [error]
error.
PHP Fatal error:  Interface 'Doctrine\Common\Reflection\ClassFinderInterface' not found in /home/www/sites/zb/web/core/lib/Drupal/Component/Annotation/Reflection/MockFileFinder.php on line 14

I'm new to Drupal, so please help me get over these errors, I understand that the solution may seem straightforward to some, but I don't know what to do. Thank you!

Add "doctrine/common":">2.8" under conflict in your composer file and then run composer update.

"conflict": {
    "drupal/drupal": "*",
    "doctrine/common":">2.8"
},

See issue: https://www.drupal.org/project/drupal/issues/2986725

I'm struggling with the same error, and had no time to dig the entire problem about Composer. But I came up with a workaround as follows:

Delete core and vendor folders from your Drupal root directory.

$ rm -rf core vendor
From a fresh downloaded drupal, copy core and vendor folders to your Drupal root directory.

$ cp -R core vendor /path/to/drupal/root/directory/

I had the problem on two servers. On one I managed to restore from an existing backup. And on the other I managed to resolve the problem with the steps above.


Features are sweet but what about content? I used features successfully to restore my VIEW and content type...but the data for the content type didn't make it? Did I miss the option or is this something you typically bring over manually?

Features are useful to export (and import) configurations, but is not useful for "entities": users, nodes, files, terms, and so on.

A great module to export and import is Node Export


render form item of type text_format in twig file I have created a form element, basically I want text formats to change texts as accordingly.

$form['thankyou'] = [
        '#type' => 'text_format',
        '#title' => $this->t('Thank you'),
        '#format'=> 'full_html',
        '#default_value' => $config->get('thankyou'),
      ];

Now, I have created a function, where I'm getting this form element value.

$config = \Drupal::configFactory()->getEditable('myconfig');
 $thankyou_paid = $config->get('thankyou');

If I directly debug $thankyou_paid, I get all my data formatted. (in bold)

But If I render it through hook_theme,

return array(
      '#theme' => 'mytwig',
      '#type' => 'markup',
      '#thankyou' => $thankyou_paid,
      '#cache' => ['max-age' => 0,],
    );

It gives me <b>ugwdegfgiurgiuterug</b>. Means, data gets rendered without formatting.

How to get this text (ugwdegfgiurgiuterug) as ugwdegfgiurgiuterug.

It's unsafe to use the raw filter, better use the render element

  raw

  This filter should be avoided whenever possible, particularly if you're outputting data that could be user-entered. See this page
  for more information on auto-escape in Drupal 8.

processed_text:

return [
  '#theme' => 'mytwig',
  '#thankyou' => [
    '#type' => 'processed_text',
    '#text' => $thankyou_paid,
    '#format' => 'full_html',
  ],
];

To configure the text format visit /admin/config/content/formats and read the warnings

  Improper text format configuration is a security risk.

In this case it might be better to use Restricted HTML or Basic HTML.

solution in twig file:

{{  element['#thankyou']|raw }}

raw provides formatted text.


Content items with multiple images I have created a content item in Drupal 7 which has multiple image fields (well it has an image field that accepts multiple images).

When I display the item, the images are displayed one under the other, or I can put them into a lightbox gallery.

How can I change or over-ride the CSS and JavaScript code associated with these content items? Additionally, I eventually want to be able to count up the number of images in the content item and write some js to do this. But I am not sure how to find the names of the items and/or if that is indeed necessary.

My goal is to make a gallery of images that can be flicked through like many JavaScript galleries that place content in hidden tags.

You can use javascript to add css to your page after all the other css files have been  listed.

<?php
  drupal_add_js();

  // Then in the js file you can add the css file

If you are still stuck then place a link here of your site and contact me.

// used to add your own stylesheet
drupal_add_css();
// used to add your own script
drupal_add_js();

then you can catch all your image fiels with something like this:

 jQuery(document).ready(function() {
     jQuery('.your-image-class').hide();
 });


Are there any embedded video/media field modules which integrate with Rules? I'm trying to set up some Rules conditions which deal with whether or not a user has added a YouTube URL into a media field for a node. The idea is to use a Media type module to embed the YouTube video into the forum post. But I want a specific Rule to fire if the user saves their forum post without adding a YouTube video URL to that custom field.

However, I can't seem to find a module like Media or Video Embed Field, or Embedded Media field which expose that field entity to Rules.

You could use a hook_form_alter() to check if a youtube video has been added. Then run rules_invoke_event() to trigger the rule.

Btw, I personally like the Video Embed Field module.

I haven't perused them all, but Johan Falk posted a new bunch of Rules videos just before Drupalcon Denver.  You may find a solution within them:
http://www.youtube.com/watch?v=BunFdtCTfK0&feature=results_main&playnext=1&list=PL84B6FFA4F7ACAD57
Best of luck!
Susan


Ajax slideshow for D7? I am looking for some kind of Ajax-based slideshow/banner module for D7 for a changeable front-page photo banner. Unfortunately neither Views Slideshow Ajax nor Ajax Slideshow have been ported to D7 yet. I have several megabytes of photo content and would like to load each image on demand, not load them all at once (which is, as I understand, how most of the slideshow modules work). Right now I am just using a view that returns a randomly-chosen image, but I'd rather have it cyclable by the user with arrows or by a timer.

Are there any existing D7 modules that do something like this? There are so many slideshow, banner, and gallery modules: I may have missed the one I need.

The Views Slideshow module relies on the Cycle library, if I'm correct. It supports AJAX / progressive loading in it's current version as seen here:

http://malsup.com/jquery/cycle2/demo/progressive.php

In my experience, a lot of Drupal modules make the integration of library options unneccessarily complex:
So you could just generate the necessary code via views instead and load the lib yourself via template. Most current slideshow scripts support AJAX loading, so you can choose one that suits you.

How about trying Galleria. I am not sure why u insist to go only with ajax based modules. But to me i think galleria can achieve your needs.


Leaflet Map disappears when selecting term in views exposed filter I'm using leaflet in a content view with a page having an exposed filter on taxonomy terms.

Problem is whenever a term/filter is selected and applied the map disappears and turns grey.
I'm using Leaflet More Maps and this seems to happens with any map.

You must use global area views from other block with generic map, should not have results always show you the map.


Custom block with configurable message inside it When creating a custom block, how can we add a message and have it configurable by the user?  Is this possible?

This is a good example for a Drupal 8 custom block that is configurable by the user

Please check the example here. You'll need to create a hook_block_configure call.

https://api.drupal.org/api/examples/block_example!block_example.module/8


Hiding a block based on code I'm looking for the best way to programmatically hide a block. In Drupal 6 I'd normally use preprocess_block to do all my logic and then unset title and content/body from there. I've tried to do same thing in Drupal 7 but failed. What's the correct way of doing this? I'd like to avoid editing the settings through the UI as this change has to be deployed in code rather than database.

The best (IMHO) way is to implement hook_block_list_alter() in a custom module and unset specific blocks when you need to. Advantages are:

No PHP code in your database, so your alterations can be managed in a version control system
No hacking in the theme layer, so the alterations will remain when you switch themes
Better performance because the block is removed from the list before it is rendered

Drupal core also uses this hook to hide blocks: block.module itself implements hook_block_list_alter to apply the default block visibility settings.

Enable PHP filter module so that you can write PHP on block visibility settings page.

Like this


How to change redirect after adding node of a particular content type I am currently developing a D7 site.  One content type is a "resource," which is a link to an external site, or uploaded pdf file.  I have a page view to list out all resources (/resource-list/edit ) that allows an admin to see resources broken up by category, reorder them, edit, and delete.

The edit, and delete links were added via views.  I have also added an "Add new resource" button to the header of the view, which properly opens the add resource form in the admin overlay.  However, when the admin submits the new resource, they are redirected to the new node that was created.  Instead, I would like them to be redirected back to /resource-list/edit.  How would one go about changing the redirect only for this content type, and only when triggered from the /resource-list/edit view page?

You can do this with http://drupal.org/project/rules.

Just import this declaration and adjust it to your needs:

{ "rules_redirect" : {
    "LABEL" : "redirect to view",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "page" : "page" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "path/to/your/view" } } ]
  }
}

If all you want to do is change where a user redirects to after they submit an add node form, there is a much easier way.

Just make your link look like this: /node/add/[CONTENT-TYPE]?destination=[URL-REDIRECT]

Here is an example that I got working: /node/add/ic-competencies-toolkit-codes?destination=admin/survey-codes


How can I override certain breadcrumb segments? Drupal seems to be adding some default breadcrumbs that come from the URL.  How can I disable this feature? I don't see it in configuration but maybe I'm looking in the wrong place.

The default breadcrumb builder is defined in the system services file and has the priority 0:

system.services.yml

  system.breadcrumb.default:
    class: Drupal\system\PathBasedBreadcrumbBuilder
    arguments: ['@router.request_context', '@access_manager', '@router', '@path_processor_manager', '@config.factory',  '@title_resolver', '@current_user', '@path.current']
    tags:
      - { name: breadcrumb_builder, priority: 0 }

If you want to turn off the default breadcrumb builder you define one with a higher priority. This is an example for taxonomy terms:

taxonomy.services.yml

services:
  taxonomy_term.breadcrumb:
    class: Drupal\taxonomy\TermBreadcrumbBuilder
    arguments: ['@entity.manager']
    tags:
      - { name: breadcrumb_builder, priority: 1002 }

With the method applies() you choose for which routes the breadcrumb builder should be used:

TermBreadcrumbBuilder::applies()

  public function applies(RouteMatchInterface $route_match) {
    return $route_match->getRouteName() == 'entity.taxonomy_term.canonical'
      && $route_match->getParameter('taxonomy_term') instanceof TermInterface;
  }

The breadcrumb manager checks all applies() methods, starting with the highest priority, until it reaches the default breadcrumb builder, which applies for all routes:

PathBasedBreadcrumbBuilder::applies()

  public function applies(RouteMatchInterface $route_match) {
    return TRUE;
  }

In D8, breadcrumbs are now blocks. They can be disabled in Block Layout.


Add attributes to the render array I am trying to add some attributes to a render array. In Drupal 7, we can do this by adding a property in an array like the following.
$items[] = array('data' => $item_data, 'id' => 'someId'); // attribute = 'id'
$variables['subpanels'] = theme('item_list', array('items' => $items, 'title' => NULL, 'type' => 'ul'));

In Drupal 8, there's no #attributes property documented in Render Arrays in Drupal 8. How can I add this id as an attribute in a render array, with Drupal 8?
This is the code I am using so far.
mymoduleController.php
public static function _mymodule_f1($users_online) {
  $user = \Drupal::currentUser();

  $render_array_1 = array();
  $render_array_1['name'] = 'test-name';
  $render_array_1['header'] = t('test-header');
  $render_array_1['contents'] = array('#value' => '
' . ''. '
');

  $items = array();
  foreach ($users_online as $key => $value) {
    if ($key != 'total') {
      $items[] = array('#value' => '' .   $value['name'] . '', 'class' => array('status-' . $value['status']));
    }
  }
  //print_r($items);
  if ($items) {
    $item_list = array(
      '#theme' => 'item_list',
      '#items' => $items,
    );
    $render_array_1['footer'] = $item_list;
  }
  $render_array_1['text'] = array('#value' => t('T1') . ' (' . count($items) . ')');
  $image = [
   '#theme' => 'image',
   '#uri' => drupal_get_path('module', 'mymodule') . '/css/themes/images/loading.gif',
   '#width' => NULL,
   '#height' => NULL,
   '#class' => 'icon'
  ];

  $render_array_1['icon'] = $image;
  $mymodule_subpanel = array(
    '#theme' => 'mymodule_subpanel',
    '#subpanel' => $render_array_1
  );
  return $mymodule_subpanel;
}

mymodule.module
function mymodule_theme() {
  return array(
    'mymodule' => array(
      'variables' => array('mymodule' => NULL),
      'template' => 'mymodule',
    ),
   'mymodule_subpanel' => array(
     'variables' => array('subpanel' => NULL),
     'template' => 'mymodule-subpanel',
   ),
 );
}

function mymodule_preprocess_mymodule(&$variables) {
  $items = array();
  $users_online = mymoduleController::f2();
  $render_items = mymoduleController::_mymodule_f1($users_online);
  $render_items['#attributes'] = array('id' => 'some_id'); //not working; unable to add id='some_id' in the
 tag.
  //print_r($render_items);

  $items[] = $render_items;
  //print_r($items);

  $item_list = array(
    '#theme' => 'item_list',
    '#items' => $items, // array of render arrays.
    '#title' => NULL,
    '#list_type' => 'ul',
    '#attributes' => array('id' => 'mainpanel')
  );
  $variables['subpanels'] = $item_list;
}

Render arrays can contain render elements or theme templates.

Example for a render element:

'#type' => 'link'

and a theme template:

'#theme' => 'item_list'

Render elements have the parameter #attributes. This is defined in the base class Drupal\Core\Render\Element\RenderElement that all render and form elements are extended from.

That is not the case for templates in general.

The template links for example has #attributes and handles this in template_preprocess_links() in /core/includes/theme.inc.

The example from the question is item-list. This template has a variable #wrapper_attributes. You can see in the first line of the preprocess function how wrapper-attributes is transformed in an attributes object, which is then passed on to the twig template where it is placed in the list wrapper:

/**
 * Prepares variables for item list templates.
 *
 * Default template: item-list.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - items: An array of items to be displayed in the list. Each item can be
 *     either a string or a render array. If #type, #theme, or #markup
 *     properties are not specified for child render arrays, they will be
 *     inherited from the parent list, allowing callers to specify larger
 *     nested lists without having to explicitly specify and repeat the
 *     render properties for all nested child lists.
 *   - title: A title to be prepended to the list.
 *   - list_type: The type of list to return (e.g. "ul", "ol").
 *   - wrapper_attributes: HTML attributes to be applied to the list wrapper.
 *
 * @see https://www.drupal.org/node/1842756
 */
function template_preprocess_item_list(&$variables) {
  $variables['wrapper_attributes'] = new Attribute($variables['wrapper_attributes']);
    foreach ($variables['items'] as &$item) {
    $attributes = array();
    // If the item value is an array, then it is a render array.
    if (is_array($item)) {
      // List items support attributes via the '#wrapper_attributes' property.
      if (isset($item['#wrapper_attributes'])) {
        $attributes = $item['#wrapper_attributes'];
      }

The template item_list has also the variable attributes, which is passed on to the twig template. Here you can see how this all ends up in the html markup, including the attributes of the items, which are collected for each item from wrapper-attributes in preprocess:

item-list.html.twig

{#
/**
 * @file
 * Theme override for an item list.
 *
 * Available variables:
 * - items: A list of items. Each item contains:
 *   - attributes: HTML attributes to be applied to each list item.
 *   - value: The content of the list element.
 * - title: The title of the list.
 * - list_type: The tag for list element ("ul" or "ol").
 * - wrapper_attributes: HTML attributes to be applied to the list wrapper.
 * - attributes: HTML attributes to be applied to the list.
 * - empty: A message to display when there are no items. Allowed value is a
 *   string or render array.
 * - context: A list of contextual data associated with the list. May contain:
 *   - list_style: The custom list style.
 *
 * @see template_preprocess_item_list()
 */
#}
{% if context.list_style %}
  {%- set wrapper_attributes = wrapper_attributes.addClass('item-list--' ~ context.list_style) %}
  {%- set attributes = attributes.addClass('item-list__' ~ context.list_style) %}
{% endif %}
{% if items or empty -%}

    {%- if title is not empty -%}

{{ title }}

    {%- endif -%}
    {%- if items -%}
      <{{ list_type }}{{ attributes }}>
        {%- for item in items -%}

{{ item.value }}

        {%- endfor -%}
      </{{ list_type }}>
    {%- else -%}
      {{- empty -}}
    {%- endif -%}

{%- endif %}

Btw. the wrapper is only placed in the classy theme, the base theme doesn't use this.

Conclusion:

Templates don't have attributes by default. As the examples show, they can handle them like render elements, under a different variable name or not at all.

I hope this example may help you.

Step 1. Create your module and Block (http://www.drupal8.ovh/tutoriels/107/create-a-simple-block-programmatically)

Step 2. Add your template usin hook_theme()  (here module name = clock)

Example:

function clock_theme($existing, $type, $theme, $path) {
  return array(
    'clock' => array(
      'variables' => array(
        'icon' => NULL,
        'title' => NULL,
        'time' => NULL,
      ),
    ),
  );
}

You cal also use template_preprocess to handle your template
Example:

function template_preprocess_clock(&$variables) {
  //Add global classes
  $variables['attributes']['class'][] = 'my_clock';
}

Step 3. Create the twig template in clock/templates/clock.html.twig
Example:

  {% if icon %}

  {% endif %}

{{ title }}

Step 4. Add the template to your block or page, using the render array
Example :

return array(
      '#theme' => 'clock',
      '#icon' => $icon,
      '#title' => 'The Title',
      '#time' => "The Time is : ".date('H:i:s'),
    );

http://www.drupal8.ovh/en/tutoriels/140/add-twig-template-to-a-custom-module-block-or-page

And also this one

$output[] = array(
  '#type' => 'inline_template',
  '#template' => '{{ yourvar }}',
  '#context' => array(
    'yourvar' => 'The Value',
  ),
);
return $output;

http://www.drupal8.ovh/en/tutoriels/154/inline-template-drupal-8-and-twig


How to implement revisioning in my own module? In my module I store some node related data in a specific table of the database. Now I want to implement the revisioning system, so I create my_table_revision with the same information and a new column called revision_id.

But, How can I know when a new revsion of the node is created? and how can I know when a node revision is reverted?

It exists something like hook_revert() or hook_revision?

As Clive says, you need to create a custom entity (with the API) to hold the data. Then Drupal will create the necessary tables and take care of the versioning for you.

If you need to do special things (that is not already done by Drupal's built-in versioning), you can intercept both saving of new revisions and reversals with hook_entity_update.

AFAIK, there is no simple way to tell a new revision apart from a reversal.  Technically, a reversal results in a new revision with a new version ID (vid) being created, where the content of the new revision just happens to be identical to some old revision.

If it is really important for you to tell them apart, I guess you could keep a table with SHA2 (or MD5) hash signature for each revision, and look up the signature in that table to identify a reversal.

For the sake of completeness, I'll also mention that I've observed than when someone do a reversal, a log message is generated and placed in {node_revision.log} (E.g. "Copy of the revision from Thu, 2014-06-19 13:53.". Otherwise, this field is filled in with a user-written change notice (or left blank). You may be able to use this to detect reversals, but IMHO this method is not reliable as the string can easily be spoofed by a user who knows about this.

As Free Radical and Clive says the best way to implement a revisioning system is creating a custom entity. But if you can't create a custom entity and you have to use your own table, I answer here what I have done.

So, you have your table and you have to create a table_revision with the same fields and one mor field called revision.

With the hook_node_update you can control when a node is updated, even when a node is revisioned.

So in the $node argument of the hook_node_update you have three vid (revision ID): $node->vid, $node->old_vid and $node->original->vid. The $node->vid is the new vid, the $node->original->vid is the previous vid that the node had, and the $node->old_vid is the vid of the node where you revert.

If the $node->old_vid is the same value than $node->original->vid means that the node is edited and not reverted, and if it is not the same value, it means that the node is reverted to a previous revision.

If the node is edited, you have to insert the new values in the table_revision with the '$node->vidrevision ID. But if the node is reverted, you have to get the old values from thetable_revisionwithrevision_id = $node->old_vidand then copy this values in thetableandtable_revisionwith the$node->vidas newrevision_id`.


views - how to filter by birthdays dependent on the current date I have the following use-case:

I have a custom content type called profile which has a birthday field (of type Unix timestamp).

I need to be able to filter all profiles that have a birthday in the interval (-3 days from now to +7 days from now). How can I achieve this using views? Do I need to make a custom filter or custom contextual filter or some other custom plugin?

Thanks a lot for your input.

Update:

So I started building a custom filter with the following:

my_module/my_module.module

<?php

/**
 * Implements hook_views_data_alter().
 */
function my_module_views_data_alter(array &$data) {
  $data['node__profile_birthday']['birthday'] = [
    'title' => t('Filter by birthday'),
    'group' => t('Content'),
    'help'  => t('Filter profiles by birthday.'),
    'filter' => [
      'id'    => 'birthday',
      'field' => 'profile_birthday_value'
    ],
  ];
}

my_module/src/Plugin/views/filter/Birthday.php

<?php

namespace Drupal\my_module\Plugin\views\filter;

use Drupal\views\Plugin\views\filter\NumericFilter;

/**
 * Basic filter handler for Birthdays.
 *
 * @ViewsFilter("birthday")
 */
class Birthday extends NumericFilter {
  /**
   * Override the original Views opBetween behavior.
   */
  protected function opBetween($field) {
    // The birthdate is between -3 days and +7 days from the current date
    $expression = "DAYOFYEAR($field) BETWEEN ((DAYOFYEAR(CURRENT_DATE())) - 3) AND ((DAYOFYEAR(CURRENT_DATE())) + 7)";

    $this->query->addWhereExpression($this->options['group'], $expression);

  }

}

I am still having issues with views not properly saving the values of min and max of the between operator. Any help is appreciated.

So it looks like a custom filter is in order. They are relatively simple to make. There are a few tutorials out there. Look up “custom views filter handler” here or elsewhere. I’ve made custom contextual filters and sort handlers several times. “Contextual range filter” and “Views Raw SQL”. You can look at the code for them on Drupal.org. I think this would be a good candidate for something worth releasing as an official module. You could call it “Anniversary Date Filter” or something.

I thought you used to be able to add a filter, specify “less than” and type “now + 7 day”. Then add another “greater than” and type “now - 3 day”. Have you tried something like this?


Region for Main page content block field is required Error? I have created a custom region called latest. And when I am assigning some block to that region from admin, while saving it returns this error

  Region for Main page content block field is required.

What might be the reason?

This post helped me get closer, but I thought I would provide a more concise answer for those following the same path.

If you are looking to remove all blocks from Drupal 7, like you would want to do if you were placing blocks by using Context, you want to make sure that core's "Main page content" is the last block removed.

Steps:

Select "- None -" for all other blocks, then click Save.
Then change the "Main page content" block's region to "- Select -" and
click Save.

Just enable the "Main Content Page" block in Structure>Blocks then save. That will save the problem.


Fatal error: Class 'DrupalDefaultEntityController' not found in comment.module I'm trying to update the Drupal Core of a website, specifically from 7.65 to 7.67.
I've followed the instructions from here. After the process, I've try to access the website without luck, because I'm getting the following error: Fatal error: Class 'DrupalDefaultEntityController' not found in /var/www/html/modules/comment/comment.module on line 1698

I've tried to run the update.php file and clearing the cache from the db several times, without fixing the error. I've also tried to update from 7.65 to 7.66, but the problem persists.

What am I doing wrong?

UPDATE 1

I've tried to follow the instructions written here suggested by the user sivani. Here is the message I am getting:

DRUPAL_ROOT is /Users/DamianFox/tests/drupal-website/website.

Bootstrapping to DRUPAL_BOOTSTRAP_SESSION

Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in lock_may_be_available() (line 167 of /Users/DamianFox/tests/drupal-website/website/includes/lock.inc).

Additional

PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in system_list() (line 165 of /Users/DamianFox/tests/drupal-website/website/includes/module.inc).

%

After a bit of research, I found out that the problem might be generated from entity.inc inside the includes folder.
Therefore, I tried to put back the previous entity.inc (from the 7.65 installation); subsequently, I run the update.php script, and after another refresh, the website is finally accessible.
I done few more tests to check if there are warnings or errors, but everything seems to work fine, so somehow I got it sorted.

Try drush rr --fire-bazooka and see if that helps


How to make Drupal 6 search result URL use "-" instead of space? Example of Drupal 6 search result URL is like this:

http://www.site.com/search/node/Search for something

How to make Drupal 6 search result URL use - instead of space? (below is an example):

http://www.site.com/search/node/Search-for-something

You could add the functions custom_url_rewrite_inbound() and custom_url_rewrite_outbound() in the settings.php.

custom_url_rewrite_outbound() would rewrite the URLs which are output from any module, and custom_url_rewrite_inbound() would rewrite the URL being requested to Drupal.

This is the example code used in the documentation of custom_url_rewrite_outbound().

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  global $user;

  // Change all 'node' to 'article'.
  if (preg_match('|^node(/.*)|', $path, $matches)) {
    $path = 'article' . $matches[1];
  }
  // Create a path called 'e' which lands the user on her profile edit page.
  if ($path == 'user/' . $user->uid . '/edit') {
    $path = 'e';
  }
}

In your case, the code could be something similar to the following one.

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  if (preg_match('|^search(/[^/]+/(.+))|', $path, $matches)) {
    $path = 'search/' . $matches[1] . str_replace(' ', '-', $matches[2]);
  }
}

custom_url_rewrite_inbound() should do the exact opposite.
The code I wrote does not consider the case the - is included in the search string. The code should consider that case, for example adding another - where there is already one; when it does the opposite operation, the code should first replace a single - with a space, and then remove a - where there are more of those characters in row.

If you have installed pathauto module then Check admin/build/path/settings this setting.


Base path and user picture uploading So I recently migrated my site between servers. I think this is causing some issue with the base path of Drupal, which in turn affects the image upload path when a user tries to upload an image to his/her profile.

So, before migrating, some data was already uploaded to some of the users and their images and paths work just fine. The path is as follows for example:

www.example.com/sites/default/files/styles/thumbnail/public/pictures/picture-125-1377507580.jpg

But now, when I'm trying to add new users and when I upload new pictures, the image doesn't get uploaded and the path to the image is as follows:

www.example.com/new/?q=sites/default/files/styles/thumbnail/public/pictures/picture-125-1377507580.jpg

Why is this happening? How do I change the Drupal base path? Thanks

Firstly, it seems that the new server does not allow clean urls or it needs some configuration. Check the documentation on Drupal.org: Step 6: Configure clean URLs

Then, clean all caches and run cron. You will then see all image paths as /new/sites/sites/default/files/...

That's because the new site is set on folder ROOT/new or am I wrong? So there is no error, you have to set the domain to look at this subfolder.

If you don't have permissions to do this in your hosting or there are no options like Add-On domains you can follow the discussion at Drupal installed in subdirectory but made to appear in root according to your hosting enviiroment.

First of all mention $base_url = 'http://example.com'; in settings.php file. Then provide permission to your files folder. It should be at sites/default/files

Provide permissions:

cd /var/www/drupal_root/sites/default/
sudo chmod 777 -R files

Hope this helps


The directory sites/default/files is not writable on Mac OS X I had my website developed by someone else and it is currently working with no issues on our web server.  I'm trying to set the same site up on my Mac OS X 10.6 using the preinstalled Apache server, MySQL, and PHP5.  Also, it's Drupal 6.22 we're using.  I copied all of the website files (including Drupal and the .htaccess file) and put them in /Library/WebServer/Documents/website.  I then did a mysql backup on the server and imported that file on the local machine with phpMyAdmin.  I configured the settings.php file and everything else to work nicely so it can connect to the DB, etc.

Most of the site works as expected, however, there is a couple of nodes that won't work at all.  Instead I get this message when I go to them:

"The site is currently not available due to technical problems. Please try again later. Thank you for your understanding."

The weird part is if I enter in the URL to go to the edit page for that node it works, but I still cannot view the page.

When trying to search for problems that only issue I found anywhere is in the "Status Report" page it says the file system is not writable.  I get this message:

"The directory sites/default/files is not writable."

I checked the permissions and that folder has drwxr-xr-x set for it.

Any ideas as to what might not be set properly would be greatly appreciated.

The files directory in your site must be writable by the webserver. In the finder, do a Get Info on the files directory and assign read & write permissions to staff. (Make sure that this applies to any directories inside files as well.) Alternatively, in the terminal you could "chmod -R 775 my-site-path/sites/default/files" to take care of files and any contained subdirectories.

I had checked which user is running the "httpd" process. In my case it was "daemon".

  sudo chown -R daemon sites/default/files/
  had solved the problem (permissions: 775)


How to retrieve node body from nid with an SQL query in Drupal 7? From this question I learned that I have to look in field_data_body to retrieve the body of a node from a database.

field_data_body does not have an nid field though.

What query can I use to retrieve the body from an nid?

To clarify: I simply wanted to quickly fetch a text from a database dump without installing the dump on an actual site. So not looking for PHP here.

field_data_body does not have an nid field though.

Because a field can be attached to any entity, which may have a different primary key than nid.

If you really must use direct SQL, you can query the field like this

SELECT body_value FROM field_data_body WHERE entity_type = 'node' AND entity_id = 1

However, this bypasses several of Drupal's layers, so it's normally strongly discouraged to use direct queries.

Instead, it's better to

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('nid', 1)
;
$result = $query->execute();

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

foreach ($nodes as $node) {
  $bodies = field_get_items('node', $node, 'body');
  foreach ($bodies as $body) {
    var_dump($body['safe_value']);
  }
}

The EFQ version have several advantages

It's safe. You can't (easily) accidentally open injection attacks.
It outputs a safely escaped value, avoiding XSS attacks.
It works if a node has multiple values for the body field.
It works on sites with multiple languages.

In general, all entities are fieldable. Thus, the table field_data_body holds data for all body fields, regardless of being attached to a node or a comment. Hence, the column you are looking for is entity_id (with entity_type = 'node').

On a side node, you shouldn't tamper with the database in such a way, just use

$node = node_load($nid);
$body = node->body['und'][0]['value'];

to get the body (exact code of course depends on your site setup in terms of language, etc.).


Creating a thumbnail Navigation for a Flexslider I want to create this:

http://flexslider.woothemes.com/thumbnail-controlnav.html

Using Flexslider.

In Flexslider's Advanced Options I see there is an option to "Use as Navigation". I've tried setting another Flexslider slidehow (full of thumbnails) as the navigation but it doesn't seem to work right.

I just need to have a main slider and a slider under it full of thumbnails that acts as a navigation menu for the main slider. How can I do this?

Install Flexslider module
If you need to display images as a view, select "slider w/thumbnail controlnav pattern" option set in Flexslider display mode settings.
If you displays images a multi-valued image field, select "slider w/thumbnail controlnav pattern" for the field in Manage display tab.

Please note that controlNav pattern (you mentioned) is not the same as thumbnail slider.

Go to flexslider configuration menu in "Navigation and control tab" Select "page control" as thumbnail


How to alter the state of a radio button in an exposed filter to "checked" based on the view URL? I have a D7 site where I have several main topics, each containing subtopics.  I've made a views block which is shown on each of the pages of the main topics where you have two filter options:

Filter on main topic
Filter on subtopic

The idea is that when the user enters a URL like www.mysite.com/topics/maintopic, the main topic filter radio button is set automatically to the main topic the user entered and the first sub-topic for that main topic.

So how can I do that?  I tried with a contextual filter, but unless I missed something I don't see an option to preselect a radio button in an exposed filter (nor in fact to filter basing on the last part of a URL, unless it's an argument). I also tried the following code.

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  // ...
}

I didn't see any option to alter which radio button is selected.

You will need to use 2 contextual filters as each one takes a different argument, for example www.mysite.com/filter1/filter2.

You're confusing the difference between exposed filters and contextual filters, and their behaviour. An exposed filter is form based. As you want a radio button,  that's perfect. However, an exposed filter passes its values either via POST or GET; the only way to get these values through the URL is via the query string.

You can use hook_form_alter or hook_views_pre_render and check the url with $_GET or
  current_path() ,it's the fast and easy way.

Or you can play with Views create entity reference Filter (entityreference_filter) add your CONTEXTUAL FILTERS after that in your view add Reference Filter in Filter Criteria.