Customising user profile tabs I've customised the user profile tabs to look like a dashboard by using the generated classes and styling them using just CSS. Just to be clear, I haven't used any hooks or preprocesses to render the tabs, these are the default tabs that appear on the user profile.

I'm really pleased with the result! It all works fine and there's no bugs whatsoever as i've done it all through CSS:.

.logged-in.page-user {
  .dashboard-navigation {
    @include at-breakpoint($medium) {
      width: 20%;
      float: left;
    }
    section {
      padding: 0;
      margin: 0;
      max-width: 100%;
    }
    ul {
      padding: 0;
      margin: 0;
      border: 0;
      li {
        a {
          background: $lightgray;
          color: $darkgray;
          margin: 0;
          border: 0;
          text-transform: capitalize;
          display: inline;
          width: 50%;
          float: left;
          padding: .5em;
          color: $drupal;
          &.active {
            border-left: 3px solid $drupal;
            background: $white;
            &:after {
              content: "›";
              font-size: 2em;
              line-height: 0;
              float: right;
              margin-top: .25em;
            }
          }
          &:hover {
            background: $drupal;
            color: $white;
            &:after {
              content: "›";
              font-size: 2em;
              line-height: 0;
              float: right;
              margin-top: .25em;
            }
          }
        }
        @include at-breakpoint($medium) {
          display: block;
          overflow: hidden;
          a {
            padding: 1em 1em;
            text-align: left;
            display: inline-block;
            width: 100%;
            float: none;
            background: $lightgray;
            color: $darkgray;
            &:hover {
              background: lighten($gray, 10%);
            }
            &.active {
              background: $orange;
              color: $white;
              border: 0;
            }
          }
        }
      }
    }
    .secondary {
      clear: both;
      overflow: hidden;
      li {
        padding: 0;
        border: 0;
        a {
          background: $drupal;
          color: $white;
          &:hover {
            background: lighten($drupal, 10%);
          }
          &.active {
            color: $drupal;
            @include at-breakpoint($medium) {
              color: $white;
            }
          }
          &:after {
            margin-top: .3em;
          }
        }
      }
    }
  }

  .main-content {
    @include at-breakpoint($medium) {
      width: 80%;
      float: left;
    }
  }
}

Here's what i've come up with:

I'd like to take it a step further and add icons to each tab if possible like this:

I wasn't able to target the tabs using CSS as they all have general classes or non at all + obviously the tabs that appear depend on the role so I can't target them using pseudo nth-of-type selectors.

Maybe the solution is to add more specific classes but i'm open to ideas and some help on how I should go about it.

If the final addresses are known to be static, you could use destination specific information to identify each link

http://css-tricks.com/snippets/css/style-links-depending-on-destination/

If they include nodes of random values though, this might not work unless you can force the paths for the nodes to be predictable.


How can I disable specific layouts provided by contrib modules via the layout API? For example, the Bootstrap Kit module provides many layouts that I'm not using. Is it possible to only enable the specific layouts that my theme  needs?

Kind-of. With IPE you could use the patch in https://www.drupal.org/node/2849219.


Migrate to data field with multiple values I'm trying to use the migrate module to create products.
My issue is that I need to map data to a field that contains multiple values.

This is the exact case.

Product A has 3 prices,

Stand Price
Price for x to y qty
Price for x yo -1 (unlimited)

Using the commerce price tables module this has created the field data table with 3 fields, price, min_qty, max_qty.

Is it possible to map data to a field that contains multiple columns(values) with the migrate module?

Also the data is coming from another database.

I have not had any success using the addFieldMapping() function in the migrate module.

Regards,
Nathan.

I've worked it out.
Migrate can handle multiple values but due to the commerce price table having its own field type of 'commerce_price_table' I've needed to create a field handler for this field type.

Mapping is done like this in the migration class:(machine name for this field is field_volume_price)

$this->addFieldMapping('field_volume_price', volume_price);
$this->addFieldMapping('field_volume_price:currency_code',volume_price_min_qty);
$this->addFieldMapping('field_volume_price:min_qty',volume_price_max_qty);
$this->addFieldMapping('field_volume_price:max_qty',volume_price_currency_code');

Due to these fields holding arrays of data we need to create these in the prepareRow function in the migration class:

function prepareRow($row)  {
    foreach($row->product['volume_prices'] as $volume_price) {
        $row->volume_price[] = $volume_price['price'];
        $row->volume_price_currency_code[] = $row->product['currency'];
        $row->volume_price_min_qty[] = $volume_price['minimumQuantity'];
        $row->volume_price_max_qty[] = '';//this is unknown in our data, this is set in the handler
    }
}

If anyone is interested I've attached the handler. Also due to our set of data not containing the max qty value we had to work this out and set this in the arguments.(remove the loop if its set)

class ProductVolumePriceFieldHandler extends MigrateFieldHandler {
  public function __construct() {
    $this->registerTypes(array('commerce_price_table'));
  }

  public function fields($type) {
    // Declare our arguments to also be available as subfields.
    $fields = array(
      'currency_code'   => t('Subfield: Currency code for the field'),
      'min_qty'         => t('Subfield: Min Qty for the field'),
      'max_qty'         => t('Subfield: Max Qty for the field'),
    );
    return $fields;
  }

  public function prepare($entity, array $field_info, array $instance, array $values) {
    $migration = Migration::currentMigration();
    if (isset($values['arguments'])) {
      $arguments = $values['arguments'];
      unset($values['arguments']);
    }
    else {
      $arguments = array();
    }

    $language = $this->getFieldLanguage($entity, $field_info, $arguments);
    //we need to set the max value because the our data does not provide this
    if(isset($arguments['min_qty']) && !is_null($arguments['min_qty'])) {
        $minimumQuantity = $arguments['min_qty'];
        sort($minimumQuantity,SORT_NUMERIC);
        //create the max value of the ranges, eg:
        //min qty: 1,3,5,20
        //1-2,3-4,5-19,20--1

        //reconstruct the arguments array with qtys in order
        //$index becomes the new delta
        foreach($minimumQuantity as $index => $min){
            $args['currency_code'][$index]   = $arguments['currency_code'][array_search($min,$arguments['min_qty'])];
            $args['min_qty'][$index]         = $arguments['min_qty'][array_search($min,$arguments['min_qty'])];
            $args['max_qty'][$index]         = isset($minimumQuantity[$index+1])?$minimumQuantity[$index+1]-1:-1;
        }
        if(isset($args)){
            //set arguments array for new ording
            $arguments = $args;
        }
    }

    $delta = 0;
    foreach ($values as $value) {
        if(!is_null($value)) {
            $return[$language][$delta] = array('amount' => ($value * 100));
            if (isset($arguments['currency_code'])) {
                if (is_array($arguments['currency_code'])) {
                    $return[$language][$delta]['currency_code'] = $arguments['currency_code'][$delta];
                } else {
                    $return[$language][$delta]['currency_code'] = $arguments['currency_code'];
                }
            }
            if (isset($arguments['min_qty'])) {
                if (is_array($arguments['min_qty'])) {
                    $return[$language][$delta]['min_qty'] = $arguments['min_qty'][$delta];
                }else {
                    $return[$language][$delta]['min_qty'] = $arguments['min_qty'];
                }
            }
            if (isset($arguments['max_qty'])) {
                if (is_array($arguments['max_qty'])) {
                    $return[$language][$delta]['max_qty'] = $arguments['max_qty'][$delta];
                }else {
                    $return[$language][$delta]['max_qty'] = $arguments['max_qty'];
                }
            }
        }
        $delta++;
    }

    return isset($return) ? $return : NULL;

  }
}


Placing a programatically created menu I'm creating a menu programatically using this code
$this->menu = $this->entityTypeManager->getStorage('menu')->create(
    [
      'id' => $properties['id'],
      'label' => $properties['label'],
      'langcode' => $properties['language'],
      'status' => TRUE,
    ]
  );
  // Save the menu.
  $this->menu->save();

When visiting the block ui I see the block is already created. It appears that I do not have responsibility for creating this block, although I don't seem to be able to load the block straight after creation of the menu. I need to place this block in a specific region programatically. What would be the preferred method of doing this be?

After an intensive debug session I discovered the block is actually created when you place blocks and select the menu you have just created through the Block UI. That didn't fit with my requirements to place the block programatically so I took a look at the structure of an existing menu block and replicated that.
$this->block = $this->entityTypeManager->getStorage('block')->create(
    [
      'id' => $this->getBid($form_state->getValue('language')),
      'region' => 'header',
      'plugin' => 'system_menu_block:' . $this->menu->id(),
      'settings' => [
        'id' => 'system_menu_block:' . $this->menu->id(),
        'label' => $this->menu->label(),
        'provider' => 'system',
        'level' => 1,
        'depth' => 0,
        'expand_all_items' => FALSE,
      ],
      'theme' => 'mytheme_base_theme',
      'visibility' => [
        'language' => [
          'id' => 'language',
          'langcodes' => [
            $form_state->getValue('language') => $form_state->getValue('language'),
          ],
          'negate' => FALSE,
          'context_mapping' => [
            'language' => '@language.current_language_context:language_interface',
          ],
        ],
      ],
      'weight' => 100,
    ]
  );
  // Save the block.
  $this->block->save();

This achieved the result I was looking for. So far so good. I can now create menus and place them immediately after the menu is created.


How to store value of variable if it is changed inside of ajax callback function? I have a form with several ajax callback functions.
And I have a variable which should change its value inside these  callback functions.
Unfortunately, I have faced with a problem. Namely, I don't know how to store the value of the variable after change. Because after the callback function executed the value is lost.

There is a little example of code.

class MyForm extends FormBase {
    public $i = 0;

public function buildForm(array $form, FormStateInterface $form_state){
    ...
    $form['add_more'] = [
        '#type' => 'submit',
        '#value' => 'Add More ...',
        '#ajax' => [
            'callback' => '::addMore',
        ]
    ];
    ...
}

public function addMore(array &$form, FormStateInterface $form_state){
    ...
    $this->i++;
    ...
}
}

Here the variable $i doesn't increase its value whenever the button is being pressed.
Could you clarify, what should I do if I want the variable to increase its value whenever the button has been pressed ?

The ajax callback is not for form logic. It's only supposed to send back a new version of $form or part of it in a wrapper. Or in more advanced cases a collection of ajax commands.

Use instead buildForm(). You can check which button was clicked with $form_state->getTriggeringElement().

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $i = $form_state->get('elem') ? $form_state->get('elem') : 1;
    $trigger = $form_state->getTriggeringElement();
    if (isset($trigger['#ajax']['callback']) && $trigger['#ajax']['callback'] === '::addMore') {
      $i++;
    }
    $form_state->set('elem', $i);

    $form['counter'] = [
      '#markup' => $form_state->get('elem') ?? 1,
    ];

    $form['btn'] = [
      '#type' => 'button',
      '#value' => 'Btn',
      '#ajax' => [
        'callback' => '::addMore',
        'wrapper' => 'ajax_wrapper',
      ]
    ];

    return $form;
  }

  public function addMore(array &$form, FormStateInterface $form_state){
    return $form;
  }

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

  }


How can I monitor the number of user password reset requests? I would like to keep track of the number of times users request that their password be reset to make sure that users are able to reset their password successfully.  I am getting reports a couple of times a month that users are experiencing difficulty resetting their passwords; to see how common this is, I want to see if users are requesting their password be reset several times in a row (within the same day).

To do this, I was thinking of e-mailing myself every time a user requests that their password be reset.  My first instinct was to do this with Rules, but there is no Event like "When a user requests that their password be reset."

Note, in user_pass_submit

watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));

There's already a watchdog log entry created when the user requests a password reset.

Perhaps you can simply monitor the watchdog log at

Admin > Reports > Recent log entries?


Unable to submit rendered field I have a custom form with text field and a submit button.

$form['bid_amount'] = array(
  '#type' => 'textfield',
  '#title' => t("Your Bid"),
  '#prefix' => '
',
  '#suffix' => '
',
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Calculate your bid'),
  "#ajax" => array(
  'callback' => 'custom_callback',
  'wrapper' => 'test-ajax',
  'method' => 'replace',
  'effect' => 'fade',
  ),
);
}

What I want to do is, when 'bid_amount' is empty, and button is clicekd, 'bid_amount' should be rendered again with a prefilled value.
This is what I can do.
But at this time, when again button is clicked, with FILLED field of 'bid_amount', it shows up again with suggested value. Actuly it should be submitted this time.

Here is how I am rendering this ....

function custom_callback(&$form, &$form_state) {

    $next_bid = 100;
    return array(
      '#type' => 'ajax',
      '#commands' => array(
        ajax_command_replace("#test-ajax", render($form['bid_amount'] = array(
              '#type' => 'textfield',
              '#title' => t("Your Bid"),
              '#value' => $next_bid,
              '#prefix' => '
',
              '#suffix' => '
',
        ))),
      )
    );
}

I was facing the same issue.  I think the render function doesn't add "name" to the html so the form values are not submitted. I fixed this by adding them in the array

'#attributes' => array(
  'class' => array('edit-bid-amount'),
  'name' => 'bid_amount'
),

The function now is

function custom_callback(&$form, &$form_state) {
  $next_bid = 100;
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace(
        "#test-ajax", render($form['bid_amount'] = array(
          '#type' => 'textfield',
          '#title' => t("Your Bid"),
          '#value' => $next_bid,
          '#prefix' => '
',
          '#attributes' => array(
            'class' => array('edit-bid-amount'),
            'name' => 'bid_amount'
          ),
          '#suffix' => '
',
          )
        )
      ),
    )
  );
}

Hth,
Sadashiv


How do I set permissions for a subdirectory that Drupal creates when uploading a file? I'm using Drupal 8 and the Flysystem module to configure remote file storage via SFTP. My question probably applies in general, though.

When a file is uploaded, and the file directory setting has a value, then Drupal creates a subdirectory if it doesn't already exist in the remote location. For example, the file directory defaults to [date:custom:Y]-[date:custom:m] to organize files by month. I need to set the permissions of these subdirectories. Currently, they're defaulting to 744. How do I change this? I'm hoping there is either a global setting, a hook, or a way to set the permissions in a module.

Thank you in advance for your help!

A standard Drupal would use Core's FileSystem class to create directories and set permissions according to the file_chmod_directory setting, which you can adjust within your site's settings.php files:

/**
 * Default mode for directories and files written by Drupal.
 *
 * Value should be in PHP Octal Notation, with leading zero.
 */
# $settings['file_chmod_directory'] = 0775;
# $settings['file_chmod_file'] = 0664;

It defaults to 0775 and is therefore commented out in a regular installation.

However, you mentioned using the Flysystem stream wrapper module. A short look into it's code reveals, that it is indeed using the FileSystem::CHMOD_DIRECTORY constant as default for local files. But the final directory permissions can vary depending on the Flysystem adapter plugin you are using. Something that is out of our control here at Drupal Answers. It's a contrib module anyway. So you will have to check yourself, of whether your adapter plugin supports the Core setting values/allows to configure it by other means. If not, you may wish to file an issue against the module that is providing the adapter you are using.


Is it possible to provide logins based on purchases? There shall be an online shop with drupal commerce. It is required that a visitor can buy a digital product, i.e. a ticket with a barcode that he can print out. The visitor shall not be able to create an account.

The visitor must provide his email when buying a ticket. When the visitor finishes the payment process a pdf (a ticket with a barcode) and a unique id are generated (an id for that purchase if you will). A visitor can buy multiple tickets, but everything that is bought in one process has the same purchase id.

Is it possible to let that user "login" with his email and the generated id, given an overview of all the tickets the user bought related to that purchase id?

Background of this is: a user shall be able to see the bought tickets to be able to print them again. But one email address can be used several times, not meaning its everytime the same user.

Example:

Visitor foo@bar.com makes a purchase with 2 tickets, t1 and t2, id abc is generated.

The visitor can then "login" using the credentials foo@bar.com and abc "as password", seeing tickets t1 and t2.

Two days later, another visitor with the same email address makes another purchase, buying a ticket t3 and generating the id def. Hours later, he wants to print the ticket again, he can login using the mail foo@bar.com and the "password" def, showing ticket t3.

If he used password abc instead, he would be shown tickets t1 and t2.

YOu don't need a real login, just an access to a certain node. For this, you can use the Node autorize link module:

  Generates link for view, edit, or delete content without login

So, when someone pruchases something you must create a node tieh the data tue user can view. Add the view authorize link to the purchase email notification and the customer will have access to the node with data just following the emailed link.


What is the URL for the login form? I am trying to log in on a Drupal site, but the site doesn't have the login block enabled.

How can I find the URL for the login form?

Drupal default login URL format,

example.com/user


What is difference between field tables? What is the difference between a content_field_myfield and field_data_field_myfield in the db?

First used for field in Drupal 6.x versions.

Second used for fields in Drupal 7.x version.


How can I translate the name of a vocabulary? I am looking for a solution through which Vocabulary name can be translated.
I'm using the i18n module with latest D7.

Currently I have chosen the option like so:

  Translate. Different terms will be allowed for each language and they
  can be translated.

Here is a screenshot to illustrate that option:

I am able to translate terms of this vocabulary as shown in the screenshot below:

Problem Statement: How can I translate the vocabulary name, i.e. "Test Vocabulary English" in my example above.

Typical taxonomy translation issues

My best guess is that you are experiencing the typical taxonomy translation issues, as described in the community documentation about Taxonomy translation also. While digesting that, you may want to verify one of its comments, which is about using the Title module also.

The closest I have come so far with translated terms (and without using the Title module), is similar to the setup you have done so far. The result of it being that when you want to select a term from a taxonomy on a language specific node, you get a list of all terms to select from (with all terms from all languages). Not the ideal solution, but similar to what is written in the URL I mentioned, and probably "as good as it gets in D7".

Translate vocabulary name

If however you're only looking for a way to translate the vocabulary name (as the title of your question indicates), then be aware that that is simply not possible today, and is actually a known issue: Vocabulary Name value doesn't get translated. It dates from 2005 (!), related to D6, status "won't fix". However comment # 2 in that issue states:

  I have used the locale module to translate the name of the vocabulary, and display it with t($vocabulary->name). If all modules would display the name this way (e.g. taxonomy_menu does it), then there is no need for a new database table i18n_vocabulary.

The t($vocabulary->name) seems like a possible/partial work around to consider, i.e. from within a (custom) module.

There is a more recent similar issue, i.e. Vocabulary names are not translated. That one is for D7, with status "needs work".

Another potential work around could be to have a separate taxonomy for each language (and with a "name" corresponding to that language). Of course, you'd have to think how to best use these separated taxonomies for each content type (a kind of "solution to the problem, changes the problem) ...


Can I override the title attributes on an H2 tag within a specific drupal region or block? I have a region within a site theme I'm working on, and would like the H2 title attribute to be white as opposed to the rest of the theme which calls for a blue. Can I use CSS to assign specific font size and color attributes to the title tag for that specific region/s within the theme?

You can use CSS to style the H2 tag inside a specific block.

Your block should have a unique ID, based on the name of the block.

Your CSS would look something like this:

<style>
#block-your-blockname h2 {
 color: white !important;
}
</style>

Note: you may not need "!important", and that CSS can go in your main CSS file if you want.


Add custom field to taxonomy term I added a custom field to a taxonomy term via 'Manage Fields' (see screenshot here: https://cl.ly/022v2B2H2c1m). How can I display this new field in the Frontend? In my template.php I have this:

$cats = taxonomy_get_tree(7);
$categories = array();
if (!empty($cats)) {
  foreach ($cats as $cat) {
    $parent = $cat->parents[0];
    $item = array(
      'tid' => $cat->tid,
      'name' => $cat->name,
      'description' => $cat->description,
      'image' => $cat->field_images,
      'children' => array(),
    );

  }
}

When I do a var_dump($item), the image field shows 'NULL', although I added an image.

Anybody with a solution?

Best wishes

You can use this -

$term = taxonomy_term_load($tid);
$field_image = field_get_items('taxonomy_term', $term, 'field_image');
if ($field_image) {
  $headerimg = field_view_value('taxonomy_term', $term, 'field_image', $field_image[0], array('type' => 'image'));
}
print render($headerimg);

In your file template.php use the theme_preprocess_page function like this :

function mytheme_preprocess_page(&$vars) {
  $term = menu_get_object('taxonomy_term', 2);
  if ($term) {
    $field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
    if ($field_header_image) {
      $vars['headerimg'] = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
    }
  }
}

Then in you page.tpl.php you can print render($headerimg);


How do I actually change the site name on a localized site? Even after changing the settings in /admin/config/system/site-information, the page title still contains "Drupal".

All external examinations of the site configuration (config table and exported files) show the new name.

I examined the function template_preprocess_html() in theme.inc (where the configuration value is supposed to be loaded and entered in the theme variables), and inserted the following var_dumps:

var_dump(\Drupal::config('system.site')->getRawData()['name']);
var_dump(\Drupal::config('system.site')->get('name'));
var_dump(\Drupal::config('system.site')->getOriginal('name'));

The resulting output is string(12) "My Site Name" string(6) "Drupal" string(6) "Drupal".

The configuration value isn't overridden anywhere in the site's settings files either. All caches are cleared.

Why is ->get('name') returning the wrong value even though ->getRawData() contains the correct one?

Edit: I should probably add that this is a site with a non-English default language. That seems to be the cause of nearly all the configuration-related core bugs. However, the langcode of the sytem.site configuration entity is correctly set.

Edit: More digging reveals that the language module is indeed responsible for overriding the configured name with the default name.

Edit3: There doesn't appear to be a way to set the localized site information without editing the configuration externally. I exported it, deleted the file language/de/system.site.yml and re-imported, which fixed it. (In the production site, importing didn't remove the deleted configuration entity; I had to delete the language.de/system.site record from the config table directly.)

The key to translating the configuration entities and objects is the core module config_translation (Configuration Translation).

This provides extra routes for every form that edits site settings or config entities, which allow editing the translations of translation-enabled config strings.


WSOD while sending headers, probably Cache-related I have a very strange problem with a fresh Drupal install: On some pages, I receive a WSOD with ERR_EMPTY_RESPONSE:

It happens for instance when on admin/config/development/performance I click Clear all caches. (But also other pages are affected – for instance the Layout Builder page of a Node type.)

Interestingly, I could isolate the bug down here: If in vendor/symfony/http-foundation/Response.php::sendHeaders() I tweak the code so that it unsets a lot of the headers to be sent (actually, all of them but X-Generator and X-Frame-Options), the error disappears.

...
$headers = $this->headers->allPreserveCaseWithoutCookies();
unset($headers['Cache-Control']);
unset($headers['Content-language']);
unset($headers['Date']);
unset($headers['X-Drupal-Dynamic-Cache']);
unset($headers['X-UA-Compatible']);
unset($headers['X-Content-Type-Options']);
unset($headers['Expires']);
unset($headers['Vary']);
foreach ($headers as $name => $values) {
  ...

Based on the headers I unset, it seems that it is a caching-related problem. (However, Caching is switched off, Browser and proxy cache maximum age is set to <no caching>.)

My setup:

installed Drupal 8.7.5 via composer
on my local machine, a MacBook Pro with macOS High Sierra
installed via Homebrew

PHP 7.3
Apache 2.4
MySQL 5.7.24

Any idea what the problem might be?

Edit: Regarding Apache error logs: I first had no entries there but now I debugged again and saw such one:

[core:notice] [pid 92592] AH00052: child pid 98466 exit signal Bus error (10)

Googling gave the suggestion to apc_clear_cache(); but it's not available in PHP7. So I ran opcache-reset().

Result: Problem is still there, now already when opening the page admin/config/development/performance.

Now the error logs say:

 [core:notice] [pid 7428] AH00052: child pid 7446 exit signal Segmentation fault

Google suggests this is likely  caused by a syntax error in php.ini or some included extension there. Thus I have taken out all extensions, including

zend_extension=/usr/local/opt/php/lib/php/20180731/opcache.so

but the problem remains.

Edit 2: Here's the output of my php -i (It uses the same php.ini file as phpinfo() in localhost). https://pastebin.com/ppvCpPA6

Now I could solve it myself. My Apache error logs did show

AH00052: child pid 7363 exit signal Segmentation fault (11)

so it must have been a problem with the Apache config.

I took the opportunity to reinstall Apache and configure it with FCGI/FPM according to this and now the problem is gone.


Drupal 7.10 upgrade theme problems I was running with Drupal 6.22 and tried doing an upgrade to drupal 7.10.
The upgrade reported everything was successful.

My problem is that I was previously using a theme called 'contrast'.
I thought that I had disabled it, but it now has references to that theme.

How can I get around these errors?

I tried moving garland into the all/themes folder and renaming it to contrast, but that only created another set of errors.

Notice: Undefined variable: site_name_and_slogan in include() (line 14 of   /mysite/sites/all/themes/contrast/page.tpl.php).
Notice: Undefined variable: site_name_and_slogan in include() (line 14 of /mysite/sites/all/themes/contrast/page.tpl.php).

Chose another default theme, disabled & deleted the 'contrast' directory. Clear your cache to make sure, but there should be nothing trying to reference a theme that isn't there.


AJAX checkboxes in Views to change node values I have a use case in D7 where I need to make a listing of nodes in table format, and included in the fields are checkboxes that us AJAX to do  things like publish/unpublish a node and set other field values in the node.  I know I saw merlinofchaos mention somewhere that there is a way to do this in Views, but I haven't been able to find details on how.  I can do it easily enough by creating a table and manually filling the cells, but I would like to use Views if I can.  Does anyone know how this can be done?

Thanks.

If you can "do it easily enough by creating a table and manually filling the cells," you can easily leverage Views' global custom text field along with rewriting to create whatever you need.  For example, create a view with whatever you want in the fields, just make sure one of them is nid. Then add a global custom text field after all of them and craft up whatever AJAX divs or spans or ids etc you need to call your functions, substituting the nid token where necessary in the markup.  Make sure that javascript is including on your page and you should be on your way.


Check if user_picture value is changed or compare with old value I am trying to find if a field value is changed or updated by the user. But there are blockers.

function custom_form_process_user_picture(&$form, FormStateInterface &$form_state) {
  $file_name = "";
  $username = "";
  $fid_0 = NULL;
  $user_picture = $form['user_picture'];
  $uid = $form_state->getValue('uid');
  if ($form_state->hasFileElement() && $form_state->hasValue('user_picture')) {
    $username = $form_state->getValue('field_name')[0]['value'];
    $fid_0 = isset($form_state->getValue('user_picture')[0]['fids'][0]) ? $form_state->getValue('user_picture')[0]['fids'][0] : $fid_0;
    /*
      $changed = $form_state->get('user_picture')->getValue() == $form_state->getValue('user_picture');
      //This is not working as $form_state->get() returns null.
    */
    /*
      $changed = $form_state->get('user_picture')->getValue() == $form['user_picture']['#default_value'];
      //This is not working as $form['user_picture']['#default_value'] is null.
    */
      if($changed) {
        // Proceed to rename the file.
      }
    }

What piece of the code I am doing wrong? Searched drupal and stackoverflow for the changed/updated/dirty field value. Also tried with $form_state->getFormObject()->getEntity() and got no clue if there is old value stored or not.
FormStateInterface seems to have no method to find out altered/modified values.

Perhaps you should use hook_entity_presave that keeps the old (original) value

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

  if($entity->getEntityTypeId() == "file"){

    $filename = $entity->getFilename();

    $file_old = $entity->original;

    if($file_old != null){
      $filename_old = $file_old->getFilename();

      if($filename_old !== $filename){
        $entity->setFilename('newfile.jpg');
      }
    }
  }
}

The function above changes the filename if its not the same as old filename.

Depending on your use case you might want to apply the above logic when user is presaved

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity)
  if($entity->getEntityTypeId() == "user"){

    // get specific field by field machine name
    $file = $entity->get('field_file');

    // or get the user_picture field
    $picture = $entity->get('user_picture');

    $user_old = $entity->original;
    // drill down in the old user object to see values changes
    // and do appropriate changes
  }
}


How do I get the content type name using code? I'm working on Drupal 8 and I want to get content type machine name and label. Here is my code:

$cont_type = node_type_get_types();
foreach ($cont_type as $key => $value) {
  $label = $value->name;
  $machine_name = $key;
}

I get the following error message:

  Cannot access protected property Drupal\node\Entity\NodeType::$name

Hoe can I get the content type name?

To get a property, there is ConfigEntityBase::get(). Since ConfigEntityBase is a base class for NodeType, you can always use $value->get('name') to get the value of the name property.


Views Taxonomy selection and display I am displaying a list of taxonomy terms for registered users on a Node and the user is asked to make multiple selections depending on what appeals to them. e.g what are their Top Ten song choices for 2016

I would like them to put that same list of taxonomy terms with their 2016 choices (Selected) within a View and I would like to email them that View list in 2017 and ask them to check if its still correct and or to make amendments to their choice to reflect their choice for 2017.

I can get the Views list to display the list of taxonomy terms, but how do I get check boxes to display with ticks with past choices for 2016 in Views and then store the changes for 2017?

Perhaps I'm overlooking something and this should be very simple.

Anyway, thanks in advance.

This can be achieved using following approach.

Create a content type for example "Favorite song" and add a field of "Term reference" type into this content type where widget will be "Check boxes/radio buttons" and select the vocabulary of songs for options.
Give permission to users to add/edit content "Favorite song",then while adding user will select their favorite songs from the list of songs.
Again to view/edit favorite song list of a user you can find the correct node by author of the node.

Hope it will help.


commerce_line_item VS field_data_commerce_line_items Right now, I am touching the database for drupal 7. I searched about the difference between "commerce_line_item" table and "field_data_commerce_line_items" table. But no luck.

Does anyone know the difference between them? Also, is there any reference that I can follow to check the table explanation?

I really appreciate anyone's help.

UPDATE

Based on everyone's help and my own opinion, I drew a simple diagram for these two tables:

My answer concerns the structural and not the semantic difference between the two.

The table field_data_commerce_line_items corresponds to a standard drupal field. On the other hand commerce_line_item is a table that is managed by one of the modules in the commerce module family.

The table field_config_instance describes the relationships between drupal fields (which are actually tables such as field_data_commerce_line_items) and higher level entity types (i.e. node) and bundles (i.e. content type) that reference them.


Migrate error: Call to a member function count() on a non-object I am trying to implement a user migration with the migration module but am getting this error:

  Fatal error: Call to a member function count() on a non-object in
  E:\wamp\www\website\sites\all\modules\migrate\includes\migration.inc
  on line 946

here is my migrate class:

abstract class CakeBaseMigration extends Migration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->team = array(
      new MigrateTeamMember('Chris', 'chris@somewhere.com',
          t('developer')),
    );

    Database::addConnectionInfo('for_migration', 'default', array(
      'driver' => 'mysql',
      'database' => 'databasename',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'prefix' => '',
    ));

  }
}

class CakeUserMigration extends CakeBaseMigration {
  public function __construct($arguments) {

    parent::__construct($arguments);
    $this->description = t('Lagacy cakePHP system customers');

    $query = Database::getConnection('default', 'for_migration')
    ->select('customers', 'c')
    ->fields('c');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationUser();

    $this->map = new MigrateSQLMap($this->machineName,
        array('id' => array(
          'type' => 'int',
          'not null' => TRUE,
          'description' => 'Account ID.'
        )
        ),
        MigrateDestinationUser::getKeySchema()
    );

    $this->addFieldMapping('username', 'name');
    $this->addFieldMapping('pass', 'password');
    $this->addFieldMapping('mail', 'email');
    $this->addFieldMapping('created', 'modified');
    $this->addFieldMapping('roles')
    ->separator(',')
    ->defaultValue(DRUPAL_AUTHENTICATED_RID.',4');

  }
}

running the drush command drush migrate-audit --allsays that that cakeUser is missing a source and destination.

I don't get it, Setting the database and running the query at devel/php returns the expected rows from the database.

Any help on this would be fantastic :)

It seems the problem was the files not saving properly after I updated them, The code I posed above seems to be working ok now.


New role assigned on user account update I'm thinking about writing a condition ("has new role(s)") using the Rules module to send an email to user to whom a new role is assigned. I need to know how to actually code this...

If (user has a new role(s)) {

  //   do something

}

I think that, by comparing whether a user has a role before saving and after saving or updating the content, one could tell whether a new role assigned. But I can't figure out how to code it and what API I should use. Please advise.

Just found a way to do it without coding. Works well so far.

EVENT: After updating an existing user account

CONDITIONS:

1) Data >> List contains item - LIST: "account-unchanged:roles", ITEM: "Role A" (Check NEGATE)

AND

2) Data >> List contains item - LIST: "account:roles", ITEM: "Role A"

ACTION: Send mail

Ref: http://goo.gl/Pcz2wN


How to get hook_form_FORM_ID_alter field value in hook_ENTITY_TYPE_presave I am adding one field dynamically by using hook_form_FORM_ID_alter.

/**
 * Implement hook_form_FORM_ID_alter
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function hook_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    // Modification for the form with the given form ID goes here. For example, if
    // FORM_ID is "user_register_form" this code would run only on the user
    // registration form.

    $form['platforms'] = array(
        '#type' => 'textfield',
        '#title' => 'Add Platforms',
        '#required'=>True,
    );
}

"platform" field is added dynamically here, now I want this field value in hook_ENTITY_TYPE_presave.

/**
 * Implement hook_ENTITY_TYPE_presave
 *
 * @param \Drupal\node\NodeInterface $node
 */
function hook_ENTITY_TYPE_presave(\Drupal\node\NodeInterface $node){
    if($node->bundle()=='platform'){
        $field_platforms = $node->get('platforms')->getValue();// Here how to get platform field value.
   }
}

I am not getting any idea how do this any help very appriciate.

The form field you've added is not a node field.

If you want the field to be accessible in the node, then add it to the content type. In this case you don't need a form alter hook, because the entity fields are added to the form automatically. You can create multiple form modes with and without the field and select them dynamically, for example with Form mode manager.

If you don't want the field to be stored in the node, but want to do something else with the user input, then add a custom submit handler in the form alter hook to process the field value.


Changing background color in table when status is changed I have table in VIEWS who stores from webform so i want to make is
When user select green from webform, then those informations need to be with green background, if other user select blue, that need to be blue in my table with results.

You can add use fields as classes to table rows and then through CSS assign background color to it. Check the screen shot, in the screen shot I have used a field as Row class. You will get your field replacement pattern in "Rewrite the output of this field" for all fields.


How do I remove the site name from the page title on a particular page? I have unchecked the sitename in admin/build/themes/settings but all of the titles of pages are still showing the site name.

I am not sure why this happens. Is there any other way to remove it?

I have installed the Page Title module, and in admin/settings/page-title I have the page title set as [page-title] for that particular page, not as [page-title] | [site-name].

Try the Page Title module. Here is a quote about it (from the module's project page):

The word "title" is a bit overloaded. Every piece of content in Drupal has a title, and so does every page. The page title is the one found in the HTML head inside the  tag. It is also used on SERPs (Search Engine Result Pages) and can greatly enhance your websites SEO (Search Engine Optimization).
This module gives you granular control over the page title. You can specify patterns for how the title should be structured and, on content creation pages, specify the page title separately to the content's title.


Simple field to display static data I am trying to do module with different share buttons in form of field to content type. It has no settings, I just need to enable it in admin panel and the button should appear on node. But I cannot get to work simple sample of code like this:

function fblike_field_info() {
    return array(
        'fblike' => array(
            'label' => t('Facebook Like'),
            'description' => t('This field displays Facebook Like button.'),
            'settings' => array(),
            'instance_settings' => array(),
            'default_widget' => 'fblike_default_widget',
            'default_formatter' => 'fblike_default_formatter',
        ),
    );
}

function fblike_field_widget_info() {
    return array(
        'fblike_default_widget' => array(
            'label' => 'Like Box',
            'field types' => array('fblike'),
        ),
    );
}

function fblike_field_formatter_info() {
    return array(
        'fblike_default_formatter' => array(
            'label' => t('Like Box (default)'),
            'field types' => array('fblike'),
        ),
    );
}

function fblike_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
    $link = '

';

    $element = array();
    $element[0] = array('#markup' => $link);

    return $element;
}

The result of this code is:

Like:&nbsp;

I already run out of ideas. I have created many modules with fields before, but none was that simple... Am I missing something?

Ok, got this. As far as my field has nothing in $items, in order to print something I had to use this snippet:

function fblike_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
    foreach ($entities as $id => $entity) {
        if (empty($items[$id])) {
            $items[$id][0] = 'something';
        }
    }
}


VBO calls entity_save after custom action is triggered. How to stop that? I have VBO custom actions defined and it gets triggered. Also, I do NOT have 'behavior' => array('changes_property') defined in my hook_actions_info() as described in How to create custom VBO action?

I see that my custom action is getting triggered and does custom operations and finally saves by creating new node revision. Weird part is that entity_save operation is being called after this and it is updating node table with older version of node rather than new vesrion created by custom funtion.

How can I stop or prevent vbo to call entity_save and just perform custom action?

Any insights will be greatly helpful.

Thanks!

This is an old issue, but I literally just had the same problem and after banging my head off of it all day I found upon a solution through the d.o issue queue.

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

I applied the patch from #42 and it solved it right away after setting 'behavior' => array().

Hope this helps someone else.


Multiple image styles Is there a way to take multiple style image for one image field?
I want to use a 150×150, 180×180, and a 300×300 style at the same time.

If I understand your question correctly, you'll want to use the ImageCache module. This is in core as of Drupal 7. Try the documentation for Drupal 6 and/or this screencast if you need help understanding how to use this module.


Drupal7 - How to display both summary and body on full view? It probably has an easy solution, but I couldn't figure out how. I have the original "Article" content type with an image and a summary field. Summary is readily displayed on front page, but in full view, only the body is displayed, but I want to display both the summary and the body. I will have articles where the summary is an eye-catch for the article, but I want to display and style it differently on the full view page too. I am free to edit templates or modify drupal settings so any method vill be fine with me.

Edit: I managed to print the summary with

print render($content['body']['#items'][0]['safe_summary']);

Is this a good way to print the summary?

It would be better to use print drupal_render( field_view_field('node', $node, 'safe_summary') );.

This will also handle i18n.


What's the difference between 'attachment before' and 'block' in views? Recently I followed a tutorial in views which listed taxonomy and gave me a short list above the view with hyperlinked first characters of taxonomy name. In this case, I created a "block".

In investigating the default Glossary view, I see the same hyperlinked first characters of title created by using "Attachment before".

Are there advantages of using one method over the other?

Block - separate views display that can be outputted in any region of the site.
Attachment - views display that can be outputted in addition to another views display, so you can attach this display to output of another views display.

Attachment has some special options like Inherit contextual filters:Yes, Inherit exposed filters:No, so you could use one exposed filters form for both displays.


"The pdf.js library could not be found." (PDF module) I installed pdf.js with the PDF module in an effort to show pdf on the fly on my Drupal 7 site. I keep Drupal 7 constantly upgraded on Ubuntu on an instance an AWS.

I installed the module using drush which placed the module at sites/all/modules/pdf. I then copied pdf.js to: sites/all/libraries.

After installing I have created a new content type called PDF and I added a file field that is able to only include a pdf file.

I selected the display to show: "PDF: Default viewer of PDF.js". I then added a content with a PDF file in it selected and uploaded.

While trying to show it I get the message: The pdf.js library could not be found. And down the page: pdf: Please download and install pdf.js!

Can anyone help?
Where do I put the JS file?
Is there a problem with the FDF module?

The path will be like this /sites/all/libraries/pdf.js.

pdf.js is a FOLDER not a FILE. It is very strange to have a folder with a DOT in the name.

I have attached a screenshot on the folder hierarchy that works.

SUMMARY:

The folder in your libraries folder must be named: pdf.js, you will have to rename the top folder of anything you download to pdf.js (in this instance pdf.js is not a FILE, but the container of the library)
See screenshot for the correct file hierarchy.


Webform import via Webform Share Question: How can I import a Webform via the https://drupal.org/project/webform_share API?

What do I know/current state: The API shows a graphical UI to do it, but I'd need a way to do it via an exported function, if any (e.g. a function call like webform_share_import($formspec)).

Reason/scenario: Because I want to install some forms in the .install of a module.

Found: there's not an exported API, but an implementation of a regular form hook for the UI, which does all the magic (webform_share.module:123).


Where are service saved? Where are services saved?
With Drush cr they are read, but I do not understand where they are saved
(In non-database I find them)

They are stored in the {cache_container} table of the database. The services themselves are declared in [MODULENAME].services.yml.


Custom content in auto generated menu I have been working on a website that contains a main dropdown menu generated by Drupal (7.28). Is there any way I can add a link to it between the other links that shows content generated by me in the dropdown? So instead of: fetch pages, fetch something else (defined by me).

Thanks in advance =]

Every module on your site can be found in the list on /admin/structure/menu.
just click 'list links' and then 'add link' to add a link to a menu.


Rules - How can I put a link into an email sent by a rule I would like to use rules to send an email to my admin staff when a new piece of content is created.  It would be great if the email contained a link to the content to make it easier to find.  Is there a way to insert the link?  Perhaps there is a token that I could use.

You can use the following: [site:url]user/login?destination=node/[node:nid]/edit.

This will show login form to the users who are not authenticated and then redirect them to the node edit page.

If the user is already logged in, he/she will be immediately taken to the node edit page.


How to get custom indexed field to show up in view? I have a custom field I have added to my search index, and I have confirmed that there is data being indexed there, and I can query against it in a view using my global index.  But when I add the custom field as a display field, the field doesn't render.

I'm noticing the same behavior when I add the urls with the AddURL processor.

I can see the fields are there, and I can query against them with filters, but when added to a view as a field, they won't display.

I noticed that if I go into SearchApiQuery.php on line 527 and change this:

foreach ($result->getFields(FALSE) as $field_id => $field) {

to this

foreach ($result->getFields() as $field_id => $field) {

Then the view displays the results, but it also causes a lot of lag, and is obviously a hack I don't want to do.

What am I doing wrong?  Why can't I display a custom solr indexed field in a view?

It took a while, but I figured the issue out.

You have to set your solr server configuration within Drupal to return fields at /admin/config/search/search-api/server/

Here's the text on that settings page:

"Retrieve result data from Solr:
When checked, result data will be retrieved directly from the Solr server. This might make item loads unnecessary. Only indexed fields can be retrieved. Note also that the returned field data might not always be correct, due to preprocessing and caching issues."

Basically, if you want to pull data directly out of solr, you have to have this checked.  I don't think you can do this at the view level.


What replacement token to use for counting a specific content-type I have a content type of 'partners', and I wanted to create a body text like 'Currently we are working with X partners'. I have token-filter working, but I cannot find a token that allows me to choose the content-type.

[content-type:node-count] Doesn't do anything.

[node:content-type:node-count] Returns the amount of the current type (basic page, not partner).

Is there some token that allows me to choose the content-type to work with? eg. something like [content-type:?:node-count] where I can enter my content-type of partner on the ? ?

I ended up creating a custom module for this to calculate the specific amount of items. Now I can use a token like [partner:partners].

/**
 * Implements hook_token_info().
 */
function partner_token_token_info() {
  $types['partner'] = array(
    'name' => t("Partner Tokens"),
    'description' => t("Tokens for partners."),
  );

  $partner['partners'] = array(
    'name' => t("Partners"),
    'description' => t("The count of partners."),
  );

  return array(
    'types' => $types,
    'tokens' => array(
      'partner' => $partner,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function partner_token_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'partner') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'partners':

          $query = db_select('node', 'n')
            ->condition('type', 'partner');
          $num_rows = $query->countQuery()->execute()->fetchField();

          $replacements[$original] = $num_rows;
          break;
      }
    }
  }

  return $replacements;
}


move fields in the user profile form in fieldsets I want to move the email address fields in the user profile form (user/1/edit) in a custom fieldset. I have this code:

$form['change_mail'] = array(
    '#type' => 'fieldset',
    '#title' => 'change email address cake',
    '#weight' => 6,
    '#collapsible' => FALSE,
    '#tree' => FALSE,
);

$form['change_mail']['mail'] = $form['account']['mail'];
unset($form['account']['mail']);
$form['change_mail']['confirm_mail'] = $form['account']['confirm_mail'];
unset($form['account']['confirm_mail']);

But I get an error when I try to change my email address: undefined index 'mail' in user_account_form_validate() (line 1232 of /modules/user/user.module). Apparently, I can't 'unset' the fields. But I don't know how to get rid of them.

As you mentioned the problem appears in user_account_form_validate() because you changed the account index from $form['account']['mail'] to $form['change_mail']['mail']

the issue is with this line form_set_value($form['account']['mail'], $mail, $form_state);

In order to achieve what you are looking for you need to replace existing form validation with a custom validation as the following code:

function MODULE_NAME_form_user_profile_form_alter(&$form, &$form_state, $form_id) {

  $form['change_mail'] = array(
    '#type' => 'fieldset',
    '#title' => 'change email address cake',
    '#weight' => 6,
    '#collapsible' => FALSE,
    '#tree' => FALSE,
  );

  $form['change_mail']['mail'] = $form['account']['mail'];
  unset($form['account']['mail']);
  $form['change_mail']['confirm_mail'] = $form['account']['confirm_mail'];
  unset($form['account']['confirm_mail']);

  $form['#validate'][0] = 'MODULE_NAME_user_account_form_validate';
}

function MODULE_NAME_user_account_form_validate($form, &$form_state) {
  $form['account']['mail'] = $form['change_mail']['mail'];
  // original validation function
  user_account_form_validate($form, $form_state);
}


Drupal 8, save new fieldCollection items to user from a foreach loop doesn't work My user structure have a multiple field "foo" of type "FieldCollection". From a custom module, I want create programmatically several fieldcollection item and add them to the current user.

Without any loop, when I add only one new FieldCollection item to the user, its work. But, when I want user a loop for add several FieldCollection, only the first item is added. I mean :

With some light php :

// In my module
    // some operations and prepare the datas structure
    foreach(datas as data){ // count(datas) = 2, by example
        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $field_collection_foo = FieldCollectionItem::create(array('field_name' => "field_foo"));
        $field_collection_foo->set("field_data",$data);
        $field_collection_foo->setHostEntity($user);
        $field_collection_foo->save();
    }

Then if I go to the user edit page from the back office, I see only the item datas[0] added, not datas[0] datas[1]

Where is my mistake ?

UPDATE (add some test) :

I think I find, I do an another $user->save somewhere in my module and I think its it who save the wrong value :) Ill test it

Make sure you've configured the cardinality of the field collection foo as unlimited (or at least anything more than 1) under "Field settings".

Also double check the name that you are passing to the FieldCollectionItem::create() method. It shouldn't be the label name but the machine name of your foo field collection, which will probably be field_foo:

$field_collection_foo = FieldCollectionItem::create(
  array('field_name' => "field_foo")
);

This also applies to the subfield_data (in your field collection item):

$field_collection_foo->set("field_subfield_data", $data);


Is the Dutch translation incomplete? Using kickstart 2-rc4 I seem to miss some Dutch translations (I used the 2.x translation file).

If 'Add a product' ('Voeg een product toe') is translated, then why would 'Manage products' not be translated? The Dutch .po file does indeed not contain a translation for this, but it seems weird, if you would translate the one, why not translate the other?

Am I doing something wrong here?

You can try importing the translation file again; it is possible that the connection timed out and that some of the translations were not inserted.

However, if you check the .po file and you can't find the translations of those strings - it means that whoever was translating the terms did not finish them all.

You can translate missing terms yourself within Drupal at admin/config/regional/translate/translate or download Poedit and contribute translations back here.


composer and Lightning I have composer.jon to require

"acquia/lightning": "2.1.3",

This installs Drupal core 8.3.3. Can I change this to Drupal core 8.3.2 or does Lightning force you to use the Drupal version its packaged with?

I updated this post after fixing the problem. I changed the composer.json file and specified what drupal core version to use like this.

    "acquia/lightning": "2.1.3",
    "drupal/core": "8.3.2",

Looks like you've largely answered your own question. But to confirm, Lightning generally does not pin to a specific version of core in it's composer.json file. The current constraint is ~8.3.1 (note the tilde) which means the current release of Lightning should work with core 8.3.1 to 8.3.9(repeating) but not 8.4.0.

Core is the exception to the rule. Lightning normally pins to specific versions of dependencies if they are patched (see Lightning's dependency constraint logic). But since core follows SemVer, has predictable releases, and Lightning releases every time core does, Lightning doesn't pin core - even when it is patched (which is pretty much always).

Lightning increments the second digit of its release numbers (the minor release) when Drupal makes a minor release. In the current release of Lightning (2.1.4) the one relates to the three in the current release of core (8.3.3). So Lightning 2.1.x should run on any core 8.3.x. That's why Lightning uses the tilde (~) modifier and three digits when specifying Drupal core constraints.


How do I edit individual meta tags on a panelized page? Setup I have: Drupal 7, Panopoly 7.x-1.30, Metatag 7.x-1.13

I've installed and enabled both the metatag and metatag_panels modules. Perhaps I'm just not looking in the right place, but I don't see any way to add custom metatags (title and description) to an individual panelized landing page.

On an individual node page (which isn't panelized), I can click the "edit" tab, and at the bottom is a form that lets me customize the metatags for just that node. But if I click the "edit" tab on my landing page, there is no such form. Clicking the "customize this page" button which invokes the panelizer doesn't seem to offer any way to edit the metatags, either.

I've read the documentation and searched the drupal.org forums, but nothing has made a solution clear to me.

Apparently it has nothing to do with the panels; the Metatag plugin just doesn't support landing pages. Converting the needed landing pages to customized content pages solved my problem.


\Drupal::database()->select with Expression used as Condition I am trying to execute this query:

'SELECT sd.entity_id AS entity_id, WEEK(node__field_start_date.field_start_date_value) AS week, YEAR(node__field_start_date.field_start_date_value) AS year
FROM
{node__field_start_date} sd
INNER JOIN {node__field_plane_reservation} pr ON sd.entity_id = pr.entity_id
WHERE (sd.bundle = :db_condition_placeholder_0) AND (pr.field_plane_reservation_target_id = :db_condition_placeholder_1) AND (week = :db_condition_placeholder_2) AND (year = :db_condition_placeholder_3)'

And I am using this piece of code:

    $database = \Drupal::database();
    $query = $database->select('node__field_start_date', 'sd')
  ->fields('sd', ['entity_id']);

    // Expressions
    $query->addExpression('WEEK(sd.field_start_date_value)', 'week');
    $query->addExpression('YEAR(sd.field_start_date_value)', 'year');

    // Conditions
    $query
  ->condition('sd.bundle', 'reservation', '=')
  ->condition('pr.field_plane_reservation_target_id', $refPlane, '=')
  ->condition('week', $weekNo, '=')
  ->condition('year', $weekYr, '=');

    // Join Tables
    $query->join('node__field_plane_reservation', 'pr', 'sd.entity_id = pr.entity_id');

And whenever I execute it, it give me the error:
Unknown Column 'week' in query or Unknown column 'year'.
How do I use a condition with a pseudo column created with an expression?

// Where Expressions
    $query->where('WEEK(sd.field_start_date_value) = :weekNo', array(':weekNo' => $weekNo));
    $query->where('WEEK(sd.field_start_date_value) = :weekYr', array(':weekYr' => $weekYr));

Apparently this can be achieved with $query->where();


Programmatically execute an action set (Rules module) I want to use Rules UI to define some action sets, but want to execute those actions programmatically from a custom module.

How to I execute the action by code and pass the needed arguments (just a node in this case).

Thanks!

If you have set it up as a rules component, you can use rules_invoke_component, alternative you can invoke an event, which could trigger mutiple rules by using rules_invoke_event.

Both is similar in that you pass first a name/id and the rest of the args is passed along, so something like

 rules_invoke_component('name', $node);

if your custom component rule has several parameters pass them one by one and separate them with comma as example

rules_invoke_component('rules_save_search_send_activation_sms',  'paramval1', 'paramval2', ....);

is properly how you need to do it. This again depends on how the rule/component is defined and configured.


How to access field values from a custom block How do you give a custom block (in a custom module) access to field values produced by the context of page?

eg: If the page has a field, say 'field_my_custom_id' and I want to use it for some purpose in the Build function of a custom block, how to access it from within my module?

At the point when you build your block you don't know what other code will put in the page.

As alternative you can use the routing system, because the route is resolved in the bootstrap process (in D8 the symfony framework) before any custom code is run:

if ($node = \Drupal::routeMatch()->getParameter('node')) {
  $field_my_custom_id = $node->field_my_custom_id->value;
}

Of course you don't know if other code will put this field on the page, but you know that the url of the page will produce the specific node as main content.


User uploads media and community votes: How do I implement them? I am a graphics guy who can fumble through code, but not write it from scratch. I have developed a NUMBER of sites, but this is my first Drupal experience. I've read all the starting documents, been playing with Drupal for DAYS now; I have even installed and modified different modules, so I'm somewhat familiar with it and the concepts (nodes, vocabularies, etc).

I have installed Drupal 7.2 on MDD Shared Hosting. I am looking to build a community site (actually a NUMBER of them very similar to this one once this is completed). They are very similar to these sites:
- colourlovers.com
- instructables.com
- gdgt.com (somewhat).

The concept is that the users will upload various pictures/video & a description to a page, and then the rest of the community will be able to 'like' it (not in a Facebook way, though). The pages with the most 'likes' will appear in the home page and various search/sideboxes (top rated by time/date, newest, most viewed, etc). For example, a user uploads a video and/or pictures of some artwork. He'll write a short statement about it and 'publish' it to the community. Once published, other users will be able to see it, comment on it, and rate it if they choose to. There are different categories for each type of upload (vocabularies, etc), as well as tagging, comments, etc.

Users can also 'follow' their favorite members to easily keep track of any new pictures/media they post, comments they make, etc. It would be fairly similar to the sites mentioned above.

My problem is that I just don't get where/how to go about doing this. I have designated various vocabularies, installed a few different gallery modules. I really don't think I want a gallery for this, as each 'project' a user uploads will be separate from all the others they upload (but it can still be found/visible in the author's profile page). Is there a module that pretty much does this functionality?  Alternatively, is there a key concept that someone could explain to me on how to handle something like this? I could even pay a little bit to have someone set it up for me. However, I want to learn how to do it, so I can maintain the site later and build future sites in the same way.

Surely you need Views, which allows you to create a view of specific nodes; if the users of your site are allowed to votes on the content, you probably want to offer a list of the most voted notes, or the less voted nodes.

As per rating a node, there are many modules that can be used. Part of them requires the Voting API module, such as Fivestar, Rate.
Which one to use depends on how the users are allowed to vote. The Rate module allows the users to up-vote and down-vote. With Fivestar, they are allowed to give a vote from 1 to X (where X is normally 5); they are not allowed to down-vote, which means the rate cannot be a negative number.

The Flag module allows the users to flag a node for a specific reason; by default the module comes with the "Add to my bookmarks" flag that can be, in your case, changed to "Add to my followed." Thanks to the integration with Views, Flag creates a view listing all the nodes flagged with a particular flag; such view can be per user, and in this case each user has a view for the nodes they flagged, which is visible as tab in their user profile, or it is global, and in this case the view is not specific for a user but every user can add nodes to that list.


Getting user photo url and profile url using views_json I'm using the views_json module in Views Datasource to send some information in JSON format to a related website.  I've got a bunch of content views built, but now I'm trying to build staff pages.  I've got most of it working fine, but when I try to add the user picture I end up with an empty field, When trying to find a url for the user's profile page (using User: Link), I got the text "view", leading me to believe that when drupal tries to output the content as a link, views_json returns the link text.  I just want the url in plaintext, I don't need the html for a link.  How can I get the user picture, and the absolute url to the user profile in views_json?

Image fields for my node views work just fine, I get field_image.src and field_image.alt elements in the JSON that is returned, with the Use picture I get a blank field or a series of \n´s

To get the user pic url, you can do it using Image URL Formatter. Once enabled, when you click on the user picture field, you will now see a formatter option, select image url.

For the user, assuming this is a user view, in FIELDS add the User: Uid as a field and checkmark ☑ exclude from display.

Now, add Global: Custom text as a field. In the text box, put http://ultrabob.com/user/[uid]

I got [uid] from replacement patterns. Side note, in order for fields to appear as a replacement pattern, they must be above the current field.

Else, if you're using pathauto so the user pages are /user/[username] then add the User: Name field instead and use the [name] token.

Now, if your view is a content view, ex: shows articles, then you will need to add a relationship of node author first, once you do that, the user fields will become available to be added as a field.

  OK, that issue got me sorted with the pictures, I'm now working on the
  solution for profile page link. Can you think of a good way to get the
  domain part of the url (http://ultrabob.com/) in your example
  dynamically in views from the site configuration. I would like this to
  continue to work without modification as it is deployed across test
  servers and onto production

You can using php. Ex: <?php echo $_SERVER['HTTP_HOST']; ?>

Either you could enable the Views PHP module, but remember to turn it off on production, or use a template file.

views-view-field--[view-name]--views-data-export--[field-name].tpl.php

<?php

$fields["field_name"]->content = 'http://' . $_SERVER['HTTP_HOST'] . '/user/' . $fields["field_name"]->content;

echo $fields["field_name"]->content;


Display two Views blocks with equal height I have created two Views Blocks "NEWS" and  "BLOG", which resides side by side on my front page.

Both the views have 20 contents (but can be any number) in it and a pager. How do I display contents in views block, so that the both views end up with equal height regardless of number of contents displayed.

Try using the equal heights module

  This module implements a jQuery Equal Heights plugin that can equalize
  the height of the elements of the specified class.

  To use it, give the elements the same class, then go to the
  administration interface and add this class (separate multiple classes
  by a space). By default, it sets the height to the height of the
  tallest element but you can also specify minimum and maximum height.

To use the just give both the blocks the same class and add the admin name in the admin interface of the module and then js will do the rest.


Migrate content alone We are using Drupal 8.5.X. As of today, we dump the complete DB to move from one environment to another. My concern is doing this, there are few sensitive information like user info or audit logs will be migrated to each environment. So I want to see whether we can migrate only contents and not the entire DB.

We use config_split for migrating the contents. We tried https://www.drupal.org/project/content_sync.. but looks like it is broken in the new Drupal. Any other modules or suggestions?

You might want to take a look at Workspace, which which was added to Drupal core (8.6.0) just a month ago. It's mainly about content moderation and let's you prepare content on one site that then can be published to another site.

So maybe, if you wanna stick to your setup of one live (master) site and multiple dev (slave) sites, then you could let Workspace push just the content from live to dev – if it works this way.

Unfortunately, I can't find any really good documentation about Workspace. And yes, it has been added to core as an experimental module. But I'd say, you should give it try and can maybe contribute your experiences back :)


How to conditionally render fields with a different formatter I have a content type with two fields one called display which is a simple list and the other is an entityreference field.

I would like to change how the entity reference field is rendered depending on which option is selected in the first field.

I have custom formatters installed and I have created two custom formatters so I need a way of changing the #formatter based on the result in the first field.

I've tried a hook_preprocess_node() and also changing it in a custom tpl file but neither seem to render the field any differently to how it is set in the manage field UI.

I would try using the Context module API and adding a new reaction plugin.


Unit Testing code that retrieves content I have a method which calls another one to retrieve a specific node ID. If it can be found, it then retrieves the node.

Is this the kind of functionality that can be tested in Drupal? Or even should it tested? If so what is the best approach for it?

private function retrieve() {
  // Call another method to get IDs of specific bundle based on its workflow status. We get just one ID back as there is only one node for this bundle.

  // If statement to validate we do have a node ID.
  // Call method to retrieve content for node based on the retrieved `nid`
  // Return node content if any has been found

  // If no content is found return FALSE.
}

By definition, when unit testing your function you should focus on the logic the unit delivers, which, in your case, is the following conditional logic:

IF (nid IS NOT FOUND) OR (a node for a found nid HAS NO CONTENT)
  => FALSE
ELSE
  => NODE.CONTENT

That being said, you could:

Mock the two internally-used methods:

methodA:

CaseA1: returns an empty result (no nid found)
CaseA2: returns X as a nid
CaseA3: returns Y as a nid

methodB:

CaseB1: Given X as a parameter returns an empty result (no content found)
CaseB2: Given Y as a parameter returns some dummy content

Assert that the retrieve() method returns for each of the following cases:

CaseA1: FALSE
CaseA2+CaseB1: FALSE
CaseA3+CaseB2: TRUE

This is not very "deep" testing, but your function does not carry much logic. It is still testable in this minimal way.

Good luck!


How to use a custom template for a custom view in Drupal 7? I'm working with panels and views. I'm trying to understand how to create a  view and also create a custom template for that view. I'm able to create the view through the Drupal admin and also create the demo.tpl.twig template (using twig, rather than php for templating), but not sure how to tell Drupal to use a specific template for my view.

Any and all help is appreciated. Thanks.

You dont need to tell drupal use your template to display output. In your view, click on Theme: Inforamtion (at bottom right), see the file names in Display Output and Style Output section (Last file in both the sections). Create files with same name and save them at sites/all/themes/YOURTHEME/templates directory.

To design whole page use last file from Display Output and to design each row use last file from Style Output. First create and save the files. Then click on Display Output or Style Output, copy the code and paste it respective file. Use your HTML/CSS to design the page. Clear the cache and you will see the result.


How can I get the filesize of an image with an image style programmatically I need to make two links for an image, one link points to a low res version the other to the original file.

I'm creating the link for the low res with image_style_url

<?php print image_style_url('img-lib', $data->field_field_photo[0]['raw']['uri']) ?>

How can I print out the filesize of the image with img-lib style?

You can get the size of the original image easily:

$size = filesize($data->field_field_photo[0]['raw']['uri']);

But the size of an image file behind a derivative path is impossible to get reliably. The files aren't generated until the URL is first visited, so the file may simply not exist yet.

For those that do already exist, you can use image_style_path():

$path = image_style_path('img-lib', $data->field_field_photo[0]['raw']['uri']);
if (file_exists($path)) {
  $size = filesize($path);
}

If it's 'mission-critical' to get the file size, you can always force-create the derivative there and then with image_style_create_derivative():

$path = image_style_path('img-lib', $data->field_field_photo[0]['raw']['uri']);
if (file_exists($path)) {
  $size = filesize($path);
}
else {
  if (image_style_create_derivative('img-lib', $data->field_field_photo[0]['raw']['uri'], $path) === TRUE) {
    $size = filesize($path);
  }
}

if (!isset($size)) {
  // Something went wrong creating the derivative...
}

It's worth noting that you shouldn't do all (or any really) of the above directly in a template file. Instead, move your logic out to a preprocess function and pass variables in.

And if you're looking for full-on 'best practice', instead of accessing the field data directly through the array (e.g. $data->field_field_photo[0]['raw']['uri']), prefer field_get_items() for procedural-style, or an EntityMetadataWrapper if you're comfortable with OO.


How can I override strings? I'm trying to change a label of Drupal 8's contact form ('Your email address'). The label is defined /core/modules/contact/src/MessageForm.php, but obviously I don't want to change this in core.

$form['mail'] = array(
'#type' => 'email',
'#title' => $this->t('Your email address'),
'#required' => TRUE,
);

In Drupal 7 I always used string overrides but the module isn't available for Drupal 8 yet. How can string be overridden in Drupal 8?

The easiest method would be to implement a hook_form_alter inside a custom module that overrides the title

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.2.x

Some information how to create custom module.

https://www.drupal.org/docs/8/creating-custom-modules


How to delete lines from a table created by a custom module? I'm working on a custom module that has an admin form designed to contain a number of values.
age 21 => value, age 22 => value, etc.

The issue I'm having is that while I can add information to the table I've created through my form, I'm only supposed to have 1 possible value per age.
I dont know how to delete the old value before the new one is added.

This is what I have that adds info to my table successfully:

/**
* Saving Score administration settings and DB information
*/
function savingsscore_admin_form() {
  $form = array();
$form['savings_ages'] = array(
  '#type' => 'fieldset',
  '#title' => t('Saving Ages'),
  '#weight' => -1,
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
  '#description' => t('Description of fields in this fieldset here'),
);
$form['savings_ages']['saving_age21'] = array(
'#type' => 'textfield',
'#title' => t('21'),
'#size' => 10,
'#maxlength' => 10,
'#default_value' => '10.85',
);
  return $form;
}

/**
* Handle submission of Admin forms
*/
function savingsscore_admin_form_submit($form, &$form_state) {
db_query("INSERT INTO {savingfactors} (saving_age21)
VALUES ('%s')",
  $form_state['values']['saving_age21']);

drupal_set_message(t('Your form has been saved.'));
}

I know that what happens next should start like:

 db_query("DELETE FROM

But I dont know what I should add next, I'm uncertain of the syntax.
Any help or links to documentation would be much appreciated

Thanks
Stephanie

You will find an answer here.

Basically you can use Drupal's drupal_write_record() to let Drupal handle that.

Or you can run a SELECT query first and an UPDATE or INSERT based on SELECT's result.

EDIT:

Based on information gathered in comments, it seems that the "savingfactors" table has several columns and only one row. If the row is already present, with any value, then a simple UPDATE query is enough. Here's an example:

function savingsscore_admin_form_submit($form, &$form_state) {
  db_query("UPDATE {savingfactors} SET saving_age21 = '%s'", $form_state['values']['saving_age21']);
  drupal_set_message(t('Your form has been saved.'));
}

That way you overwrite only saving_age21 field, ignoring others.

You can do the same with any other field you want to save.

There's an initial requirement: the row must exist. You can manually create it with a db client software, or you can implement Drupal's hook_install() inside your module .install file.


Alter field widget settings fields I'm trying to alter the settings fields displayed when you click on the cog icon on the "Manage form display" admin screen.
More specifically I want to alter fields set by another module through hook_field_widget_third_party_settings_form
I finally found the solution so i'll share it here as an answer.
It was not that hard, but I had to dig a bit into the core code in order to figure out how to do it.

The form_id we want to alter is entity_form_display_edit_form
Because the settings fields are loaded through ajax, we first have to check if we are currently editing a field settings by checking  $form_state->get('plugin_settings_edit')
The fields we are looking for are then located at  $form['fields'][FIELD_NAME]['plugin']['settings_edit_form']
function fintech_form_entity_form_display_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $field_name = $form_state->get('plugin_settings_edit');
  if(!empty($field_name) && isset($form['fields'][$field_name]['plugin']['settings_edit_form'])) {
    $form['fields'][$field_name]['plugin']['settings_edit_form']['third_party_settings']['whatever_you_want_to_alter'] = '';
  }
}


Render Content Labels and Values In my node--content_type.html.twig template file, I can output both the label AND value of a field by using:

{{ content.field_title }}

I can also render just the label of a field with:

{{ content.field_title['#title'] }}

So far, so good.

However, how can I output only the VALUE of a field using the content array? I've tried:

{{ content.field_title['#value'] }}

And:

{{ content.field_title.value }}

To no avail.

Thank you for any help.

To get the field value without the label:

{{ content.field_name[0] }}

  BONUS

  If your field allows for multiple values, just increase the 0 to get the
  other values.

  {{ content.field_name[1] }} {{ content.field_name[2] }} ... and so
  on.


Center header logo in Bartik theme I am using the Bartik theme in Drupal 7.15 and would like to have the header logo centered rather than left-aligned, is there some little piece of CSS I can add in with drupal_add_css() that will center the logo image? I need it to center correctly based on the width of the header image, so fake centering just using left padding isn't an option.

Thanks in advance.

A rule like this should do it:

#logo {
  display: block;
  width: 100px; // width of the image
  margin: 0 auto;
}


do some work when user login or register in drupal6 I want to set some fields in database when user registers or login. I know I don't have to change the drupal core and I guess I should use hooks for this purpose but I don't know how and where.

Should I write a new module and implement a hook inside it? What hook?

In drupal 6, there is a function named hook_user.

By using this hook in your custom module. You can do watever you want. Remember to put condition in this by '$op' like

function hook_user($op, &$edit, &$account, $category = NULL) {
  if($op == 'login') {
    //do watever you want
  }
}


Inline js inside a form I'm trying to attach inline js inside a form, but it's not working out. Is there anything wrong with below code

$form['#attached']['js'][] = array(
    'data' => 'jQuery(function() { console.log("test"); });',
    'type' => 'inline',
);

You seem to be trying to use method for adding settings. I believe this is the correct way as stated on the docs:

$form['#attached']['js'] = array(
  'jQuery(function() { console.log("test"); });' => array(
    'type' => 'inline',
  ),
);

Docs: #attached


Hook for when a new content type is created? Does a hook exist for when a new content type is created?  If so what is it?  I've looked through the API and nothing has jumped out at me.

hook_node_type_insert() is invoked from node_type_save() after the node type is added to the database.

See:
hook_node_type_insert()


Editing a footer menu in a theme How can I edit a footer menu in theme like Bartik, currently its displaying the menu in vertical format and I want it in horizontal format. Any idea how I can go about editing this.
e.g.
current:
Menu 1
Menu 2
Menu 3

Desired: Menu 1| Menu 2| Menu 3

You can do this using CSS

Firstly you will want to create your own theme using bartik as a base.

Copy /themes/bartik to /sites/all/themes/YOUR_THEME
Rename bartik.info to YOUR_THEME.info
Edit YOUR_THEME.info, Make Changes, name = YOUR_THEME, description = YOUR_DESCRIPTION
Edit template.php replace all instances of 'bartik' with 'YOUR_THEME'
Goto /admin/appearance
Find YOUR_THEME Enable and set default.

Why do we do this? Never hack the core or contributed modules and themes, If you do, updates will be a nightmare.

Now you will need to find the "id" of the menu element. In Chrome right click on the menu and 'Inspect Element' you may need to click up and down in the code window to find the relavant container. Example: id='block-system-user-menu' for the user menu block.

Modify /sites/all/themes/YOUR_THEME/css/style.css I will use 'block-system-user-menu' as an example.

Add this code (depending on your id).

#block-system-user-menu li,
#block-system-user-menu ul.menu li a {
  border:none;
}
#block-system-user-menu ul.menu li a {
  float:left;
  border-right:1px #fff solid;
}
#block-system-user-menu ul.menu li.last a {
  border-right:none;
}

That's it done!

You could also use the superfish module at http://drupal.org/project/superfish This will allow you to have a horizontal menu from any of your menus with some default styling or the ability to style it yourself in the same way as outlined above if you prefer. It is also an easy and clean way to get drop-down menus on your site.


How to make sure you're not on the production website in Drupal 7? I remember seeing some kind of module where it lets you know that your on a staging / dev site without the risk of you editing the main production site. Or is there other methods that others use to prevent accidents from happening.

Environment Indicator is designed to do that:

  This module will help you to keep sane while working on your different environments by adding a configurable color bar to each one of your environments. The Environment Indicator adds a coloured bar on the site informing you which environment you're currently in (Development, Staging, Production, etc.). This is incredibly useful if you have multiple environments for each of your sites, and like me, are prone to forgetting which version of the site you are currently looking at.


View content based on if a new session is created I am running a Drupal 7 website using the Ubercart module. I am trying to show some HTML content when users get on the site, and not keep viewing it when they click on a certain button. I need this piece of content to appear at the top of the website so I tried putting it in the HTML in the page.tpl.php file, which works, but then it keeps appearing every time the user goes to a different page or reloads the page. The way I am thinking of approaching this is as follows:

1) A new session is created when a user lands on the site.

2) If a new session is created, I will copy that session's value into another variable ($variable = session_id();), and execute some code when the content of $variable is equal to the value returned from session_id().

3) I will have that piece of content as a <form method="POST">. When the user clicks on the close button, that will $variable = $variable + 1;.

4) This way the if statement will be FALSE for this session and the content won't appear anymore.

my problem is with knowing if a NEW session has been created or not. I have tried using if (drupal_session_started()) { echo "s";} ?> but that doesn't print anything which means I still can not check for new sessions started. Shortly, I need a way to know if a new session has been started on the site, so I can do the mentioned steps. Bonus if you tell me what you think about how I'm going about doing this, because I'm a Drupal newbie and there might be easier solutions.

On Drupal, when a new user logs in, a new session is started; when the session expires, the user must log in again. You just need to use the hook that Drupal uses when a user logs in, which is hook_user_login(). Take system_user_login() as code example.

function system_user_login(&$edit, $account) {
  // If the user has a NULL time zone, notify them to set a time zone.
  if (!$account->timezone && variable_get('configurable_timezones', 1) && variable_get('empty_timezone_message', 0)) {
    drupal_set_message(t('Configure your account time zone setting.', array('@user-edit' => url("user/$account->uid/edit", array('query' => drupal_get_destination(), 'fragment' => 'edit-timezone')))));
  }
}

Keep in mind that PHP variables don't persist between sessions. If, for example, you need to show the content only once for users, you need to use code similar to the following one.

function mymodule_user_login(&$edit, $account) {
  if (variable_get("mymodule_show_message_{$account->uid}", 1)) {
    // Show the message.
    variable_set("mymodule_show_message_{$account->uid}", 0);
  }
}

For anonymous users, you cannot count on the session being saved between two different page requests. Drupal, at the end of a page request, destroys the session for anonymous users, if it is empty. See drupal_session_commit().

  if (empty($user->uid) && empty($_SESSION)) {
    // There is no session data to store, destroy the session if it was
    // previously started.
    if (drupal_session_started()) {
      session_destroy();
    }
  }

For a solution that works for both the anonymous users and authenticated users, I would rather implement hook_page_build(), although this has the side effect of always creating the session for anonymous users, with all the consequences.

function mymodule_page_build(&$page) {
  if (empty($_SESSION['mymodule_page_disclaimer_shown'])) {
    // This is a new session. Show the disclaimer.
    $page['page_top']['disclaimer'] = array(
      '#markup' => t('Acme, Inc. is not responsible for the contents of this sample code.'),
      '#weight' => 0,
    );
    $_SESSION['mymodule_page_disclaimer_shown'] = TRUE;
  }
}

In this way, since the session is not empty, it won't be destroyed from Drupal after serving the page. The second time the anonymous users visit the site using the same computer/browser, the disclaimer will not be shown.


Create Block Programmatically I am learning Drupal 8, i know how to create block programmatically in Drupal 7.

Can anyone please suggest how can u create block and render that block in more than one region in Drupal 8?

The 'id' property in the annotation defines the unique, machine
   readable ID of your block.

The 'admin_label' annotation defines the human readable name of the
   block that will be used when displaying your block in the admin
   interface.

The 'Category' defines which section belongs to under block listing page.

The Drupal block manager scans your module's classes for a class that contains the @Block Annotation (a special comment right above your class declaration)

<?php
/**
 * @file
 * Contains \Drupal\article\Plugin\Block\XaiBlock.
 */
namespace Drupal\article\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 * Provides a 'Article' Block
 * @Block(
 *   id = "article_block",
 *   admin_label = @Translation("Article block"),
 * )
 */
class ArticleBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#type' => 'markup',
      '#markup' => 'This block list the article.',
    );
  }

custom block programatically


form_set_error message delayed one page refresh I'm making a custom validation in a form I'm making but my error message is always delayed by one page refresh.

$form['submit']['#validate'][] = 'asap_sollicitation_form_validate';

function asap_sollicitation_form_validate($form, &$form_state)
{
    if(strlen($form_state['values']['pass']) < 6){
        form_set_error('pass', t('Must be longer than 6'));
    }
}

It successfully marks the field in red but the message is delayed. If I use only drupal_set_messsage without the form_set_error I do get a message displayed in time.
I render my form in a node template:

$arr = drupal_get_form('asap_sollicitation_form');
print drupal_render($arr);

How can I get my message to display after form submit?

I had the same, here is the solution and explanation:
The key of this problem is the drupal_get_form('FOO') is called in theme layer. For example _preprocess_WHATEVER or directly in BAR.tpl.php

The messages are prepared in _process_page()  After that it's unchangeable in deeper theme functions, like FOO_preprocess_node. (That's not exactly true, but it's out of scope of this topic.)

I bet, you prepared a variable by drupal_get_form('FOO') in _preprocess_node, maybe later.

You should use hook_entity_view_alter or hook_node_view_alter, maybe hook_page_alter if necessary, anything else than theme hooks.

Just for the record: The last time you are able to set a message by drupal_set_message() is _preprocess_page


How to prevent accidental clicks in the Save button when saving a node? I need to prevent accidental clicks in the Save button when a node is being saved.

I found this module  which does exactly this. But the problem is that it uses javascript (jquery). Then if the user disable javascript this module is useless.

My problem is that in my website the user get points when creating nodes, so I have to prevent this in a more secure way.

How can I do this?

What do you think of these ideas?:

1) Maybe I would forbid the node being saved more than one time    programmatically instead of disabling the Save button.

2) Or better: I would allow the user to just save a new node every 5 minutes.

Finaly I got this  using these 2 modules:

http://drupal.org/project/hide_submit (to prevent clicking the bottom using jquery)

and

http://drupal.org/project/node_limit (just for browsers with javascript disabled) This allowed me to set a time interval limit to post new nodes.


Why default template suggestion use double dash instead of single dash? block--module--delta.tpl.php
page--front.tpl.php

As above example, what is the reason behind double dash? Why not use single dash like page-front.tpl.php?

I do believe it's just to add separation on the off-chance that the region/content type/page name has a dash in it, itself. block--my-impressive-module--delta.tpl.php is a lot easier to see that the intended target is block named my-impressive-module, than if it were block-my-impressive-module-delta.tpl.php (now there's no separation between the three name sections). It's possible for a region/content type/page name to have a dash, but none will have two dashes, so it's a reasonable substitution.


What are the available hooks for views I cannot find the list in the api documentation.

https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/group/views_hooks/8.5.x

Nor am I able to enter such functions in a theme when loading a page with a view.

They're here

In the codebase: core/modules/views/views.api.php.
On the web: https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/8.5.x

As always, only *_alter hooks and hook_theme can be implemented in a theme. Any other hook needs to be implemented in a module.


Sorting options in an entity reference Select list within a form When I change the input method for an entity reference field from an Autocomplete widget for a Select widget of an admin-side form, I have noticed there are no sorting options available under "Manage form display" and the Select widget is by default sorted by entity ID.

Is there a way to sort the entities in that Select widget by another field (in my case 'title')? I saw a note about this, but that pertains to drupal 7 (and my entity type is custom and not a node extension).

To enable this functionality in Drupal 8,

Add a view for your entity type.
Create an Entity Reference view display with a field and sort option (See comment from @saramm1 above).
Edit the Field Settings for the entity reference field and change the "Reference Type" to use a view.


Node clone module - how to use it? I am using Node clone.
The administration part of the module works 100%. I can edit the settings, but the clone tab that should appear beside the other node related tabs (edit, devel...) does not appear.

Has anyone out there used this module and could help me?

I have enabled Node clone on a Drupal 7 site. The cloning capability appears as an action link at the beginning of the node content on the View tab, not as a separate tab. The link text is "Clone content". The actual HTML is:

Clone content

I'm using a clean Zen subtheme. Perhaps your theme is preventing the action links from appearing?