Add image upload to theme configuration I'm trying to add an image upload to the theme settings in a theme I made. The image upload field does appear, however nothing actually gets uploaded and the image never get's saved.

in theme-settings.php I have the function

function mytheme_form_system_theme_settings_alter(&$form, $form_state, $form_id = NULL) {
    $form['banner']['banner_image'] = array(
        '#type' => 'file',
        '#title' => t('Banner Image'),
        '#description' => t('Upload a banner image'),
        '#default_value' => theme_get_setting('banner_image'),
    );
}

The image upload field does appear, but when choosing the file and clicking 'save configuration' nothing actually gets saved.

The problem with your code is that it needs a submission handler to handle the uploaded file. Using #file as form element type is fine, since that is also done from Drupal core in system_theme_settings().

$form['logo']['settings']['logo_path'] = array(
  '#type' => 'textfield',
  '#title' => t('Path to custom logo'),
  '#description' => t('The path to the file you would like to use as your logo file instead of the default logo.'),
  '#default_value' => theme_get_setting('logo_path', $key),
);
$form['logo']['settings']['logo_upload'] = array(
  '#type' => 'file',
  '#title' => t('Upload logo image'),
  '#maxlength' => 40,
  '#description' => t("If you don't have direct file access to the server, use this field to upload your logo.")
);

The form submission handler (system_theme_settings_submit()) then handles the uploaded file with the following code.

  // Exclude unnecessary elements before saving.
  form_state_values_clean($form_state);

  $values = $form_state['values'];

  // Extract the name of the theme from the submitted form values, then remove
  // it from the array so that it is not saved as part of the variable.
  $key = $values['var'];
  unset($values['var']);

  // If the user uploaded a new logo or favicon, save it to a permanent location
  // and use it in place of the default theme-provided file.
  if (!empty($values['logo_upload'])) {
    $file = $values['logo_upload'];
    unset($values['logo_upload']);
    $filename = file_unmanaged_copy($file->uri);
    $values['default_logo'] = 0;
    $values['logo_path'] = $filename;
    $values['toggle_logo'] = 1;
  }

You could use similar code in a form submission handler, but as described in When theme-settings.php has a managed_file field and a submit callback, " Call to undefined function" error is thrown. such form aubmission handler would not be found because Drupal doesn't load the theme-settings.php file automatically.
If you get around that, and you are able to make Drupal automatically load the file containing the submission handler, you could use the following code in your submission handler.

  if (!empty($form_state['values']['banner_image'])) {
    $file = $form_state['values']['banner_image'];
    unset($form_state['values']['banner_image']);
    $filename = file_unmanaged_copy($file->uri);
    $form_state['values']['banner_image_path'] = $filename;
  }

With theme_get_setting('banner_image_path') you will then get the path of the last uploaded file.
I would do as Drupal does, and add a textfield for the path of the last uploaded file.


How to deal with block cached for anonymous user? I have placed in the site's home, via twig, a views block of nodes with a random sort and obliviously no cache active.
Therefore, at each page reload different nodes appear.
The problem is that block get still cached for anonymous users.
For now, we can't yet do performance test of the site, so we'd rather not disable the Internal Page Cache module.
The Internal page documentation says:

Websites that serve personalized content to anonymous users (dynamic, per-session, e.g. a shopping cart) will want to disable the Internal Page Cache module. This module assumes pages are identical for all anonymous users. Those websites can still take advantage of the Dynamic Page Cache module though, or can alternatively do their personalization using JavaScript + AJAX.

So after failing to find anything else useful, I've tried this solution to solve the issue.
Unfortunately I found no module that let "load" the block via ajax, or something similar. For now I've implemented a custom route that render the block view:
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Render\Renderer;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\sdm_user\SdmUserSalesforceClient;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;

/**
 * Provides route responses for the Example module.
 */
class myController extends ControllerBase {

  /**
   * @var \Drupal\Core\Render\Renderer
   */
  private  $renderer;

  /**
   * @param \Drupal\Core\Render\Renderer $renderer
   */
  public function __construct(Renderer $renderer){
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('renderer')
    );
  }

  /**
   * @return array
   *   A simple renderable array.
   */
  public function render($id, $display) {
    $view = \Drupal\views\Views::getView($id);
    $render_array = $view->buildRenderable($display);
    $rendered = $this->renderer->renderRoot($render_array);
    $response = new Response();
    $response->setContent($rendered);

    return $response;

  }
}

And then in a custom js, load the necessary block via ajax:
(function ($, Drupal, drupalSettings) {
    Drupal.behaviors.products_in_home = {
        attach: function (context, settings) {
            $(document, context).once('products_in_home').each(function () {
                jQuery.ajax({
                    url: drupalSettings.path.currentLanguage + '/ajax/views/prodotti/products',
                    method: 'GET',
                    success: function (data) {
                        $(".products-container-home").html(data);
                    }
                });
            });
        }
    }
}(jQuery, Drupal, drupalSettings));

This works, but I'm kinda baffled: is this the only approach possible?
I mean, do I need to manually load via ajax every block\thing in the site that will suffer this problem?
Isn't there a module\API\some approach that can generally solve this problem, without custom specific code for every element?

In general the Internal Page Cache is a rather simple solution. If you need more features replace it with Varnish or a CDN. Most of them provide similar features, like for example ESI to serve dynamic blocks if you can't use Javascript. I think most people would use Javascript in this case, though, and there is a fully cacheable solution. You can deliver all eligible node IDs in drupalSettings and then select and fetch a random node in Javascript. Both, the page containing all eligible nodes and the node randomly fetched, are cacheable, so you can provide the dynamic behavior without any performance hit.


Prevent login except from Services I would like to prevent my users to login except for those who login through my REST Service.

Is that possible?

It sounds like the login_disable module will do exactly what you need.

Prevent users from logging in to your Drupal site unless they know the secret key to add to the end of the login form page. ( default: http://example.com/?q=user/login&admin )
If your site has clean urls enabled you may use http://example.com/user/login?admin instead.

That way you can set a secret key so only users who know that key are able to log in using the login form.
Another possible solution would be to disable the login form completely, like this:
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login') {
    $form['#access'] = FALSE;
  }
}


Correct way to append value to serialized array in key_value table I have a serialized array in the value field of key_value, to which I constantly what to append values. An easy way to do this is to get the array, append the new value, and reinsert it. However, with a large enough array it's quite inefficient and in theory it can be done on an SQL level.

What's the correct way to do this in Drupal 8? Is there a way that does not involve getting and then setting the array?

The best way to go about doing this is by using config API. If somehow this option is not suitable for your use case. You can also use the DB API to update the desired congratulation table records. In both cases, you will need to unserialize the blob then change the data and serialize it back before inserting it into the database.

https://www.drupal.org/docs/8/api/configuration-api/configuration-api-overview


node:menu tokens not working in Pathauto I can't get any node:menu-based tokens to work in my Pathauto replacement patterns.  Other tokens, such as [current-user:name] or [node:language], work fine.  But the token I am trying to use, a menu-based token, specifically [node:menu-link:parents:join:/] does not. I've tried a slew of the node:menu-link tokens, such as [node:menu-link:parent:url:path], and they're all being skipped.

When I bulk delete all Content aliases, then bulk update them, I do not get any error messages.  The resulting aliases from my pattern [node:menu-link:parents:join:/]/[node:title] just ends up being the node title.
git status

I've been banging my head against this for days, and in trying to fix it have:

installed Token Tweaks and set the depth to 2
run drush @test ev "token_clear_cache(); incessantly
disabled Menu Firstchild, then when that didn't help...
updated Menu Firstchild to the dev version and applied this patch
applied this Token patch
applied this core (!) patch

Now I'm running:

Pathauto 7.x-1.2+21-dev
Token 7.x-1.5+4-dev
Token Tweaks 7.x-1.x-dev
Menu Firstchild  7.x-1.1+1-dev

An additional detail:
Going to node/[nid]/devel/token for any given page hangs for a while, then displays a blank screen.  It produces three errors like this:

Notice: Undefined property: stdClass::$field_studio_location in addressfield_tokens() (line 219 of /var/www/html/test/sites/all/modules/contrib/addressfield/addressfield.tokens.inc).

This doesn't seem particularly serious, but maybe relevant.

Any ideas? Even pointers on how to debug would be great.

Just encountered that, after a full debug, it seems that menu_tokens() is not called at all.

  // There is a huge bug with menu tokens not being detected, to fix that, load
  // token include file and force repicking the menu_tokens() function as
  // implementation of hook_tokens()
  module_load_include('inc', 'token', 'token.tokens');
  module_implements('tokens', FALSE, TRUE);

That crappy hack fixed my problem but Why... just WHY ?

So yeah, after a deeper investigation, in module_implements():

  $include_file = isset($hook_info[$hook]['group']) && module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  // Since module_hook() may needlessly try to load the include file again,
  // function_exists() is used directly here.
  if (function_exists($module . '_' . $hook)) {
    $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  }

Okay, so the only thing that is preventing menu from being picked is the sorting:

if menu is processed before token in this module_implements(), the menu.tokens.inc include file will not be picked as it doesn't exist
if token is before menu, the token.tokens.inc thus menu_tokens() function will be discovered and picked up after

So if you don't want any code, just alter the weight of token and menu so that menu's is higher than token's.

But NO, there is a token_module_implements_alter() that just does that, but it is not called, and that is the thing I couldn't figure out. So the final hack was:

  // Rebuild implementation cache
  cache_set('module_implements', array(), 'cache_bootstrap');
  cache_clear_all('hook_info', 'cache_bootstrap');


Views selective filters show terms hierarchy I'm using Views Selective Filters, trying to expose taxonomy terms filters with its depth/hierarchy.

Whenever I configure a filter with criterion Content, for instance Country (field_country) where field_country is a term, I have this extra setting window to choose the widget :

Instead, with the same field, but selective filter option, that extra settings window doesn't appear.

The Exposed form style is provided by Better Exposed Filters, but I let the default style for that filter.

Is there a configuration step I'm missing ? A necessary module combination to achieve that ? Meanwhile, I updated to Views selective filters dev version, plus a patch providing taxonomy weight ordering for the filters. This is the relevant part, from views_handler_filter_selective.inc :

/**
 * Get list of options for current view, only at runtime.
 */
protected function get_oids() {
//...
// Sort values.
  $sort_option = $this->options['selective_display_sort'];
  switch($sort_option) {
    case 'WEIGHT':
      $terms = taxonomy_term_load_multiple(array_keys($oids));
      usort($terms, function($a, $b) {
        return $a->weight - $b->weight;
      });
      $oids_ordered_by_weight = array();
      foreach ($terms as $term) {
        $oids_ordered_by_weight["$term->tid"] = $oids[$term->tid];
      }
      $oids = $oids_ordered_by_weight;
      break;
  }

And I'm trying now to figure out how to overwrite that to show hierarchy instead.

I realised the BEF desired option "Nested checkboxes" was missing for all selective filters. Since into  better_exposed_filters_exposed_form_plugin.inc, the missing option depends on :

if ($bef_nested) {
  $display_options['bef_ul'] = t('Nested Checkboxes/Radio Buttons');
}

So I added the following :

/* line 314 */
if ($filter instanceof views_handler_filter_selective) {
  $bef_nested = TRUE;
}
/* line 493 */
if ($bef_nested) {
  //...
  $bef_options[$label]['more_options']['bef_select_all_none_nested'] = array(
    '#disabled' => !$filter instanceof views_handler_filter_selective &&(!$filter->options['expose']['multiple'] || !$filter->options['hierarchy']),

I know this is a very quick hack and should be improved for general use. Alternate proposals are warmly welcome.

Last, I had to patch also Views selective filters handler, resulting in :

case 'HCHY':
  $options = array();
  //get remaining terms tids
  $remaining_terms = taxonomy_term_load_multiple(array_keys($oids));
  $tids = array();
  foreach ($remaining_terms as $term) {
    $tids[$term->tid] = $term->tid;
  }
  //get vocabulary tree
  $anyterm = array_shift($remaining_terms);
  $tree = taxonomy_get_tree($anyterm->vid);
  if ($tree) {
    //we flag the terms to avoid displaying them more than once
    $flagged = array();
    //we keep tree items if they match with current selection
    foreach ($tree as $trm) {
      if(in_array($trm->tid, $tids ) && !in_array($trm->tid, $flagged) ){
        //so we always keep its parents displayed
        $parents_all = taxonomy_get_parents_all($trm->tid);

        if($anyterm->vid == '3'){//country vocab, Three levels taxonomy
          switch (count($parents_all)) {
            case 3:
              $parent = $parents_all[1];
              $gd_parent = $parents_all[2];
              break;
            case 2:
              $gd_parent = $parents_all[1];
              break;
            default:
              break;
          }
          //Add the gd_parent to options
          if(!in_array($gd_parent->tid, $flagged) && !is_null($gd_parent->tid)){

            $gd_parent_depth = get_term_depth($gd_parent->tid)-1;
            $choice = new stdClass();
            $choice->option = array($gd_parent->tid => str_repeat('-', $gd_parent_depth) . $gd_parent->name);
            $options[] = $choice;
            $flagged[] = $gd_parent->tid;
          }
          //Add the parent to options
          if(!in_array($parent->tid, $flagged) && !is_null($parent->tid)){

            $parent_depth = get_term_depth($parent->tid)-1;
            $choice2 = new stdClass();
            $choice2->option = array($parent->tid => str_repeat('-', $parent_depth) . $parent->name);
            $options[] = $choice2;
            $flagged[] = $parent->tid;
          }
        }

        //last, add the term itself to options
        $choice3 = new stdClass();
        $choice3->option = array($trm->tid => str_repeat('-', $trm->depth) . $trm->name);
        $options[] = $choice3;
        $flagged[] = $trm->tid;
      }
    }
  }
  $oids = $options;

/*
 * Returns a term depth (https://www.drupal.org/node/886526#comment-7708315)
 */
function get_term_depth($tid) {
  $limit = 5;
  $depth = 0;
  while ($parent = db_select('taxonomy_term_hierarchy', 't') ->condition('tid', $tid, '=') ->fields('t') ->execute() ->fetchAssoc()) {
    $depth ++;
    $tid = $parent['parent'];
    if ($depth > $limit) {
      break;
    }
  }
  return $depth;
}

Both are necessary, usual nested checkboxes from BEF do not work as is. This might be useful for some of you.


7: How to cache $form[] elements in complex AJAX forms How is it best to efficently rebuild your form on multiple AJAX requests?

That is how can I cleanly cache individual elements so I don't need to rebuild them?

Using static variables is not an option as they will not persist across form rebuilds. Using $_SESSION is probably the best, but this needs care as potentially a single session my have to windows open with diffent copies of the form in each one - and $_SESSION seems generally unclean.

Anyone got any best practices or boiler plates?

Background:
In order to AJAX in "proper" drupal style you need to rebuild the entire form on each AJAX call back. Your AJAx call back then just returns individual elements to replace. This is efficent for http bandwidth, but if the form elements are expensive to build this is potential an unneccessary performance hit.

The answer probably involves using $form_state somehow...

You need to rebuild whole form, no way around it, but you can store expensive things in Drupal cache. I advise against storing parts of $form array if it can be avoided, but using cache_set() and cache_get() to keep things like options available for select B when there is X in select A, it should work like a charm. And it will work with APC and Memcache modules out of the box.

The key is, of course, careful selection of $cid building algorithm.

$form_state as cache

$form_state is kept in form cache bin, but it is not a "real" cache. Let's look at the definition from Wikipedia:

  In computer science, a cache (/ˈkæʃ/ KASH)1 is a component that transparently stores data so that future requests for that data can be served faster.

Now, that's pretty much what $form_state is not - it is kept to save temporary data that needs to be consistent, and that are never stored anywhere else during form processing. It means that when someone is using APC or Memcache, he needs to take extra care to prevent their "it can be deleted without any reason, for performance purposes" approach from corrupting forms. Most Drupal admins I know simply exclude form cache bin from them. And that is not what you want for your pre-built form parts.

Your pre-built form parts are real cache. So you want to keep them in bins that will be treated accordingly, you want to have speed over stability - you can afford additional rebuild once and then more than you can afford slowing down each request by pulling this data from database - slowest cache possible for Drupal.

Second reason not to use it is scope. $form_state exists only per one form session. So if user ends filling the form and access it again, $form_state is build anew. If hundred of users access he same form at one time, you have a hundred instances of $form_state. That's not what you want when your form elements does not depend on the user of your system. By keeping them in separate cache bin, keyed only by the things they depends on, you can have one copy, and use it for all hundred of users, every time they need it. It is impossible to loose anything, and you can decrease load (both CPU for generation and space for storage) to minuscule fraction of what it would be, if you would keep it in $form_state.

Algorithm for using cache (if someone happens to forget, of for newbies reading in future):

Check if data is in cache
If not, build it and save to the cache
Use either data obtained from cache in 1., or built in 2.


Decode entities in node titles I have a few node titles that are being saved with & and displaying that way too.

Is there any way to not encode them while being saved? I tried:

$node = node_load(727);
$node->title = html_entity_decode($node->title);
node_save($node);

I dump out the node and the title is corrected, but is not saved that way. Should I only try to correct the display using the same function?

Filter input, escape output. You can't be sure that everything in your database is safe.


Access custom user field from a different account The following works so far:

I can set a custom user field e.g. 'full_name' in Drupal Account Settings
The logged in user has access to this field using the following code.

global $user;
$user = user_load($user->uid); // Fully load the user object
$custom_vars['full_name'] = $user->field_full_name[LANGUAGE_NONE][0]['value'];
echo "My full name is :  $custom_vars['full_name']";

This is what I want to do:

I want to log in as an admin account and for a specific group of
users who's unique IDs know I want to display this field.
So perhaps for userID = (1234, 1175, 14532) I want to see this value
for 'full_name', how do I do it?

I am hoping for a PHP solution that uses code similar to the above rather than a SQL DB call, but if I need to directly access the DB so be it.

This seems a bit dirty, but using your exact code as a base, something like the following may work:

$uids = array(
  // Here is the list of user ID's that you know.
);

$full_names = array();

foreach ($uids AS $uid){
  $account = user_load($uid);
  $full_names[$uid] = $account->field_full_name[LANGUAGE_NONE][0]['value'];
}

unset($account);

return $full_names;

This will give you an array of full usernames keyed by the UID.

Also to bear in mind, this performs no access checking or permission checking.

For further reading, you might want to try taking a look at something like field_get_items() as well.


Define constants in hook_init I am writing a custom module for stripe payments and I need to declare constants for CLIENT_ID and CLIENTSECRETKEY.

is it good to declare them in hook_init because then they will available every where ?

module contains other functions like make_payment and add customer etc.

hook_init() is not invoked for cached pages, so you could be opening yourself up to a world of pain if you do that.

Constants outside of a class that need to be accessed by several functions are global by nature, so just put them in the global namespace. It's the best way to ensure they're consistently available when you expect them to be.


$file->original: Where does it come from? I am attempting to write a patch for the Redirect module that automatically creates a redirect from the old file path to the new one, whenever a file is updated.

I added a hook to redirect.module:

function redirect_file_update($file){
      /**
     * Creates a new redirect from old file to new one when the new one has a different URI.
     */

  if (empty($file->original)) {
    $file->original = entity_load_unchanged('file', $file->fid);
  }
  if ($file->uri !== $file->original->uri) {
    $redirect = new stdClass();
    redirect_object_prepare(
        $redirect,
        array(
        'source' => file_create_url($file->original->uri),
        'source_options' => array(),
        'redirect' => file_create_url($file->uri),
        'redirect_options' => array(),
        )
    );
    module_invoke(
      'redirect',
      'object_prepare',
      $redirect,
      array(
        'source' => file_create_url($file->original->uri),
        'source_options' => array(),
        'redirect' => file_create_url($file->uri),
        'redirect_options' => array(),
      )
    );
    module_invoke('redirect', 'save', $redirect);
  }
}

and I verified with a dpm() that $file->original exists as expected when I'm working with files in the GUI.

But when I run tests it doesn't work. According to hook_file_update() docs, it should be called whenever file_save() is called, but it appears that the code inside my redirect_file_update() is never being called, entity_load_unchanged() is returning the exact same object as plain old $file, and my $file objects don't have an 'original' property as far as the test knows, even after saving. Here's the testing code:

function setUp(array $modules = array()) {
  parent::setUp($modules);

  $this->admin_user = $this->drupalCreateUser(array('administer redirects', 'access site reports', 'access content', 'create article content', 'edit any article content', 'create url aliases'));
  $this->drupalLogin($this->admin_user);
}
  // Test whether replacement of a file redirects the old file URI to the new one.
  function testFileReplacementRedirects () {
  // Create a few test files and save them.
  $files = $this->drupalGetTestFiles('image');
  foreach ($files as $file) {
    file_save($file);
  }
  // Get a list of all the files we just created.
  $fileQuery = new EntityFieldQuery();
  $files_list = $fileQuery->entityCondition('entity_type', 'file')
    ->propertyOrderBy('fid')
    ->execute();
  // Pick out two files to use for our test.
  $test_file_one = file_load($files_list['file'][1]->fid);
  $test_file_two = file_load($files_list['file'][2]->fid);

  // Move file one to file two's URI
  $old_url = file_create_url($test_file_one->uri);
  $new_url = file_create_url($test_file_two->uri);
  $test_file_one = file_move($test_file_one, $dest = $test_file_two->uri, $replace = FILE_EXISTS_REPLACE);
  // Load the old module's URI and see if it redirects to the new one.
  $this->drupalGet($old_url);
  $this_page = $this->drupalGetHeaders(TRUE);
  $this->assertEqual($this_page[0]['location'], $new_url, 'Redirected from ' . $old_url . ' to ' . $new_url . '.');
  $this->assertEqual($this_page[0][':status'], 'HTTP/1.1 301 Moved Permanently', 'Status: ' . $this_page[0][':status']);
}

What is going wrong?

$file->original is set from file_save() to make it available to hook_file_presave(), hook_entity_presave(), hook_file_insert(), hook_entity_insert(), hook_file_update(), and hook_entity_update(). It is then removed from file_save() before the function returns the file object to the caller.

// Load the stored entity, if any.
if (!empty($file->fid) && !isset($file->original)) {
  $file->original = entity_load_unchanged('file', $file->fid);
}

Clearly, if the file was not previously saved, $file->original doesn't get set.


How can I index all remaining items programatically? I'm just using the stock Drupal 7 search. Is there a function to index all the unindexed content from my module? And re-indexing? I haven't found this yet if it exists.

One way to do it is exec("drush search-index");.


Bilingual site - when adding translations to Organic Group, prevent creating a separate group/content node We have a bilingual site. We use organic groups to separate suborganisations and their members.

The Organic Group content's multilingual option is set to "Enabled, with translation"

We just want the "Landing" page of the Organic Group to be translated.

When the Organic Group is translated, it creates a discrete Group that allows users to join.

Essentially, we'd like everyone to be in the same group, but still be able to see content in their preferred language.

Anyone have a workaround for this?

Basically the answer is to use Entity Translation. See here https://www.drupal.org/node/371181


Drupal 8 Webform - Change to Dev Version I need to send emails in Drupal 8 Webform conditionally based on what the user has selected. I know this feature was added in the most recent release in  8.x-5.x-dev, but I have the beta branch installed (8.x-5.0-beta16). Is there an easy way for me to change to this version of the module, or am I out of luck?

Thanks,
Lisa

if you have drush on your server you can easily select a version with this command

drush dl webform --select

it should show something like this

Choose one of the available releases for webform:
 [0]  :  Cancel
 [1]  :  8.x-5.x-dev     -  2017-Sep-07  -  Development
 [2]  :  8.x-5.0-beta16  -  2017-Aug-08  -  Supported, Recommended
 [3]  :  8.x-4.x-dev     -  2016-Nov-28  -  Development

and you could press 1 then enter to select 5.x-dev

i believe you'd also be prompted with a message warning you that you're overwriting the previously installed beta16 version and you'll say ok


Load and Save nodes with script? I have about 30,000 nodes I need to load and resave so things like autotags and url aliases get generated.  Is there a quick script I can write to do this?

I recommend to resaving for smaller count of nodes, and run next script few times. Of course using batch will better UI, add itself:

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$from_nid = variable_get('tmp_from_nid', 0);

$sql = "SELECT n.nid
        FROM {node} n
        WHERE n.nid > :nid
        ORDER BY n.nid";
$result = db_query_range($sql, $from, 1000, $from_nid);

foreach($result as $row) {
  set_time_limit(30);

  $node = node_load($row->nid);
  node_save($node);
  $from_nid = $row->nid;
}

variable_set('tmp_from_nid', $from_nid);
drupal_set_message(t('Last processed nid - !nid', array('!nid' => $from_nid)));
?>

Also VBO for mass resaving nodes.


How to count clicks made on an image I created a click-able image block and posted it on the left sidebar. A click made on the image leads to an external website. How do I count the number of clicks made on that image. The Google analytics don't seem to give immediate results. Is there any module for this. Any help is much appreciated.

Look on how Advertisement module is doing it.

Simplified outline is:

Each image is linked to a page named like /count/someuniqueid
Module implements that page to increase counter and then sends 302 Found HTTP header to user's browser.
Browser is redirected to a desired page and user don't really see what happened at all.

Actual workflow is, due to performance issues, way more complicated and involves php files that does not bootstrap Drupal, caching and all that.


Auto-update of features? On a production site, I don't want admins to be able to perform many tasks at all, to limit the risks the site is exposed to, so modules like "Views UI" will be turned off.

However, I still want a number of administrators to have access to Views and similar functionality, so they can perform changes without a developers help.

Thus I would like to see the ability to have some features "auto-export" themselves, a script that commits them to the VCS, and then deploys to a stage-server where they can be tested and approved.

Is there any public work at all on this type of functionality, or would I need to start from scratch? Is the idea entirely in-sane, and if so, what other options should I pursue?

My own suggestion is a cron job that runs

@drush fu [feature 1] [feature 2]
git commit -m "Auto exported features" features-dir/
git push

and while that could certainly work, I'm also fairly certain all kinds of problems will be discovered along the way, meaning this script will need to evolve substantially over time.

Leaving question open at least until someone with actual experience (maybe myself) leaves an answer.


How to create a page view of two content type in Drupal 7 I have two content type named as workshop and meetings. I wanted to create a new page view (say events) of these content type such that event page should have titles of post from each content grouped with content type.

I tried to create this view but I can't select multiple content type while creating a view.

Here's how you do it: Once you've created your view, selecting either one of your content types:

Under "filter criteria", click the filter called "content type (= YOUR_CONTENT_TYPE).
Select "is one of", and then select all the content types you want to include.
Click Apply (all displays).
Save the view.


Classes with the same name and description, but different location When I am looking for an information about any class in api documentation, I often encounter the situation when there are several classes with the same name and the same description, but different location.

For example, there are two classes with name YamlDiscovery and the same description.

How should one select a needed class for oneself? Can use any class? If so, what for they were added both into Drupal 8?

That's a bad example, it is then used as another name to avoid a name conflict use Drupal\Component\Discovery\YamlDiscovery as ComponentYamlDiscovery;.

Usually you can see the purpose of the class when you look at the namespace or the corresponding file location. It's OK to use the same class name in different namespaces. As you can see in this issue there can be different opinions how descriptive class names should be and how much you should rely on the namespace of the class to make the purpose clear:

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


How to import an addressfield with Feeds? Using Drupal 7.10 with Feeds 7.x-2.0-alpha4.  I'm trying to create a feeds importer to import node data stored in a csv file.  On the screen where you setup the mappings, my addressfield (that is part of my content type) doesn't appear in the drop down list of targets (whereas other fields of my content type do).

How can I get this to work?

I see some issues for this but being a Drupal newbie I can't really understand how to get this to work:

Mapping Address Fields using Feeds and Feeds JSONPath Parser

Mapper for Feeds importers

Do I need to switch to using the Dev release of feeds?

Following the links you posted, it looks like it's all wrapped up. Yes, try the current dev releases for Feeds.


Cron run exceeded the time limit and was aborted + How to change max_exec_time if not access on php.ini I am running a script which Fetches the data from other site like Articles of a user and other things also. I run my script in hook_cron. Cron gives me this error after a while of script running.

Cron run exceeded the time limit and was aborted.

Also I don't have access to change php.ini and setting.php. How can I change max_exec_time value.

Seeing as you don't have access to anything that allows you to change the max execution time (and I would imagine if you find a workaround that it won't work if your server is this locked down) I see a couple of options.

1:  Utilise the Batch API as I mentioned in my comment (Batch API docs are here)

2: Check out Elysia Cron to split your cron tasks up into smaller, more manageable chunks.

  Elysia Cron extends Drupal standard cron, allowing a fine grain
  control over each task and several ways to add custom cron jobs to
  your site.


Drupal 7 and Open ID How does this Open ID module work in Drupal 7? I would expect something more or less the way StackOverflow and all these StackExchange websites work: you pick up your logging provider, like Google or Facebook, by clicking one of them. If you aren't currently logged in in their service, you are redirected to their logging interface, fulfill username and password and you are redirected back to the parent website and already recognized. It looks like the OpenID module does not work this way. You have to paste an Open ID URL or something... Is there a module that does the process exactlys as in the Stack Exchange websites, or more or less the same? Because I think the process implemented in this website is absolutely fantastic: quick and comprehensive, Dummies proof. Or I am afraid I am behaving like the Dummy myself if the Drupal Open ID module works this way. I have been experimenting with it in my localhost and it requires me to paste an OpenId URL. Thanks for any help clearing this...

Yes, OpenID always works with an URL, which is your identifier.

I think what you are looking for is the Janrain Engage module: http://drupal.org/project/rpx. This provides a similar workflow and UI like the one you know from StackOverflow.


Unlimited field collection pagination in node edit page In my node I have a field collection which is set to unlimited.
How to enable pagination for node edit page, where all items from that field collection are displayed?
For display there are couple possibilities - pagination modules, views etc. but how to do it for node edit page?

A great solution to your problem would be to use the EmbeddedViewField module. It fixes your problem, as mentioned in the module's project page:

  EmbeddedViewField is a module that will allow you to render a view as
  any other field.

  It is based on keithm's ViewField module, except that it will always
  render the view, regardless of whether the user is editing or
  displaying the entity that has the EmbeddedViewField. The view used
  for displaying is controlled by the default value set for the view.


How to alter the owner/authored by field to the current user when using quick_node_clone Using Drupal 8 with quick_node_clone module.

When a node is cloned I need to change the 'owner' or 'authored by' value to the person who is cloning the node.

There is an opportunity of manually changing this but I need to automate this.
I am have been trying the hook_form_alter with some alternatives, see the commented out section, without success.

function quick_node_clone_form_alter(&$form, FormStateInterface $form_state, $form_id) {

 print_r($form_id);

 if ($form_id == 'quick_node_clone') {
  // change author
  //$form['author']['name']['#value'] = $user->uid;
  //$form->setOwnerId($current_user);
  //$form->uid = $user->uid;

  print_r($form['field_author']['nid']['nid']['#value']);
  global $user;
  $form['field_author']['nid']['nid']['#value'] == $user->uid;
 }
}

Any direction would be appreciated.

Try this out:

use Drupal\Core\Entity\EntityInterface;
/**
 * Implements hook_entity_presave().
 */
function customModule_entity_presave(EntityInterface $entity) {
  $current_user_id = \Drupal::currentUser()->id();
  $entity->setOwnerId($current_user_id);
}

Edit
You would be better to check on your content type:

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_presave().
 */
function customModule_entity_presave(EntityInterface $entity) {
  $current_user_id = \Drupal::currentUser()->id();
  if ($entity->bundle() == 'your_content_type_name'){
    $entity->setOwnerId($current_user_id);
  }
}


Best practice: Twig logic versus Preprocess functions I use Twig and Twig Tweak to do most of the processing. However, from time to time I need to rely on Preprocess functions to get the desired result.
This led me to a situation where now most of my variables are created in a Preprocess function before handing them over to Twig (this keeps my templates clean, simple and most of all easy to read). I also don't like my code being scattered between Templates and Theme functions.
But regarding Drupal Documentation, this method seems discouraged.

function mytheme_preprocess_node(&$variable) {
 if ($variable['node']->getType() === 'my_content_type_machine_name') {
 $variable['my_title'] = $variable['node']->field_my_title->value;
 }
}

You may now use the more concise {{ my_title }} in your twig file to
refer to {{ node->field_my_title->value }}.
However, while this might be possible, it is discouraged to create
new variables in this manner. Using {{ node.field_my_title.value }}
is fairly reasonable to type and avoids any potential issues and
should be preferred.

So basically my question is: Are there any simple rules to follow regarding Twig versus Preprocess functions for additional logic?

Best practice is documented in the node template. These are the two most important variables:
* Available variables:
 * - node: The node entity with limited access to object properties and methods.
 *   Only method names starting with "get", "has", or "is" and a few common
 *   methods such as "id", "label", and "bundle" are available. For example:
 *   - node.getCreatedTime() will return the node creation timestamp.
 *   - node.hasField('field_example') returns TRUE if the node bundle includes
 *     field_example. (This does not indicate the presence of a value in this
 *     field.)
 *   - node.isPublished() will return whether the node is published or not.
 *   Calling other methods, such as node.delete(), will result in an exception.
 *   See \Drupal\node\Entity\Node for a full list of public properties and
 *   methods for the node object.
 * - label: (optional) The title of the node.
 * - content: All node items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.

It clearly states that you should print the render array {{ content }} and use the object {{ node }} with its properties and methods to get the node data you need.


Multisite Installation (Attempt) Goes To My Main Site I am attempting to perform a multisite installation. My main (presently working) site is located in a subdirectory called "beta" of my ~/public_html folder. This is the site for jackstahlco.com and it is working. I also want to have this installation of Drupal run two other sites.

The first other site I am trying to get to work is meadowlarknm.com. This site is presently resolving to jackstahlco.com, which is NOT correct. I created ~/public_html/beta/sites/meadowlarknm.com/ and ~/public_html/beta/sites/meadowlarknm.com/files. I copied default.settings.php into meadowlardnm.com/ and changed the permissions, as well as creating a 'files' directory. The settings.php also contains

$databases = array ();

and no other database configuration.

When I navigate to www.meadowlarknm.com, I just see the www.jackstahlco.com website, instead of the Drupal installation screen that I expect. You can go there to see what I'm talking about, unless I fix this problem immediately after writing this question.

I am suspecting that this may be a .htaccess issue, but I am not sure. It's a little bit weird that I am trying to run multi-site from a subdirectory, but it seems like this should be possible (if my understanding was complete.)

Here is my .htaccess (inside ~/public_html, I did NOT change the .htaccess inside ~/public_html/beta):

########## End - Rewrite rules to block out some common exploits

#  Uncomment following line if your webserver's URL
#  is not directly related to physical file paths.
#  Update Your Joomla! Directory (just / for root)

# RewriteBase /

RewriteCond %{HTTP_HOST} !^www\.jackstahlco\.com$ [NC]
RewriteRule .* http://www.jackstahlco.com/      [L,R=301]
RewriteRule ^$ beta/index.php   [L]
RewriteCond %{DOCUMENT_ROOT}/beta%{REQUEST_URI} -f
RewriteRule .* beta/$0 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* beta/index.php?q=$0 [QSA]
#
#RewriteCond %{HTTP_HOST} ^(www.)?jackstahlco.com$ [NC]
#RewriteRule ^(/)?$ /beta/$1 [L]

RewriteCond %{HTTP_HOST} ^(www.)?jackstahlcompany.com/puertadelsolsite$
RewriteRule ^(/)?$ puertadelsolsite [L]

RewriteCond %{HTTP_HOST} ^meadowlarknm\.com$ [NC]
RewriteRule ^(.*)$ http://www.meadowlarknm.com/$1 [L,R=301]

########## Begin - Joomla! core SEF Section
#
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteCond %{REQUEST_URI} !^/index.php
#RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
#RewriteRule (.*) index.php
#RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
########## End - Joomla! core SEF Section
<IfModule mod_suphp.c>
 suPHP_ConfigPath /home/jsco
 <Files php.ini>
   order allow,deny
   deny from all
 </Files>
</IfModule>

Additionally, the following is in /home/jsco/public_html/beta/sites/sites.php:

  $sites = array(
   'www.jackstahlco.com' => 'default',
   'www.meadowlarknm.com' => 'meadowlarknm.com',
  );

The end goal here is to re-do the existing sites on this server (some Joomla! as you may have guessed from the .htaccess) to a single Drupal system running multisite.

I don't believe this is a DNS issue. nslookup says these are all going to the correct place, and my domain-to-folder mapping on cPanel (sending everything to ~/public_html) looks OK.

Additionally, the multisite wizard says MOST of my steps are OK.

OK Create sites/sites.php file
OK Fill up sites/sites.php file with domain-folder array
OK Create sites folders inside sites/ folder
OK Each site folder should have own settings.php file
NOT OK - Prefix inside each settings.php file should be unique. I think I want a different DB

Thank you very much for the help.

-Brian J. Stinar-

Indeed this is not a DNS issue, the problem here is your sites directory is located in the wrong directory. It shouldn't be under all but in the root of sites. In your case it should be:

sites/jackstahlco.com/settings.php
sites/jackstahlco.com/files
sites/meadowlarknm.com/settings.php
sites/meadowlarknm.com/files

If you want the Drupal installation process popping up, you need to put an empty array connection info in the settings.php of the desired website.

$databases = array ();

The sites.php should be like this:

$sites = array(
    'jackstahlco.com' => 'default',
    'meadowlarknm.com' => 'meadowlarknm.com',
);

You don't need to specify the www prefix.


Solution how to import contents of a .txt file into a body field? Are any solution how we can import content of text (.txt) file with feeds into body field?

We don't have any problem with standard feeds import with CSV file and files into field file. We just need solution how we can import content of separate text file into body field.

Thanks

I believe you can accomplish this with Feeds Tamper and a custom plugin.

Take one of the existing text plugins and clone it to a new one.  Then inside the plugin callback, take the cell value (your text file name), build up a proper path, do a file_get_contents(), and stuff the contents into the result.

If you end up going this route, it may be a decent patch to Feeds Tamper for inclusion in the project itself.


How do I fix File Upload After Upgrading to PHP 7 I know this question has been asked a thousand times in a thousand different ways, but none of those solutions have worked for me.
Problem: I recently updated from php5 to php7. Whenever I attempt to upload an image (have not tried any other file types) I get the attached
My Setup:

Drupal 8.6.1
PHP 7.2
Windows 2012 Server
IIS 8

Things I've Tried:

I have ensured that IIS users permissions have been set to read/write/modify for the tmp directory.
I have explicitly declared the tmp_upload_directory value in php.ini

upload_tmp_dir = C:\inetpub\wwwroot\tmp

The reason I believe it is PHP (could definitely be very wrong) is because of the first failed item in the error. "The file php3BF5.tmp....."

upload_tmp_dir existed in two places. I was only updating in one location. Answer came from https://stackoverflow.com/questions/15733183/unable-to-set-upload-tmp-dir-on-iis


Printing to a strict template (multipage invoices / multiple delivery labels per sheet etc) I would like to be able to print out hard copies of some strict templates.

Primarily I would like to eliminate the web browsers header and footer garbage that plagues printing from the web. I am prepared to be locked into a specific web browser for the purposes of printing such documents, as I understand this is a source of variability.

Specific examples of documents to be printed are:

Full page / multipage invoices that would require line breaks in specific places (and the ability to provide a custom page header for each individual page)
Printing to label paper (6/8 labels per A4), which would require fairly decent precision in order to print to the correct regions of the paper, as well as being able to specify page breaks for printing a multitude of labels across a many pages.

Is there a Drupal specific method for achieving this, preferably directly from browser to printer, although alternatively via PDF or some other means?

I understand that I might need to settle for something less-than-perfect, but anything available that is either Drupal specific would be greatly appreciated. For non-Drupal solutions, I have posted a similar question here at StackOverflow.

You can look into Fill PDF as an option. For this, you'd have to pre-create the templates with fillable form fields and would probably need a bit of programmatic glue to deal with page breaks, number of pages, etc. Fill PDf basically lets you use tokens from nodes and webforms to populate fillable PDF fields.

It would probably make achieving your template easiser.


Pagination for entities I have an entity called announcement, and I have a page (user/%/announcement) where I display a table of three columns (name of entity,an edit entity link and an delete entity link).

function announcements_user($account) {
  $uid = $account->uid;
  $return = '';
  $total = 0;
  $i=0;
  $pid = array();
  $text = array();

  $query = db_select('announcements','a')->extend('PagerDefault');
  $query->fields('a',array('pid','value'));
  $query->condition('uid', $uid);
  $result = $query->execute();

  foreach($result as $row) {
    $pid[] = $row->pid;
    $text[] = $row->value;
    $total++;
  }

  $return .= '

     Announcement
     Edit
     Delete

';

  while ($total) {
    $return .= '
';
    $return .= ''.substr($text[$i],0,10).'......	';
    $return .= 'Edit	';
    $return .= 'Delete	';
    $return .= '
';
    $i++;
    $total--;
  }

  $return .='
';
  $return .='
';
  $return .='Add Announcement';

  return $return;
}

Now my problem is that keeping this format of tabular structure, how do I display my result in a paginated format with 5 announcements per page? I have seen pager.inc for Drupal 7 and howto-print-out-the-pagination-for-entityfieldqueries link, but I just can't figure out how to apply them to my case.

function announcements_user($account) {
  $header = array(
    'announcement' => array(t('Announcement')),
    'operations' => array('data' => t('Operations'), 'colspan' => '2'),
  );
  $rows = array();

  $result = db_select('announcements','a')
    ->fields('a', array('pid','value'))
    ->condition('uid', $account->uid)
    ->extend('PagerDefault')
    ->limit(5)
    ->execute();

  foreach ($result as $data) {
    $row = array();
    $row[] = l(truncate_utf8($data->value, 10, FALSE, TRUE), 'announcement/' . $data->pid);
    $row[] = l(t('Edit'), 'announcement/edit/' . $data->pid);
    $row[] = l(t('Delete'), 'announcement/delete/' . $data->pid);

    $rows[] = $row;
  }

  $form['announcements'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No announcement available.'),
  );

  $form['pager'] = array('#markup' => theme('pager'));
  return $form;
}

Query methods generally return the object for which they are invoked; this means that method calls can be concatenated as I did in  the code.
PagerDefault::limit() has a default limit of 10; if you don't call that method, the limit is the default value.
Strings that appear in the user interface should always be translated; the only strings that cannot be translated (which means, you cannot pass them to t()) are dynamic strings obtained from a function/method.
Drupal URLs should always be obtained from url() or l(). l() returns the HTML tag for links (<a>), while url() returns the relative or absolute URL for the Drupal path passed as argument.

For an example of function that does something similar, see blog_page_last(), which returns the last blog posted by a user.


How to show popup for save or view the file? I am displaying file names as links on the page, when I click on particular link, it should ask the user that, save file or view file something like below image.

In my case this popup is not coming, directly the file content is displaying on browser. So how can I achieve this. Thanks for your any suggestions.

My code to display dynamic links as follow:

$uri = 'public://';
  $path= file_create_url($uri);

$data .= '
' ."--". $filenames .'

';

The browser you are using recognise the linked document format and try to show it directly. It is mainly true with images and PDF files.

If you want to force the browser to download the file (or to open it with a local application), as explain in this answer, you can use the HTML5 download attribute.

$uri = 'public://';
$path= file_create_url($uri);

$data .= '
' ."--". $filenames .'

';


Workbench moderation allowing a role to unpublish content? I'm using Workbench Moderation on a new D7 site build.
All is great in terms of workflow and I think I have the permissions near perfect, but I can't for the life of me seem to grant my 'content approver' roles the ability to unpublish content.

If I log in as a administrator (Drupal default role) I can see the option to 'unpublish' appearing, but I can't spot a particular Workbench / Drupal permission to grant to allow this permission for lower roles.

Anyone have a suggestion?

You need to make transitions for the backward states through moderation (eg, Published -> Needs Review, and Published -> Draft) on admin/config/workbench/moderation/transitions

Then, on  on admin/people/permissions#module-workbench_moderation, assign the permissions appropriately to the roles you want to allow to push things backwards


How to show one variation of one product in a View Pane I have a View Pane on my home page where I list all products that are in promotion. Each product variation that can be set to "show in promo banner 1" via a taxonomy term field with checkboxes. So the store owner can now tick this checkbox to indicate that this product variation is in promotion. This works but only for product displays that have only 1 variation. When, for example, I only tick this checkbox for "product variation 4" of a particular product and no other variations, the first variation shows with a variation select widget and that's not what I want. So how can I only show that particular variation without the widget but with all the correct data and an add to cart button?

If what you're seeing is the fully rendered Add to Cart form in your View, then what you're looking to do is impossible without custom code. The Add to Cart form is rendered via the field display formatter on your product display node type. It has no way to interact with the configuration or results of a Views query.

You can create a View just showing variations with an Add to Cart button that doesn't invoke the entire form, but doing so will strip the creating line item of the context of what product display that variation is a part of. This means the line item won't link to the product page like it ordinarily would. You could always link it yourself if you know that each variation only exists on one node via a reverse reference, but you'd likely still lose some functionality related to the standard form's normal grouping of variations.

If that's an acceptable trade-off, then you need to recreate your View using Commerce Product entities as the base as opposed to Nodes. Otherwise you're going to have to create some custom Views plugins.


Nodes with comments in View I want to create a view that returns all nodes of type X. Beneath each node I want to return the comments for that node as well.

Node 1

Comment 1
Comment 2
Comment 3

Node 2

Comment 1

Node 3

Comment 1
Comment 2

Something like above. Is that possible?

Create a new View, Give it a Name

Select "comments" for the show option
Display Formats should be Unformatted of Fields -- Not Comments
Hit Continue & Edit
In d7 the content relationship is going to be added for you automatically (just be aware)
Add a new field (Content: Title) -- You might want to exclude it from display
Under the Format settings there's going to be a Grouping field option, select Content: Title.
Save Your View.

That should do it. Sorry is so plain, the views UI is not the easiest to explain, if I tried this post will be insanely long. I try capturing the key details.

Hope this helps.


Render view in code with the proper view mode I have a view that calls for Show: Content, using a very specific view mode (neither Full content nor Teaser, it's created on purpose and themed according to my needs, basically an e-mail oriented output with very different HTML classes than the usual views displays in Drupal). When used in a page, it renders perfectly. However, when I render it from code to be able to use the resulting HTML directly:

$view = Views::getView('view_id');
$view->setDisplay('default');
$view->setArguments($args);
$view->preExecute();
$view->execute();
$render = $view->render();
$html = render($render);

I get an otherwise perfect render but not with that view mode, just the usual stuff. Alternative calls do the same:

$render = $view->buildRenderable('default', $args);
$html = render($render);

How could I force it to render the way I want it?

It was the theme. The rendering took place under cron and ran under the administration theme rather than the usual one, meaning different twigs. The solution will be to sub-theme the admin theme to make sure all the relevant twigs are present there, too.


How to dynamically set the maximum cardinality for a multi value field? I am using a multi value image field which is set to hold 5 values. What I need, is to be able to set a lower cardinality for this field on specific nodes of the same content type.

Edit: Below is what I ended up using, it might help someone.

/**
 * Implements hook_field_attach_form().
 */
function example_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  // Our field name
  $field_name = 'field_listing_images';

  // You may want to add more conditions
  if (isset($form[$field_name][LANGUAGE_NONE])) {

    // Our custom cardinality (hardcoded here)
    $custom_cardinality = 3;

    // Unset all field multi values that are equal or larger than our $custom_cardinality variable
    foreach ($form[$field_name][LANGUAGE_NONE] as $k => $value) {
      if ($k >= $custom_cardinality) {
        unset($form[$field_name][LANGUAGE_NONE][$k]);
      }
    }

    // Our custom form validation
    $form['#validate'][] = 'example_custom_form_validate';
  }
}
/**
 * Our custom form validation callback.
 */
function example_custom_form_validate($form, &$form_state) {
  // Our field name
  $field_name = 'field_listing_images';

  // You may want to add more conditions
  if (isset($form_state['values'][$field_name][LANGUAGE_NONE])) {

    // Our custom cardinality (hardcoded here)
    $custom_cardinality = 3;

    // Unset all field multi values that are equal or larger than our $custom_cardinality variable
    foreach ($form_state['values'][$field_name][LANGUAGE_NONE] as $k => $value) {
      if ($k >= $custom_cardinality) {
        unset($form_state['values'][$field_name][LANGUAGE_NONE][$k]);
      }
    }
  }
}

My cardinality was based on the value of another field in a related entity, so I figured out that I could set the number of values to Unlimited in the field settings, then, in hook_form_alter, reattach the field to the form with a new cardinality:

$field = field_info_field('field_my_field');
$field['cardinality'] = $my_new_cardinality;
$instance = field_info_instance('entity_type', 'field_my_field', 'bundle');

// Depending on the form, the entity may be found in $form['#entity'],
// in $form_state, or elsewhere.
// $langcode is usually LANGUAGE_NONE, but may change in multilingual sites.
$items = isset($entity->field_my_field[$langcode]) ? $entity->field_my_field[$langcode] : array();
$new_field = field_multiple_value_form($field, $instance, $langcode, $items, $form, $form_state);

// This is not needed. It tricks theme_field_multiple_value_form into
// not adding the value reordering widget.
$new_field['#cardinality'] = 0;
foreach (element_children($new_field) as $delta) {
  $new_field[$delta]['_weight']['#access'] = FALSE;
}

$form['field_my_field'][$langcode] = $new_field;


How to create different Filter Criteria which works indipendently for every views (one is "For All" the other is "For this page") I will post down an image I edited to better help you understand what I'm asking for

The reason is I've more than 50 different views that filters the same objects from a single content type based on their personal taxonomy term that differentiates them in some sub-categories, but I want those views to also have a common filter for the Year in which they were created (for development reasons, the year is a taxonomy term with just a number like "2018" "2019") so that when I want the users to view the content created this year (2019) I just have to modify one filter criteria and update it for everyone else. Currently you can only have a single filter criteria section which can either be "for all" or "for this page", this means I've to manually change the year filter for all 50 of them because I need filter criteria to be Overriden in every single view to introduce a filter for each sub categories.
Is there a solution to this? a module? Or were can I find the PHP code which regolates how filters works?

You can't influence all Views that way at one go, that wouldn't make any sense because you can have various Views types (content, user, taxonomy term).

What you can have is a Master display within one View that can be used as a template for creating new displays. But that isn't what you're asking for.

You're asking for partial Filter handling, some Filters applied to all displays, and some Filters overridden for particular displays. But that isn't available AFAICT, at least not without complex code interventions.

But I think you might be helped with Contextual filters. Usually they are used when you need to Filter according to each taxonomy term, for example. It's tedious to create a new display for each term, instead, you let Drupal calculate that on the fly.

The same with the Date, you can use a Contextual filter on Authored on field to show only the ones from a particular year.

Automation is key when dealing with a large number of data.

Here's a couple of quick tutorials about Contextual filters: Using Drupal Contextual Filters in Views, How to use Contextual Filter in Drupal 8


How do I attached language specific css in Drupal 8? As the question states - how do I include a stylesheet based on a language? It has nothing to do with right to left reading, but for different colours etc.

You may want to use the "lang" attributes to style the language.

Here is the example:

<!DOCTYPE html>

I live in Italy.

Ciao bella!

Note: For :lang to work in IE8, a DOCTYPE must be declared.


Why this specific string is untranslatable I want to translate "You can only change the parent menu item for the published version of this content" which belongs to  Menu UI module.

The string is defined in /core/modules/menu_ui/src/Plugin/Validation/Constraint/MenuSettingsConstraint.php like below:

<?php

namespace Drupal\menu_ui\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Validation constraint for changing the menu settings in pending revisions.
 *
 * @Constraint(
 *   id = "MenuSettings",
 *   label = @Translation("Menu settings.", context = "Validation"),
 * )
 */
class MenuSettingsConstraint extends Constraint {

  // This string is untranslatable.
  public $message = 'You can only change the menu settings for the published version of this content.';
  public $messageWeight = 'You can only change the menu item weight for the published version of this content.';
  public $messageParent = 'You can only change the parent menu item for the published version of this content.';
  public $messageRemove = 'You can only remove the menu item in the published version of this content.';

}

This extends a class from Symfony and doesn't use t() function, but other strings defined in the same way are translatable(which means you can find the string in the localize.drupal.org). Below is an example of a translatable string.

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 * @Target({"CLASS", "PROPERTY", "METHOD", "ANNOTATION"})
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class Expression extends Constraint
{
    const EXPRESSION_FAILED_ERROR = '6b3befbc-2f01-4ddf-be21-b57898905284';

    protected static $errorNames = [
        self::EXPRESSION_FAILED_ERROR => 'EXPRESSION_FAILED_ERROR',
    ];

    // This string is translatable.
    public $message = 'This value is not valid.';
    public $expression;

    /**
     * {@inheritdoc}
     */
    public function getDefaultOption()
    {
        return 'expression';
    }

    /**
     * {@inheritdoc}
     */
    public function getRequiredOptions()
    {
        return ['expression'];
    }

    /**
     * {@inheritdoc}
     */
    public function getTargets()
    {
        return [self::CLASS_CONSTRAINT, self::PROPERTY_CONSTRAINT];
    }

    /**
     * {@inheritdoc}
     */
    public function validatedBy()
    {
        return 'validator.expression';
    }
}

I guess there're Drupal wrappers to make the strings originated in Symfony class implementations translatable. But why does the string in Menu UI remain untranslatable? It's not urgent, but I'm curious.

EDIT:
 Entity Validation API overview says
"Symfony validator is configured to use a Drupal translator class, such that violation messages correctly run through t(). ". So if my understanding is right, the untranslatable string also gets wrapped in t() eventually...?

There are two different aspects. The first one is how Drupal compiles the core translation list. This is based on the (not running) PHP code using the Translation template extractor (POTX).

You find only the first of the four messages on localize.drupal.org because of a naming issue in this particular constraint. Drupal searches for translation strings in certain locations and $messageParent doesn't match:

/**
 * Detect validation constraint messages. Drupal 8+.
 *
 * This sequences is searched for:
 *   T_POTX_CONSTRAINT = T_CONSTANT_ENCAPSED_STRING.
 *
 * note: T_POTX_CONSTRAINT is marked for T_VARIABLE tokens inside .php files
 *   with the "Constraint" suffix, where the token is "$message", or ends
 *   with "Message"
 *
 * @param string $file_name
 *   Name of file parsed.
 * @param string $save_callback
 *   Callback function used to save strings.
 */
function _potx_find_constraint_messages($file_name, $save_callback) {

See https://www.drupal.org/project/potx/issues/2884361#comment-13052396

The second aspect is about the run-time behavior. Symfony contraints are integrated into the Drupal translation system, so that messages are wrapped in a Drupal translatable markup object.

So a quick fix would be to visit the site in a non english language and trigger the error, then the string will be added to the translation list of your local site.


Page Content Type: Displaying error in Preview mode Whenever I am creating or editing a node, in the preview mode I see these errors.

This is the code I am using.

/**
 * Implements hook_preprocess_html().
 */
function campaigns2019_preprocess_html(&$variables) {
  if (isset($variables['node_type']) && $variables['node_type'] === 'landing_page') {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node->field_dark_theme->value) {
      echo("<script>console.log('here');</script>");
      $variables['attributes']['data-theme'] = 'dark';
    }
  }
}

The dark theme does not show up in preview mode though. However, if I ignore the errors and create my page, the dark theme works and everything seems to be displayed correctly. When is template_preprocess_html() called? Where in Drupal is it called?

The error is about accessing field_dark_theme from an un-existing node instance. The proper way of loading the node during preview is explained here.

On the other hand, welcome to the wonderful world of PHP for debugging properly (on Drupal), please check this post and this documentation entry check your proper IDE/stack on how to setup debugging tools.


What is the best way to use Panels with the Omega theme? I am new to drupal 7 so I have some questions about Omega theme.

I've installed Panels/Views and Omega Theme. Using the omega-tools I created a subtheme. How can I use the panels with the omega theme? I see there are two conflicting methodologies here. Is there any tutorial that can help me understand ?

If you want to use Panels, Omega is probably not the way to go.  The lead Omega developer is a big supporter of the Context module (as noted by Letharion) and you can see an example of the slow uptake of panels support on this thread.

If you're new to Drupal and want to use Panels, I would recommend trying Adaptivetheme, especially the 3.x branch (currently rc1 but due for a stable release soon).  Adaptivetheme has a long history in the Drupal community and has nearly 30,000 sites using it; it also has the best Panels support of all the major theme frameworks.  The 3.x version of Adaptivetheme adds support for responsive design in Panels, easy CSS resets, etc., making it very comparable to the Omega theme but allowing for excellent Panels support.  There are also a variety of subthemes available (links on the module page) that should give you a good idea of what this theme is capable of.


Custom user profile titles interfering with user views block I'm using this function to replace the titles on user pages with a user text field:

function MYMODULE_user_view($account, $view_mode, $langcode) {
  $wrapper = entity_metadata_wrapper('user', $account);
  $auth_name = $wrapper->field_account_auth_name->value();
  if ($auth_name) {
    drupal_set_title('Profile overview for ' . $auth_name;
  } else {
    drupal_set_title('Profile overview for ' . $account->name);
  }
}

It works as it should, but when I add a view block with user entities it makes every page have the same title. It's Profile overview for ' . $auth_name; for the first user with a non-empty field_account_auth_name. If I delete that user the next user takes its place. This is for all pages too, not just ones with the block in it.

If it matters I'm using this function

  function MYMODULE_preprocess_user_profile(&$vars) {
    if ($vars['elements']['#view_mode'] == 'auth') {
      $vars['theme_hook_suggestions'][] = 'user_profile__auth';
    }
  }

with a user entity "auth" I created using Entity View Mode, with this in user-profile--auth.tpl:

<div class="authProfile"<?php print $attributes; ?>>
  <?php print render($user_profile); ?>
</div>

and setting auth as the view mode in the view block. But the title problem happens with the user account view mode as well.

You could check the url using the arg function and only set the title if the current page is a user/* page. You could try something like the following.

function MYMODULE_user_view($account, $view_mode, $langcode) {
  if (arg(0) == 'user') {
    $wrapper = entity_metadata_wrapper('user', $account);
    $auth_name = $wrapper->field_account_auth_name->value();
    if ($auth_name) {
      drupal_set_title('Profile overview for ' . $auth_name;
    } else {
      drupal_set_title('Profile overview for ' . $account->name);
    }
  }
}


How to add text over Slideshow/carousel? I've been able to create a simple slideshow using field slideshow, jcarousel and libraries.

But how would I go about add text in the rhs of the images? I would like the text to change depending on the slideshow image.

First of all you are using views + views slideshow for the slideshow, correct??
And you are using a slideshow content type.

No => use views + views slideshow to show your slideshow contents as a slideshow. You can find instructions in its documentation and many videos to help you out(google knows best!! :))

Yes =>

in views : should show fields and not content
so you will have 2(or more per your need) fields : image and text(custom text area or say your title)
Using css you can position your text.

Hope it helps....keep posting your problems in comments...the community will always help you out.


Panel content page not displaying correctly after restoring backup on different server I recently had to restore a backup to a new server, and many things seem to be working fine, but others are not. For example The panes page which is suppose to show links neatly on the page in a dropdown menu is displaying them messily around the page. My pixture reloaded theme is also not working correctly.It doesn't seem to have the css styling.

Here is a picture of what it looks like:

First, before doing anything else, try clearing all the Drupal caches.

Then, if that doesn't do the trick, you need to make sure that you restore your files as well as your database.  Adaptivetheme and Panels both save some of their settings in files (for example, Adaptivetheme saves the color information of the theme); if you restore the database without the files, your site will behave strangely until you restore the files as well.

Alternately, if for some reason you do not have a copy of the files, you can re-save the theme settings by going to Appearance -> Theme name -> and then scrolling down to the bottom of the page and clicking "Save," which will cause Drupal to regenerate the theme files.


views 2 - how to fetch filepath of image field for output rewriting I'm in Drupal 6/views 2 and am rewriting the output of an image field. Is there a way to fetch the filepath of the image for the output? I have tried the filepath token for the image field, but the src for the image is not rendering, just the argument. Should I be using a preprocessor hook in a template file to do this instead?

One trick I like to use is adding a field that contains the value I need, then hiding it from display but using it's token value for your original field's override.

So your view fields would look something like:

image path (hidden from display)
image (using value from the above field)

Keep in mind that the order is important here, so you only have access to tokens that are above the field you want to use them in.

You may need to tweak the settings of the path field to make it the style of url you need (relative, absolute, etc).


Problems translating strings for my module As far I as know, the t() function is supposed to collect the strings and allow for their translation at admin/config/regional/translate/translate. This is not happening though for my module's string. Despite disabling the module + flushing the cache + enabling back, the string does not show up there.

I'm aware of the filters and case-sensitivity of the search field.

Any ideas as per what is going wrong?

The string has to be displayed at least once on the site (as far as i know). If this does not work, try to rename the string you want to replace with a translation and clear the caches again.


Skip checkout process if special field has value I want to skip the checkout process and node has bin publish for free product, but my module is not working!

Any pointers greatly appreciated

<?php
function MYMODULE_node_submit($node, $form, &$form_state) {
  global $user;
  if (in_array('administrator', $user->roles)) {
    if ($node['field_noeagahi']['und']['0']['value'] = 1) {
      $form_state['values']['commerce_node_checkout_skip'] = True;
      $node->status = 1;
    }
  }
  return $form;
}

You can implement hook_commerce_checkout_router and there check if order has product that has special field value

function hook_commerce_checkout_router($order, $checkout_page) {
  /*
if $order has product with special field
drupal_goto('');
  */
}


Programmatically update field collection data in custom entity I am in desperate need of help.

I have a custom entity called Question which has a bundle called data.
Within the data bundle, I have a collection field called options with two subfields called correct_option & misc_option.

-Question
 -Data
  -options
   -correct_options
   -misc_options

I am desperately trying to programmatically write data into those 2 option fields but the following code is not working:

$field_collection_item_value = 1596; // Get field collection item value.

$field_collection_item = entity_load('field_collection_item', array($field_collection_item_value)); // Load that field collection item.

$field_collection_item->save(); // Save field-collection item.

The 1569 is the ID of an existing question entity.

Whenever the code is executed I get the following error:

  Fatal error: Call to a member function save() on array

I would appreciate any help. I'm at a loss and not sure how to get this working.

Please use below code for update existing field collection data

//$item_id load item id from your node
//enter_update_field_mechine_name replace with your field name
  $field_collection_value = field_collection_item_load($item_id);
  $field_collection_value->enter_update_field_mechine_name['und'][0]['value'] = 'update text here';
  $field_collection_value->save();

This code worked for me
Thank you


Parameter page=0 gives problem in rules I have a rule which is activated with the following url

redirect/startcoursewithpage?course=502&page=1&module=471

The condition of the rule is:
- Check if URL argument exist for course
- Check if URL argument exist for page
- Check if URL argument exist for module.

The parameter values of course and module will never be 0. The page can be of a value of zero.

If the parameter page=0 is given in the url the condition is not true and the redirect is not done. If I remove the condition Check if URL argument exist for page it is working.

The value zero is directly from the database from another view. I think I should uuencode this zero value but I do’n know how. Other suggestions?

Having a look through the code of the module, the function that checks if the url parameter exists is this:

/**
 * Rules condition callback.
 *
 * Checks if the specified URL argument is set.
 */
function rules_url_argument_argument_exists($argument) {
  return !empty($_GET[$argument]);
}

This will return false if the argument is 0.

I think it should really be this:

/**
 * Rules condition callback.
 *
 * Checks if the specified URL argument is set.
 */
function rules_url_argument_argument_exists($argument) {
  return isset($_GET[$argument]);
}

Might be a good idea to submit an issue (and maybe a patch) in the modules issue queue.
I'm not exactly sure why the function gets the argument argument and doesn't use it
I have never used this module BTW.

EDIT:
There is also if (!empty($_GET[$argument_name])) { on line 71 of the module file that might need changing to isset.


How to I trigger Xdebug 3.x with Drush in PHPStorm Has anyone has success with getting CLI debugging (drush) working with Xdebug 3.x?
There are several obsolete posts here... but all obsolete with the new version of Xdebug.
Expected behavior
After setting a breakpoint in a PHP class or module, that I know is executed when a specific Drush command is run, I would like PHPStorm to stop at the breakpoint.
Debugging when initiated from the browser works beautifully.
Drush - nothing.
Though it used to before I;

upgraded to Catalina
upgraded Xdebug from 2.x to 3.x

Environment:
Local MAMP Drupal 8 / Drush 9.7.2
PHP
PHP 7.4.13 (cli) (built: Nov 30 2020 14:46:04) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.13, Copyright (c), by Zend Technologies

I am guessing that you have changed your xdebug.ini according to the new standards. (Port changed from 9000 to 9003 etc...)
If not you should do that first.
Check this link for additional information on the matter.
Besides that considering that you are using phpstorm, you should simply run
export XDEBUG_SESSION=PHPSTORM

before running the drush command. This must be done once every time you open a new terminal session. (Not sure if there is a way to have it permanently and if there is i am not sure you want it.) Nevertheless, if your configurations are ok, this should work.
Best Regards.


Prevent accessing files in Drupal files folder directly by following link I have member area on my site, and there i have files available only to members. (also, not to all members, but to members of some role, and also they are further granulated by field condition, but that is a long story :)

But technically, anyone can download a file, if knowing the link to the file.

I would like to prevent downloading files by direct link, or by being logged of site.

It would be perfect if i can execute a script when someone asks for file by direct linking, to check if user is logged in, if he has a role that grants him download.

But if that is not possible, i would like to disable accessing files directly, they should be only accessible by browsing the site.

Thanks for clues

Have a look at hook_file_download

  Control access to private file downloads and specify HTTP headers.

  This hook allows modules enforce permissions on file downloads when
  the private file download method is selected. Modules can also provide
  headers to specify information like the file's name or MIME type.


Adding the contextual link render element I have render array like this.

$array = [
  '#theme' => 'theme_wrap',
  '#content' => $data,
  '#contextual_links' => [
    'my_module' => [
      'my_module.router.name', $pid
    ]
  ]

and theme-wrap.html.twig

{%
set classes = [
'contextual-region'
]
%}
<div {{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {{ title_suffix }}
  {{ content }}
</div>

and file mymodule.links.contextual.yml

mymodule.admin.edit:
  title: 'Edit'
  route_name: my_module.router.name
  group: my_module

and route name my_module.router.name exited and working. Render data array working but don't see contextual link.

Update: I have a form to user can enter input. After submit i'll show data from user. And simple controller return array above.
- I have insert {{ title_suffix }},{{ title_prefix }} class contextual-region but don't working.

I was doing something wrong?
Please help!

First of, usually you want to handle the contextual links in your preprocess theme function so you don't have to handle it every time you need to render the thing.

The actual contual links is added to title_suffix, so you need to do {{ title_suffix }} somewhere in your template to actual render the contextual links. You also need to render the attributes or make sure your wrapper html tag has the contextual-region class.

In Drupal 8, most of contexual links are used with relationship to an entity. If you have something you can view and edit most likely it should be an entity, meaning you should use the entity view builder to render it etc. Might also make it easier for you to do contextual links, as there are many examples of how this is done in core and contrib, like the node module, user module taxonomy module etc.


Is there a recognized practice for keeping security details in files excluded from version control? As settings.php also contains the database connection details and the site key among others, it is excluded from version control in .gitignore.

But there some modules, APC for instance that require some of their configuration to be added to settings.php.

This means that some settings necessary for the site to run correctly may not be present in a site created from a git clone.

Is there a standard practice for dealing with this, ie enabling settings.php for source control and include-ing the security and other settings from different files, or vice versa?

We split our settings.php file into two separate files:

settings.php (for configuration that applies to all environments)
local-settings.php (for configuration that applies specifically to the current environment)

"settings.php" is stored in version control, while "local-settings.php" is excluded. Each environment has its own version of local-settings.php, which contains its database credentials and other configuration that applies only to that environment.

At the bottom of settings.php, we include the local-settings.php file.

/**
 * Check for a local-settings.php in this direcory. Include it if one exists.
 */
if (file_exists(dirname(__FILE__) . '/local-settings.php')) {
    include dirname(__FILE__) . '/local-settings.php';
}


complete installation proess for drupal 7.15 and ubercart-7.x-3.0 I install drupal 7.15 and working successfully. After that i add ubercart-7.x-3.0 module. enabled product and store module but cant enable cart and order. how to enable cart and order. I am the beginner of drupal and ubercart. please help me

Note: This is an alternative way by using Drupal commerce module and not the Ubercart module.

As a beginner I'd suggest you should try the Commerce Kickstart distribution first. It includes the latest versions of Drupal core, Drupal Commerce, and the other modules it depends on.  You can explore Drupal after that ;)

Just make sure you select the Commerce profile while installing (see screenshot)

And also create the example content after configuring the site


How can I do the dynamic select in Drupal 7 forms? In the following code I call the function players() which returns array of values for option. This values were defined beforehand by hand. How can I load it dynamically from the database?

 $form['officers']['officer'] = array(
'#title' => t('Select the officer'),
'#type' => 'select',
'#description' => t('Please, select the officer'),
'#options' => players(),
'#multiple' => FALSE,
'#empty_value' => ' ',
'#empty_option' => '- None -',

);

For example in the "Text Field"  there is property #autocomplete which defines a path where Drupal’s automatically included JavaScript will send HTTP requests using jQuery.

 $form['team_name'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#description' => t('Please, insert your name'),
'#autocomplete_path' => 'autofillform/teamname' ,

);
And i created the module which handles it.

<?php
function autofillform_menu() {
$items['autofillform/teamname'] = array(
'title' => 'Example autocomplete',
'page callback' => 'autofillform_teamname',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
 );
 return $items;
 }
 function autofillform_teamname($string){
 $matches = array();
 $result = db_query("SELECT name FROM users where lower(name) like '".$string."%'  LIMIT 10");
 foreach ($result as $user) {
 $matches[$user->name] = check_plain($user->name);
  }
 print drupal_json_encode($matches);
 return;
 }

Are there any possibility to do the same with "Select" ?

In any case take a look at the first answer of this question: i think it's what you are lloking for https://stackoverflow.com/questions/5158744/drupal-7-best-practice-for-a-dynamic-select-list-in-drupal-7


How to import csv file for "field collection" using feed-importers In Drupal7, In node processor settings -> we can't map field collection values. However they are multiple values, Is there any way of possibilites to import data through CSV file. I tried using field collection feeds module, In Processor Settings -> I selected "Field collection processor", then alert error is dispalying as shown "Missing Feeds plugin FeedsFieldCollectionProcessor". Is there any other way to solve this issue?

I recently had the same issue. Follow along with what I did:

Do NOT install the field collection feeds module.

Go here: https://drupal.org/node/1063434 and apply the patch in comment #16. (See https://drupal.org/patch/apply for details. Or you can just apply it manually, by copy & pasting the patch directly into /drupal/sites/all/modules/field_collection/field_collection.module).
EDIT: You may find more luck with one of the other listed patches on that page. #16 worked for me, so that is the one I suggested.

If the field collection fields have more than one instance, use the drupal module 'feeds tamper' to 'explode' the field collection mapping.

Clear your site's cache

Set new mappings to your field collection values (they should show up now as mapping targets).

Import your nodes, field collections and all!


How to use leanModal for loading a node or content in Drupal 7? I'm using this http://leanmodal.finelysliced.com.au , but unable to achieve the goal since I need that after clicking on my button the new content or a url for an instance node/3 should get load in this modal, any idea how can I do it?

The leanmodal javascript plugin specifically states that it does not include AJAX support. That means that whatever content you want to appear in your modal needs to be already included on the page content when the page initially loads.

If you want to load a different page's content in the modal, then you will need to use an approach that includes AJAX support. I would recommend one of the many Drupal options that provide this sort of functionality, such as Simple Dialog or cTools Auto-Modal.

The exact implementation will depend on the specifics of what content you are trying to load and in what context.


Error in simplesamlphp_auth.module: no valid attribute set I'm configuring my application as a saml provider and for this I have used simplesamlauth module. This module (simplesamlphp_auth) provides the ability to make a Drupal site into a SAML Service Provider (SP).

Now while configuring this module, I'm confused about the values that it will take as inputs.

I used SAML tracer, where I'm getting SAML response. Is it from here I will get any kind of attribute that need to be configure at /admin/config/people/simplesamlphp_auth/sync page?

Because right now it is giving me error:

  Error in simplesamlphp_auth.module: no valid \"nameid\" attribute
  set.\" at
  /var/www/html/modules/contrib/simplesamlphp_auth/src/Service/SimplesamlphpAuthManager.php
  line 165",

What would be the unique identifier for the user and username for the user?

The General values for same will be as follows:

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress

but if these not works you can also check the values in Metadata XML received from your IDP.


Add Help Text for User Roles Field on User Edit Page I would like to add some help text for one of the fields displayed on the admin user edit page (the page seen when an admin edits a user account).

The help text would provide a brief description of each role that could be selected.

Is there some hook I can use to update the admin form?

You can able to do it using hook_form_FORM_ID_alter or using hook_form_alter in a custom module..

You can add help text either using #suffix form attribute or #description attribute..


how to add other component (html tag, js, and css) in form module Suppose I have the following code.

class customCreateForm extends FormBase {

/* code code code... */

  public function getFormId() { /* code */ }
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['label'] = array(
      '#type' => 'textfield',
      '#title' => t('title'),
      '#description' => $this->t('Your title'),
      '#default_value' => "",
      '#size' => 10,
      '#maxlength' => 8,
      '#required' => TRUE,
    );
    /* code code code... */
    return form;
  }
  /* code code code... */
}

I can understand how to add a form element, but how can I add HTML markup or JavaScript?

For example, I want to add the following in my custom form.

<link type="text/css" rel="stylesheet" href="bla...">

aaa

you should add a library like this :

$form['#attached']['library'][] = 'my_module/mylibrary';

Create mylibrary.libraries.yml file with the content :

mylibrary:
  version: 1.x
  css:
    theme:
      css/my-css.css: {}
  js:
    js/my-js.js: {}

more documentation: https://www.drupal.org/developing/api/8/assets


How to set value for multivalue field in drupal 8 programmatically I was saving poll choices Programmatically in Drupal 8. I have used Drupal8 Poll choices module.

$node_poll = Poll::load($pollid);
//print_r($node_poll);exit;
$i = array(13,14,15);
foreach($i as $key => $value){
  $node_poll->choice->setValue(
        [
            ['target_id' => $value]
        ]
  );
// But I want to save multiple target ids. now this is saving 15 all the time.

}
$node_poll->question->setValue([
  'value' => 'test',
]);
$node_poll->save();

The following snippet is working fine.

$node_poll->choice->setValue(
        [
            ['target_id' => 13]
       ],
       [
            ['target_id' => 14]
       ],
        [
            ['target_id' => 15]
       ]
    );

How can I, make target ids to be saved dynamically?

I would rewrite your code like this.
N.B.: This an edited version of the original answer, following some helpful points coming from the comments.

$poll = Poll::load($pollid);

$poll->question->setValue(['value' => 'test']);

$target_ids = array(13,14,15);
foreach($target_ids as $target_id){
  $poll->choice->appendItem($target_id);
}
$poll->save();

Hope this does it!


How to change the error system messages is it possilbe to use string overrides module for system messages? What i need is to change the order of the words and add some more. For example i have a webform with some required fields. When user forget to fill a field it gets this message: "Surname field is required.". I need to change this to "The field Surname is required for this form". How can i do this?

Thank you

You can use String Overrides module. Also you can override strings through settings.php, look this post.

For example that you listed above, there is one string that contains variable !name. So "Surname field is required." is "!name field is required.", when you changing use "The field !name is required for this form" and you overrides all similar messages.


"Notice: Undefined index: und in include()" Since this morning, I get this message on my website.

It says the error is on line 7 in my template file, but when I look at the line 7 the code on it is <?php if (!$page): ?>.

My template file looks like the following.

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?>">

    <?php if (!$page): ?>
      <h2<?php print $title_attributes; ?>>
      <?php if (($type == "article") && ($node->field_add_taxonomy_tag_articles[$node->language][0]['tid'] == 26)): ?>
        <a href="/discoveries#node-<?php print $node->nid; ?>"><?php print $title; ?>

      <?php else:?>
        <a href="<?php print $node_url; ?>"><?php print $title; ?>

      <?php endif; ?>
    <?php endif; ?>
    <?php print $user_picture; ?>
    <?php if ($display_submitted): ?>
      <?php print $date; ?> Ñ <?php print $name; ?>
    <?php endif; ?>

      <?php
        hide($content['comments']);
        hide($content['links']);
        print render($content);
      ?>
      <?php if (!empty($content['links'])): ?>

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

      <?php endif; ?>

    <?php if (!empty($content['links']['terms'])): ?>

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

    <?php endif;?>

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

The line that is causing that error message is the following one.

<?php if (($type == "article") && ($node->field_add_taxonomy_tag_articles[$node->language][0]['tid'] == 26)): ?>

'und' is the value for the constant LANGUAGE_NONE, which is used for $node->language, when the node is language-neutral.

When you want to obtain the value of a field, you should use field_get_items(), as in the following code.

<?php $items = field_get_items('node', $node, 'field_add_taxonomy_tag_articles'); ?>
<?php if (($type == "article") && ($items[0]['tid'] == 26)): ?>


How to declare @font-your-face local fonts in CSS? Pretty simple question, why does my CSS not render my fonts when I declare it programmatically (in my CSS) vs when I use the @font-your-face  UI?

For a number of reasons I'd like to be able to control this from my styles. I'm declaring the CSS font-family declaration correctly and the text is being changed but it's going to some sort of Sans-Serif or Helvetica default.

If it matters I'm using, or trying to use omega 4.
thanks in advance.

Here's my css for the relevant selector, I know it's trying to work because the text changes but not to this font.

.l-page{width:960px;
    margin:0 auto;
    border:2px solid black;
    border-radius:15px;
    padding:2px;
    font-family: 'Cassannet - simple';
    font-weight: normal;
    font-style: normal;}

There is an option to apply the CSS in the theme in the drop down of the @font-your-face UI.


how do I add javascript to a specific panel-page I have created a panel page (i.e using panels). I can add html content to it from the panel itself using add content->New custom content. I can also add css classes (add body css classes).

Now I would like to add a jquery button to that panel page. I could add a javascript to my theme but then it would be called on every page load not only this specific panel-page. So I would like to add my javascript through my module.

But how do I programatically check that the current page beeing viewed is that specific page panel? Is there a hook that lets me check that?

Thanks,

baba

I'd probably do this in the theme with template_preprocess_panels_pane() - http://drupalcontrib.org/api/drupal/contributions!panels!panels.module/function/template_preprocess_panels_pane/7

You can do (make sure you have devel.module installed first)

MYTHEME_preprocess_panels_pane(&$vars) {
  dpm($vars);
}

and get a full print out of everything that's going on in all your panel panes.  With enough digging, you should be able to find a $vars['_something_']['#attached']['js'] = YOUR_FILE; to hook into.  I think you can do this in a module too, if that's what you want.

EDIT: After actually thinking about it though..

I would probably advise against this and just put it in your theme js.  Unless it's an enormous amount of js, you're going to be taking better advantage of Drupal's js aggregation by not doing this.  If you put the js in your theme, it'll be compiled into the main site js file automatically, whereas if you do something different when only this panel pane is showing, it'll require that an entirely different js file be aggregated and downloaded on pages when it shows.

Assuming this is a performance tweek, I think you might actually be headed in the wrong direction with this one, since browsers should cache this file after the first time it's downloaded.

edit: hook name typo