How do I sort the field value by null in Search API Solr? I want to alter the search API Solr query in Drupal 8 to order by field null in hook_search_api_solr_query_alter(). How do I add my sort expression in the Solr search query? Do I need to add it in hook_views_query_alter()?

I also had this issue, I couldn't find an easy way to sort by null in a query alter (although Solr does have sortMissingLast, I just couldn't figure out how to inject it through Search API). Instead, I added a processor to check the field in question and add another field to identify whether it's there or not. Then you can sort by that.

<?php

namespace Drupal\my_module\Plugin\search_api\processor;

use Drupal\Core\Annotation\Translation;
use Drupal\search_api\Annotation\SearchApiProcessor;
use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * Checks for my field.
 *
 * @SearchApiProcessor(
 *   id = "my_field_null",
 *   label = @Translation("Has My Field"),
 *   description = @Translation("Adds a check for null field to index."),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 *   locked = true,
 *   hidden = false,
 * )
 */
class MyFieldNull extends ProcessorPluginBase {

  /**
   * Machine name of the processor.
   * @var string
   */
  protected $processor_id = 'my_field_null';

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = [];

    if (!$datasource) {
      $definition = [
        'label' => $this->t('Has My Field'),
        'description' => $this->t('Does this have my field?'),
        'type' => 'string',
        'processor_id' => $this->getPluginId(),
      ];
      $properties[$this->processor_id] = new ProcessorProperty($definition);
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    $entity = $item->getOriginalObject()->getValue();
    if (method_exists($entity, 'hasField') && $entity->hasField('field_my_field')) {
      $has_field = TRUE;
    }
    else {
      $has_field = FALSE;
    }

    $fields = $this->getFieldsHelper()
      ->filterForPropertyPath($item->getFields(), NULL, $this->processor_id);

    foreach ($fields as $field) {
      $field->addValue($has_field);
    }
  }

}


Recursive Drush make, working with different git branches Setup

For every site we make a custom Drupal install profile is created, copies of which are built using drush make (through Aegir, though that should not make a difference).

There is a top-level build makefile for downloading Drupal core and our install profile, and the install profile contains a makefile specifying Features to download, each of which have a makefile specifying their dependencies (either custom modules in private git repos or contrib modules).

The build makefile (build-SITENAME.make) specifies the install profile like this:

projects[SITENAME_profile][type] = profile
projects[SITENAME_profile][download][type] = git
projects[SITENAME_profile][download][url] = git.hostname:drupal-sites/SITENAME_profile

Then the install profile's makefile will specify a bunch of Features to download, for example:

projects[blog][type] = module
projects[blog][subdir] = features
projects[blog][download][type] = git
projects[blog][download][url] = git.hostname:drupal-features/blog

Which will then download custom and contrib modules and so on.

The above setup has worked well for a couple of years.

Problem

The problem occurs when trying to use git branches for managing different stages of development, e.g. development, staging and production; and having CI automatically manage Drupal sites for each branch. If a build is triggered for the development branch, drush make has to get the correct branch for every one of our repos it downloads.

Given our multi-repo and recursive makefile structure, how would drush make be used to recursively download the correct branch from our git repos?

Things already tried

drush make allows downloading from a git branch, which seemed good
for our use-case. For example, for each makefile (in the build,
install profile and Features repositories) a line is added that
looks like:

projects[blog][download][branch] = development

When the branch of the repo being downloaded matches the branch of the
repo the makefile is in, custom modules specified in the
development branch of the 'blog' Feature will be downloaded from
that module's development branch. Great!

However, this causes problems merging the branches of any repo containing a makefile (given our setup that's quite a lot), we will have to be extremely careful not to accidentally merge [branch] = development into master on any of them.
Checked drush make documentation for a command-line option to specify the default branch for git repository downloads. Found nothing.
Searched the Internet for people with similar quandaries, it seems many are dumping all the dependencies for whole projects into single make files, but that breaks the modularity of Features.

Note: I'm not polling or asking for discussion. I believe there's something silly I'm missing and/or something everyone else is doing that I'm not.

This is a great question! I maintain both Aegir and Drush Make, but I'm not certain that I have a really good answer for you.

I think that you're suggestion in (1) is probably the best bet at
the moment. It has the virtue of already working, as you've
mentioned. The issue with accidentally merging these [branch]
attributes is still valid though. The solution though, lies not in
Drush Make, but in Git!

Check out this article. It describes using Git attributes,
along with a custom (null) Git merge driver. To summarize, each
developer would have to run the following:

git config --global merge.ours.driver true

This basically means that when an item is flagged to use the
'ours' merge driver, it'll just call /bin/true, hence my earlier
reference to it being a null operation.

But, how do you flag your makefiles to use this driver? That's where
Git attributes come into play. Create a .gitattributes file at the root of your repo (i.e., along side .gitignore). Then add the
following line:

build-SITENAME.make merge=ours

You'll probably want to do the same for your feature repos as well.
As for solutions leveraging Drush Make, I don't know that there's a
solid solution.

A few years back, I experimented with using overrides trying to do
something similar, as described in the Drush Make
documentation. The basic idea is that you can change (override)
attributes from included makefiles.

However, in the case of recursive makefiles, they are built
separately, instead of being merged into the parent makefile prior
to build. As a result, there's no opportunity to override their
attributes. This may have changed in the time since I tested it, but
I think the underlying mechanics remain largely the same, and so
it's unlikely to work.

Setting a default in a parent makefile would be a nice way to
accomplish something like this too. I haven't tested this, but
again, I'm pretty sure the default wouldn't apply to the recursively
built makefile.

Instead, an option would be to build your parent makefile without
recursion, but rather including the feature makefiles directly. You
can now include makefiles directly from within a Git repo
(using the new YAML syntax):

includes:
  # A file from a git repository.
  makefile: "example_dir/example.make"
  download:
    type: "git"
    url: "git@github.com:organisation/repository.git"
    branch: "master"

You'd either want to call drush make with the --no-recursion
option, or specify it in your makefiles:

--no-recursion                   Do not recurse into the makefiles of any
                                 downloaded projects; you can also set
                                 [do_recursion] = 0 on a
                                 per-project basis in the makefile.

I'm sure there are other options available, but those are the ones that I think would least impact your existing workflows. I'd be very curious to see other suggestions.

There is a feature request to allow the use of variables in .make files, which might address such a use-case more directly, if it were implemented. Perhaps we could look for such variables in options passed on the command line, or in environment variables.

That said, in the long run, I believe that Drush Make will be supplanted entirely by Composer, so it might be more fruitful to explore in that direction, if the suggestions above don't work out.


multilingual site with views I'm trying to set an english/spanish website and I've already set in my post types which are the types I want to be translatable. I also translated the posts but I'm not really sure how to set the views to display the content based on the language... I want the spanish posts to show up in domain.com/es/whatever/route ... and the english posts to show up in domain.com/whatever/route ... right now, both paths show the same content (the posts in English and the posts in Spanish)...

I'm guessing I need to somehow set contextual filters and relationships but I'm not so sure about how. Could I get a hand with that?

for Views module add filter: Node translation: Language ->  Current user's language.


Token does not return full dynamic path to Media Image URL I'm having trouble configuring Metatag for Open Graph and Twitter Card images.
I'm using Drupal 8.9 core Media Image reference field as the source.
[node:field_hero_image] (Entity reference field) just returns the bare filename.
[node:field_hero_image:entity] (The referenced entity) also returns the bare filename, not the expected path to the image.
[node:field_hero_image:target_id] Just returns an integer. (In this case, it is 1.)
I'm reduced to trying to build the path by combining Tokens and plain text, like this:
[site:url]sites/default/files/2021-01/[node:field_hero_image]

This works, but the problem is that I used the default File Directory path:
[date:custom:Y]-[date:custom:m]

That means media assets that I upload in February will be at a different path than the ones I uploaded last month, so hard-coding the path to the directory is pointless.
Now, I could change the File Directory path to a const str like images, delete all my Media Images and recreate them.
I'm guessing there is a better approach: either a Token that returns the correct image URL, or a way to bulk reconfigure Media Image assets after moving their File Directory.
Please help!

Would you believe:
node -> media field -> media entity -> image field -> image style -> url
Makes sense, right? (I mean, it makes sense if you understand core Media and Entity References.)
As a Token, it looks like this:
[node:field_hero_image:entity:field_media_image:large:url]
Not exactly intuitive, but it makes sense in hindsight. The Media field is an entity reference to a Media entity containing an Image field that can be rendered in a variety of Image styles, so the token chain goes all the way down that rabbit hole.
This approach generates a valid image URL in the header meta tags.
Of course, AddToAny is still not picking up the metadata when I share a Twitter card ... but that's a different issue!
Just pointing out to nobody in particular that this Token does not show up in the Node section of the "View available tokens" box. ¯\_(ツ)_/¯


Views Taxonomy get children of a specific parent term within a vocabulary I have a taxonomy vocabulary with 2 parent terms with children (fishing, and hunting) I want to get all children of the fishing parent term. I've tried to do it with core, but not sure it is possible.

I'm not exactly sure what you need to implement, but here are the steps to get you what I think you need. For demonstration, I created my own vocabulary with animals like so:

Then I created a view that will accept any of the term names as a contextual filter and return its children like so:

If that's what you need, then here is how you create the view. I'm not sure how you wanted to display them, so I didn't create a page or block display.

Step 1: Add new view

Step 2: Add contextual filter for parent term

Step 3: Configure the contextual filter like so

Save that contextual filter to the view and it will return the children based on the name of the term you pass to it. There may be additional steps to get it working the way you want it, but you weren't really specific. I hope that gets you started.


How to count the number of checked Checkboxes with Rules? I have a Drupal Commerce site which uses user points (= coins) for paying.

I have a special case - the product, which the user should buy with his/her coins, needs some fields filled out by the user. So I used a content type for this case and when the user adds a new one, 10 coins will be reduced from the user's account - this works already fine.

Now I have also a taxonomy in this content type and the user can add terms to it, which are shown later in the form when the user fills it.

Problem :

I need to count how many checkboxes of the taxonomy terms are checked and multiply the costs with them. So if 3 of 5 are checked, then 10 coins * 3 = 30 coins will be the final price when the user adds a new content type.

Is this possible with Rules? I have no clue how to realize that
(I´m front-end developer and no PHP coder).

Yes this is perfectly possible with Rules, and you don't need any PHP to get the job done. In your case, the crucial part of such rule is a Rules Action to perform a Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should use (at least) these Rules Actions:

"Add a variable" (say with a machine name like nr_of_checked_terms), with initial value "0".
Add a loop related to your taxonomy terms. After you do, you should iterate over each item in that list (= each taxonomy term). And for each iteration you should then perform a Rules Action to "Set a data value", whereas you actually increment the value of nr_of_checked_terms with "1".

After the loop finished, the value of nr_of_checked_terms will be the actual number of terms that were checked. Just add another Rules Action near the end to do your actual multiplication using nr_of_checked_terms as one of the available tokens.

Done

PS 1: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.

PS 2: I assume this is about D7 ...


Decode an image in base 64 to a file, using feeds, feeds tamper and jsonpath I have a problem importing a 64 base image through the feeds module. I am consuming a service through jsonpath.

I am using the tamper feeds module to try to decode the image and then save it as a file but I have not succeeded.

I get the data well in the attribute mapping between the service and the content type, but I can not get the feed tamper to decode it and save it as an image in the content type.

Is this possible to do?

Feeds Base64 images module

I have developed a module for this which adds two additional targets for file and image fields:

Filename
Base64

The 'Filename' target always needs to be mapped first.

I created this module years ago, but I never published it on drupal.org... until today!

https://www.drupal.org/sandbox/megachriz/2961717


How to add a view mode for entity type? I want to add a view mode for particular entity type programmatically in Drupal 8.I think the documentation on view modes for Drupal 8 has not been provided like it was provided for Drupal 7 hence I am facing problem in implementing this.Any reference from module in core would help.Thanks

What needs to be done if I want to add view modes to many entities?

View modes are configuration entities.

Like anything else that is a config entity, it's very simply to put into "code": Make it default configuration. Create it in the UI, do a configuration export (admin/config/development/configuration/single/export), and then place core.entity_view_mode.$entity_type.$view_mode.yml file into config/install inside your module.

The view mode will then automatically be imported and created when the module is installed.

Note that it's not hardcoded then, so a user could remove it. If you want to prevent that, you can implement hook_entity_view_mode_access() to deny delete access to your entity for everyone.

By default, you will have a problem re-installing the module because it will not remove that view mode when you uninstall the module and display an error when you install it again. There are two ways to fix that:

Move the config to config/optional instead of config/install. Then it will only be created if it doesn't exist yet.
Add an enforced dependency on your module, which will ensure that it will be removed when the module is uninstalled. Note that this only works if you had this in place when you installed the module the first time.

Like this:

  dependencies:
    enforced:
      module:
        - yourmodule


Configuring drush alias for rsync with exclude paths and file patterns I tried adding exclude paths and file patterns to my drush alias; it didn't work, but adding the filters with --exclude= in the command works.

drush rsync --exclude=imagecache/* --exclude=ctools/* --exclude=js/* --exclude=tmp/* --exclude=xmlsitemap/* --exclude=*.doc* --exclude=*.DOC* --exclude=*.pdf* --exclude=*.PDF* --exclude=*.ppt* --exclude=*.PPT* --exclude=*.zip --exclude=*.ZIP --exclude=*.xls* --exclude=*.XLS* @sitename.live:%files @sitename.local:%files

(I wanted to create the directories but skip the contents)

I looked at a similar question but I'm not sure what I am doing wrong.

The docs for drush core-rsync explain:

  --exclude-paths List of paths to exclude, seperated by : (Unix-based systems) or ; (Windows).

here is what I tried:

$aliases['live'] = array(
  'root' => '/var/www/[domain]/htdocs',
  'uri' => '[site uri]',
  'remote-host' => '[host ip]',
  'remote-user' => 'rgoya',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
  ),
  'command-specific' => array(
        'sql-sync' => array(
            'no-cache' => TRUE,
        ),
        'rsync' => array (
            'mode' => 'rlptDz',
            'exclude-paths' => 'css:imagecache:ctools:js:tmp::xmlsitemap',
            'exclude' => '*.tmp',
            'exclude' => '*.doc*',
            'exclude' => '*.zip',
            'exclude' => '*.xls*',
        ),
    ),
);

I also tried 'mode' => 'azv'

Also, can I use regexp in the exclude patterns? some extensions are lowercase, some are uppercase .pdf / .PDF

Your subsequent 'exclude' items in the PHP array are overwriting their previous ones, so the example above only has --exclude=xls

drush help rsync does not explicitly document the syntax for --exclude but I assume that it's similar to --explude-path and that would mean you should do something like this:

'rsync' => array (
  'mode' => 'rlptDz',
  'exclude-paths' => 'css:imagecache:ctools:js:tmp::xmlsitemap',
  'exclude' => '*.tmp:*.doc*:*.zip:*.xls*',
),

EDIT: looking into the example.aliases.drushrc.php there is this tip included:

// if you need multiple exludes, use an rsync exclude file
'exclude-from' => "'/etc/rsync/exclude.rules'",

That's maybe the best way to go.


How to rebuild derived plugins after new entities are installed? I have a problem with a stale plugin-derivatives cache in a kernel test:

  protected function setUp() {
    parent::setUp();
    $this->installConfig(['my_module', 'my_module_test']);
  }

The my_module_test module installs new entities that should produce derived plugins, but when my test class tries to instantiate these plugins, they are not found.

It works if I explicitly call $this->container->get('{my_plugin_manager}')->clearCachedDefinitions() after installConfig(), so it's definitely a stale plugin cache. But I'm worried this problem might happen elsewhere. Is there some way to tag the plugin cache with {my_entity_type}_list so it gets invalidated by new entities? Or do I simply need to invalidate it explicitly whenever I do something that creates new entities?

Yes you should do that.

Module install is not really a problem as all plugins are invalidated then anyway, but entities can also be changed in the UI.

See \Drupal\block_content\Entity\BlockContent::postSave() for an example that does that in core.


Remove items from a menu based on node type efficiently I am trying to remove items from a menu based on the type of node it links to.

I'm currently achieving this using hook_menu_link and menu_get_object. I'm running into problems because the size of the menu is 500+ items, resulting in 5000+ DB queries to generate the page.

If I remove the hook_menu_link function and show all menu items, the DB queries drop to around 700.

Here is the current code:

function amoss_menu_link(&$variables) {

  // Hide book sections from the menu;.
  if (isset($variables['element']['#original_link']['link_path'])) {
    if ($variables['element']['#original_link']['menu_name'] == 'book-toc-1') {
      if (book_modifications_is_book_section($variables['element']['#original_link']['link_path'])) {
        return '';
      }
    }
  }

  // Output a menu link.
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

function book_modifications_is_book_section($link_path) {

  if (book_modifications_get_type_from_link_path($link_path) == 'book_section') {
    return TRUE;
  }

  return FALSE;
}

function book_modifications_get_type_from_link_path($link_path) {
  $node = menu_get_object('node', 1, $link_path);

  if (isset($node->type)) {
    return $node->type;
  }
  else {
    return '';
  }

}

I tried to use drupal_static in the book_modifications_get_type_from_link_path function, that killed the conditional checks.

I tried caching the results for each item with set_cache, but this was not successful either.

function book_modifications_get_type_from_link_path( $link_path ) {

    if ($cache = cache_get('book_modifications_'. $link_path )) {
        $type = $cache->data;
    }
    else {
        // Do your expensive calculations here, and populate $my_data
        // with the correct stuff..
        $node = menu_get_object('node', 1, $link_path);
        $type = isset( $node->type ) ? $node->type : '';
        // dpm('miss');
        cache_set('book_modifications_'. $link_path, $type, 'CACHE_TEMPORARY');
    }

        // dpm($type);
    return $type;
}

I appreciate any suggestions for making this slow operation faster.

Gathering node paths for the book_section nodes in a function cached with drupal_static and using removing items from the menu based on that, rather than loading node objects for each menu item removed thousands or surplus DB queries.

Refactored code

function amoss_menu_link(&$variables) {

  // Hide book sections from the menu;.
  if (isset($variables['element']['#original_link']['link_path'])) {
    if ($variables['element']['#original_link']['menu_name'] == 'book-toc-1') {
        $book_sections = book_modifications_get_book_section_paths();

      if ( in_array( $variables['element']['#original_link']['link_path'], $book_sections ) ) {
        return '';
      }
    }
  }

  // Output a menu link.
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

function book_modifications_get_book_section_paths() {
    $book_section_paths = &drupal_static(__FUNCTION__);

    if (!isset($book_section_paths)) {
        $book_section_paths = array();
        $nids = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('type', 'book_section', '=')
        ->execute()
        ->fetchCol();

        foreach ( $nids as $id ) {
            $book_section_paths[] = 'node/'.$id;
        }

    }

    return $book_section_paths;
}


How to get the original value of a field that is inside a field collection? I can get the entity reference field node id from my field collection like this:

function mymodule_node_update($node){

    if ($node->type == 'article'){

    $node_wrapper = entity_metadata_wrapper('node', $node);

        $before = array();

        foreach ($node_wrapper->field_collection_ingredients->value() as $key => $field_collection_wrapper) {

          $before[$key] = $field_collection_wrapper->field_ingredient[LANGUAGE_NONE][0]['target_id'];

        }
  }

Doing:

$before[$key] = $field_collection_wrapper->original->field_ingredient[LANGUAGE_NONE][0]['target_id'];

Causes an error.

Basically I have an entity reference, which allows unlimited values, inside the the field collection.

When someone removes a value from the entity reference field, I need to know which value was removed as I need the Node ID to update that node that was removed from the entity reference.

Try comparing field_collection_ingredients field value of $node->field_collection_ingredients[LANGUAGE_NONE] and $node->original->field_collection_ingredients[LANGUAGE_NONE], this will give exactly which field collection was removed, you can then try loading that field collection (see note below) and then load $fc->field_ingredient[LANGUAGE_NONE][0]['target_id']; field value to update Node referenced in field_ingredient field.

Note: If your node does not has revision enabled, the removed field collection will be removed from Drupal database as well, which will cause the error when trying to load the Field Collection Entity. So you might need to enable revision for your main node, to make sure that if field collection is removed from field_collection_ingredients field, it will not get removed from Database.


Creating an iframe playlist that loops through urls (from a node field) Scenario

A content type called "Playlist" exists. Playlist has a text field: field_playlist_sources. When a user creates the Playlist they can add multiple values for field_playlist_sources. Each value is a url like: http://somesite.com.

When the Playlist node is viewed, the field_playlist_sources field is displayed with a Custom Formatter (using the Custom Formatters module). The format for the display of this field is:

<iframe src="" name="frame" id="frame" width="100%" height="1080px" seamless frameborder="0" scrolling="no"></iframe>

Notice the empty src.

What I'd like to do is loop through the values provided for field_playlist_sources within the iframe.

With Javascript this would look like this:

var frameSRC = Array(
  'http://someurl.com', 60,
  'http://anotherurl.com', 60);
var i = 0, len = frameSRC.length;

function ChangeSrc() {
  if (i >= len) { i = 0; } // start over
  document.getElementById('frame').src = frameSRC[i++];
  setTimeout('ChangeSrc()', (frameSRC[i++]*1000));
}

window.onload = ChangeSrc;

As of right now, I'm not sure how to bring in the values from the field to this javascript file. Maybe there is a better approach?

Any help would be greatly appreciated.

I'd probably do this in two steps (all within the formatter hook).

Separate the js processing into an external include, added via drupal_add_js();
Put the urls into Drupal.settings.mymodule.playlist and call these from your ChangeSrc() function.
If you're wanting to do it semantically, skip point 2 and just ouptput <a href="src" data-something="60"> in your formatter markup. Then pull those hrefs with your js and inject them into the iframe.

Standard code for including custom js settings:

$settings = array();
$settings['mymodule']['playlist'][] = array('url1','metadata1');
drupal_add_js($settings, 'setting');


Choose a facet using the search form and then show filtered results The requirement is that the user specifies a facet before they search. Here's what the search form should look like:

Adding the select list to the search form is a straight forward form_alter(). My problem is how do I send the selected audience value from the drupal form to solr?

Once I have the audience value in the solr query object, I think I would apply the facet by using HOOK_apachesolr_query_prepare() (or HOOK_apachesolr_query_alter()).

Thanks!

Here's my solution:

Add the select menu to the form and append a custom submit function

  function ucb_parking_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case "search_block_form":
      // Add the audience select list
      $form['search_audience'] = array(
       '#type' => 'select',
       //'#title' => t('Choose Audience'),
       '#options' => array(
      47 => t('Faculty/Staff'),
      36 => t('Student'),
      ),
       '#description' => t('Focus your search on an audience.'),
      );
      //Add a custom submit function to the end of the array of functions.
      //(This function will run after apachesolr_search_form_search_submit().)
      array_push($form['#submit'], 'ucb_parking_front_page_search_submit');
      break;
  }

}

In the custom submit function construct the solr url with a query string representing the facet that should be applied and redirect the user there:

function ucb_parking_front_page_search_submit($form, &$form_state) {
  /*
   * Simply construct the solr url for the search.
   * Note the querystring for the facet must be passed via an array with the 'query' key
   * to ensure correct urlencoding.
   */
  $form_state['redirect'] = array($form_state['redirect'], array('query' => array('f[0]' => 'im_field_audience:' . $form_state['values']['search_audience'])));
  //drupal_goto is probably equivalent
  //drupal_goto($form_state['redirect'], array('query' => array('f[0]' => 'im_field_audience:' . $form_state['values']['search_audience'])));
}

I think that this is the correct approach because apachesolr does pretty much the same thing with $form_state['redirect']:

/**
 * Added form submit function to retain filters.
 *
 * @see apachesolr_search_form_search_form_alter()
 */
function apachesolr_search_form_search_submit($form, &$form_state) {
  $fv = $form_state['values'];
  // Replace keys with their rawurlencoded value
  if (isset($fv['search_block_form'])) {
    $raw_keys = str_replace("/","%2f",$fv['search_block_form']);
    $form_state['redirect'] = str_replace($fv['search_block_form'], $raw_keys, $form_state['redirect']);
  }
}


there any field in view that display Display author and date information I have created a view for my project, is there any field in view that displays "Display author and date information" ?

Assuming you mean the date posted and making assumptions also on entity types.

For nodes:
Author: Add the "Content: Author" relationship and then the "User: Name" field.
Date: Add the "Content: Post date" field.

For comments:
Author: Add the "Comment: Author" field.
Date: Add the "Comment: Post date" field.


Custom page with fixed content Me again with the noob question.
I want to achieve this:
At the url http://ROOT/something/{numeric_id_here} to get a page that lists the header and the footer of the theme and my custom content. The content is not manage-able through the admin. It depends on the numeric id.
Here is what I got so far.
I use the hook_menu for this:

function something_menu() {
    $items['something/%id_here'] = array(
        'title' => 'Some title',
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

I have the function that parses the url and gets the numerical value:

function id_here_load($arg) {
    $data = get my custom data from an external xml feed based on $arg; //this works nicelly - I get an array with the data I need.
    //WHAT'S NEXT?
}

Now I'm stuck. how can I pass $data to a template and render that template in the content of the page?
My question is somehow similar to this one. Just that the answers provided there don't cut it for me.

You need more in your hook_menu() like this:

function something_menu() {
  $items = array();

  $items['something/%id_here'] = array(
    'title' => 'Some title',
    'type' => MENU_NORMAL_ITEM,
    // This is the function that will return your page content.
    'page callback' => 'something_custom_page',
    // This will pass the $data variable you returned from your loader function
    // into your page callback (not the ID in the URL).
    'page arguments' => array(1),
  );

  return $items;
}

Then your load function needs to actually return what it has loaded, like this:

function id_here_load($arg) {
  // Do some checks o make sure no one can pass in bad data via the url.
  // This is an example you need to check based on your data.
  if (is_numeric($arg)) {
    $data = get my custom data from an external xml feed based on $arg; //this works nicelly - I get an array with the data I need.
    // If you get back valid data.
    // Again you need to make this relevant to your data.
    if ($data) {
      // Return the data.
      return $data;
    }
  }
  // If for any reason you didn't end up getting data return FALSE.
  // This will cause access denied for this page because of an invalid ID or something.
  return FALSE;
}

Then you need to implement your page callback function like this:

function something_custom_page($data = array()) {
  // Do something with the $data to create the page and return
  // either a string of HTML or a drupal render array.
  // Returning a render array is the preferred option.
}

See Render Arrays in Drupal 7 form more info on render arrays.


matching path rewrite without htaccess I need to move a legacy Drupal 7 site to our new Aegir hosting environment. Unfortunately, the file structure is "non standard". I need to move drupal/materials to drupal/sites/default/files/materials but also need a corresponding path rewrite or redirect .htaccess or http.config is not an option, I need to do it in Drupal.

Redirect module does not do tokens or wild cards. Match_redirect module does not rewrite, but matches on a many to one bases. A rewrite would be better than a redirect.

I cant seem to find an existing contrib - how would I do this in PHP with the Drupal APIs? Would I want to use hook_boot or hook_init?

If you have some control on the Aegir instance, and 100% trust your users that have sftp/ssh access to your site, you could use the provision_customhtaccess module:
https://github.com/mlutfy/provision_customhtaccess

This makes it possible to have a "htaccess-custom" file in your sites/example.org/ directory that will get included in your vhost configuration. However, it is a big security risk if you do not trust your users. They can close a vhost declaration, open a new one, do many bad configurations, etc.

Alternatively, if you're going to write a new module, it seems pretty easy to add in the match_redirect module. There is a feature request open, so I am sure the community would appreciate. Worst case, you can offer the maintainer to sponsor the development:
https://www.drupal.org/node/2118233

You can see how drupal_match_path() does a match and use that to rewrite the target redirect:
https://api.drupal.org/api/drupal/includes!path.inc/function/drupal_match_path/7


How to delete/hide "create new account" I have 2 roles on my site. I created 2 pages and corresponding links through which each of the roles will register.

I want to prevent users from using the default user registration menu ("create new account") by either deleting it or hiding it. Also i want to prevent users from being able to visit user/register.

Please how can i achieve this?

Use hook_menu_alter() to remove default registration page from menu system. Simply unset($items['user/register']); and clear menu cache.


Drupal Commerce Line Item temporary delete? I need to temporarily remove a few line items from an order.  I can remove them well enough, but they won't add back.  There aren't any error messages in watchdog, the error log, or on screen.

Here is the code I have currently:

$orderWrapper = entity_metadata_wrapper('commerce_order', $order);
$removedLineItems = array();

// Loop over each line item on the order.
foreach ($orderWrapper->commerce_line_items as $delta => $lineItemWrapper)
{
  $product = $lineItemWrapper->commerce_product->value(); // Get id to pass to line_item_delete

  if ($product->some_field[LANGUAGE_NONE][0]['value'] !== 'some condition')
  {
    $lineItem = commerce_line_item_load($lineItemWrapper->getIdentifier());
    $removedLineItems[] = $lineItem;

    commerce_line_item_delete($lineItemWrapper->getIdentifier());
    unset($orderWrapper->commerce_line_items[$delta]);
  }
}
commerce_order_save($order);

// Run some other code on $order
somePlugin_someFunc($order);

// Add back items removed for package calculation
if (count($removedLineItems) > 0)
{
  foreach ($removedLineItems as $lineItem)
  {
    commerce_line_item_save($lineItem);

    $orderWrapper->commerce_line_items[] = $lineItem;
  }

  commerce_order_save($order);
}

Anyone have an alterative to the above?

Turned out the issue was simpler than I thought.  If you think about the field between line_items and orders as a reference, it makes sense to just remove that reference, save the order, than re-add it later.  I assume the issue was arising that Drupal didn't like deleting than recreating the exact same line_item, so if it isn't ever deleted, than the reference can just be updated.


Get all orders that contain a certain product I am trying to create a rule so that when a node containing a commerce product is update will notify all customers that have made a order containing this product.

I act on event "After updating existing content" and get to the commerce product using entity has field (field_product).
How can I get from the product to all the orders containing it so I can loop through them?

I ended up creating a module for it as it didn't seem possible to implement using rules.

here is the function that is called on hook_node_update

//load all pending orders
$orders = commerce_order_load_multiple(array(), array('status'=>'pending'), TRUE);
//go through the loaded orders
foreach($orders as $order){
    //load each order as an entity
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    foreach($order_wrapper->commerce_line_items as $line_item_wrapper){
        //check if the order contains this node's product
        $product = $line_item_wrapper->commerce_product;
        $node_product = $node_wrapper->field_product;
        if($product->sku->value() === $node_product->sku->value()){
            //change the status of the order to processing
            $order_wrapper->status = 'processing';
            $line_item_wrapper->save();

            $order_wrapper->save();
        }
    }
}
return TRUE;

Now since I got the respective orders to processing status, I can go on using rules for the rest of the implementation.


Exposed filters doesn't work I have recently come to begin to work on a site built by someone else, so I have no idea of what specifics may have been done when building this site I am referring to. At the moment, I'm trying to revamp the structure (as well as the look to play around with it in sections), and came across an interesting problem.

In the view, I have three exposed filters: 1) Object ID 2) Title 3) Keywords (from the Search:Search Terms filter).

Now when I type in the Title filter, everything works as expected. And when I type in Keywords filter for something that would be somewhere besides the Title, that works as well, with the exception of dates and numbers that aren't in the Title Field.

You can find this page here http://history.arvadahistory.org/photographs1

You will notice that each content type has a picture, then a blue title, then a black string of letters and numbers. An example being this: HF.00668

Now, when I type this (HF.00668) into the Object ID filter, I get absolutely nothing, but when I go to type this in the overall site search, the proper content pops up.

So why would my filters be acting like this? And is there any way to fix them?

Check query of view when you providing HF.00668 value in Object ID.

SQL query of views can be enable from views settings page with name of Show the SQL query.

You can also check operator value in exposed field settings.


How do you use tabledrag API in a multi-page environment? As you can see in the image below, I'm using drupal_add_tabledrag to allow admin to sort node order by dragging. But how do I drag the items from one page to another? Is there additional Drupal API, or if not, how would you go about this?

There can be hundreds of nodes, I cannot fit them on a single page.

I doubt anyone else will have a useful answer. But the DraggableViews module for Drupal 6 showed 3 items from the previous and next Page(s) in paged results. Allowing you to drag an item from the previous page into the previous or next page.

Now if you have hundreds of items I'm not sure how you would skip multiple pages at once -- but looking at how they did this could help you to extend the Drupal 7 Draggable Views module to achieve the functionality you want.

Unfortunately the Drupal 7 DraggableViews does not support this yet.

Proof of this is in this issue queue:
https://www.drupal.org/node/1458870


How to add 'read more' link in Blog comments I created blog entry pages for different subjects in a website. Each blog page displays its comments. I need to trim the comments and add read more link. I can trim the comments, but can't able to add read more link. I can't create view for the blog pages because different blog pages needs to display differently. Any ideas? Please help me.

You can override comments template for your blog content type and in the template add the read more link.

In order to override the template simply copy the existing comment.tpl.php to your theme/templates and rename it to comment--node-blog.tpl.php and edit it to add the read more link.

on click of this you will be running jquery codes to toggle the comments below.


VBO mass email via local email client I have a drupal 7 view diplaying nodes containing an email address field. I would like the user to be able to select multiple rows and then execute an action that simply open his own email client with a new message with all the email addresses in the To: field. I don't want to let users send mass emails via my website but give them an easy way to send emails to many addresses at thew same time via their local email client.

try integrating the Views Send Module, the instructions specifically mention VBO:

  Views Send enables you to send mass mailing from a View.

Since you aren't able to install new modules, it could be done this way:

Create the view as a table of fields, include the email address as EMAIL PLAIN TEXT
add the VBO field, Save Content (you can choose anything you want, but this seems the least offensive)
add some css:

#views-form-email-test-page #edit-select {   display:none; }

This will hide the VBO button since we are overriding its functionality manually
add a header, Global Text:

<button type="button" onclick="emailUsers(); return false;">email users</button>

add a modified version (modified for view and field names) of this JS to your html.tpl.php, or drupal_add_js, or by whatever other means you want:

function emailUsers()
{
    var toField = '';

    jQuery('#views-form-email-test-page table tbody tr').each(function()
    {
        if(jQuery('.views-field-views-bulk-operations div input', this).is(':checked'))
        {
            toField += jQuery('.views-field-field-address', this).html() + ',';
        }
    });

    if(toField.length > 0) window.location.href = "mailto:" + toField;
    else alert('Please select at least one user to email!');
}

This all assumes:

the View machine name is name email_test
the View is a page
the field holding the email address is field_address

EDIT FROM OP:

  Thank you very much Geoff, your solution works very well, I've learned
  a few things and I hope it will be usefull for others in the futures,
  indeed I was quite surprised not to find anything when I searched
  befor posting. Since my email field was also a link I've used the
  following code

  tmp = jQuery('.views-field-field-applicant-email', this).html(); tmp2
  = jQuery(tmp.replace('mailto:','')); toField += jQuery(tmp2).attr('href') + ',';

  instead of

  toField += jQuery('.views-field-field-address', this).html() + ',';

  not very elegant may be (I'm not a programmer) but it works! for some
  strange reasons I cannot upvote your answer, sorry.


Restrict Specific Nodes to Roles I been using Drupal for a while, but I am completely in the dark when it comes to Roles, permissions, etc.

What I want to do is have all my content types, but I want to restrict certain nodes for certain roles. Does anybody know any modules or if the core can do this? The reason why I am doing this is to share with a specific group of people on my site.

Thanks!

You can use the Content Access module to achieve this.

  This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.


How to deal with 'internal:' in your link->uri? I have a link field, which I can populate with both internal and external links:

  /node/123

I'm building an API that parses the node and returns the URL from the link field:

$node->my_field->uri

Which returns internal:/node/123 which makes this URL useless.

If I try using use Drupal\Core\Url; and Url::fromUri($node->my_field->uri), I get a 500 error!

So what is the correct approach for getting a formatted URL, that can parse both internal and external links?

just kidding. To help future devs with this issue, check the logs *duh and you'll see this:

  PHP message: Uncaught PHP Exception InvalidArgumentException: "The URI '' is invalid.

So, check for the uri value first!

$node->my_field->uri ? Url::fromUri($node->my_field->uri)->toString() : null,


Prevent path based breadcrumb in theme, or, don't show breadcrumbs for 403/404 responses? I am looking to do one of these solutions for a users 'contact' page. When a user has unchecked "Personal Contact Form", and someone accesses that URL (user/id/contact), the breadcrumb displays the users username in the breadcrumb.

The username in the breadcrumb is not desirable, because some people make their email address their username, so:

How can I disable the breadcrumb from displaying on 403/404 responses, or
How can I disable the path based breadcrumb service outright?

You could add a visibility condition to the breadcrumb block. For 404 there is this module block_in_page_not_found and if you negate the condition the block is displayed on all pages other than 404's:

If you want to exclude 403 pages as well you can extend this module and add a check for

$status->getStatusCode() == 403

to Drupal\block_in_page_not_found\Plugin\Condition\PageNotFoundRequest::evaluate.

Or use the patch from this issue Allow blocks to be configured to show/hide on 403/404 pages, when it applies again.


Add an extra class to views exposed filter “select” if default option is selected I have some views exposed filters and need to add an extra class "test" to each list if it has default option selected.
I try to implement it using jquery with the following code:

function ($) {
$(document).ready(function () {
    $('.form-select option:eq(0)').prop('selected', true);
      $(".form-select").addClass("test").on('change', function() {
      var optionIndex = $(this).find('option:selected').index();
      $(this).toggleClass('test', optionIndex === 0);
   });
});
})(jQuery);

Question is how to make this code to act properly in Drupal 7? Currently it adds the "test" class to all the dropdown lists after the page load. But if you chose any not default value in any list the "test" classes of all lists (even where default option is selected) disappeared and never appeared again until the page reload.

Change the selector and class name to your needs, but this should work.

(function ($) {

  $("select")
    .change(function() {
      if ($(this).val() === $(this).find('option[selected]').val()) {
        $(this).addClass('default-value-selected');
      }
      else {
        $(this).removeClass('default-value-selected');
      }
    })
    .trigger("change");

})(jQuery);


Why does my 'UUID, Webform, Node' Feature remain overridden? The Feature I have created is stuck in the "Overridden" state. (I have also deployed the Prod Environment's database to the Dev Environment's database to ensure that everything was in sync during this test).

I am using Drupal 7 and am using the following modules in this situation:

Webform
Context
UUID
Features
UUI Features

Here are the additional dependencies:

Under "Configuration > Content Authoring > UUID Features Integration", I have selected the "Webform" Content Type as one of the "Exportable Node bundles" and "Files exported for Node bundles" on both my Prod and Dev environment.

When viewing the overridden page, the only component that is stuck in the "Overridden" state is the "Content" section (with the UUID of the two nodes listed):

When clicking "Revert components", it actually does revert the two nodes listed back to the state in the features. (Tested it by modifying the nodes and then clicking "Revert components" to see it revert back.

Despite that, it remains in the "Overridden" state.

In this particular situation, why does this remain Overridden?

FWIW, features should only be used to export configuration, and not content. I have audited a site which used UUID features and was not able to find a solution for reverting it. Exporting content (nodes, taxonomy terms, etc.) also makes the feature heavy.

Some things which you could do to :

Have multiple instances: (approach 1)

Dev : continuous deployment happens here. E.g. After every commit or pull/merge request.
Stage : Intermediate deployment; maybe after some feature is done completely. Think of this as a release. Or at every sprint end. When the code deployment happens. Database from the production instance is copied to this instance. So, that the testing can happen on live data.
Live : Sometimes called production instance. Data is only created here. Deployment to this instance happens very infrequently.

These are all servers located on internet. Then, each of the developers have their own "local" site setup. Database from the live site should be used to test new features being developed (or bug fixes). This will ensure more accurate results, as testing happens on latest content.
Note: You can use features in this case only to export configuration.
If you do not want direct addition of content to live environment, try modules like Workflow, Workbench, or Workbench Moderation; which enables you to empower checking of content before the actual publish happens.

Important note: If you are using live database make sure you sanitize it. drush sql-san commands can come in handy.

Use Deploy module: (approach 2)

  The Deploy module is designed to allow users to easily stage and preview content for a Drupal site. Deploy automatically manages dependencies between entities (like node references). It is designed to have a rich API which can be easily extended to be used in a variety of content staging situations.

Using this module, you can create content on one environment and push it to others. It is pretty easy to setup, with extensive documentation available.

In a nutshell -> KEEP "CONFIGURATION" AND "CONTENT" SEPARATE TO MAKE YOUR LIFE EASY!


Import CSV, row by row, into custom table I have a Drupal 7 submit method for updating CSV row by row to a custom table which I found under this link. I have tried to update it so that it works in Drupal 8 to no avail. How do I to modify it to work in Drupal 8?

function custom_module_submit($form, &$form_state) {

    $file = $form_state['values']['csv_upload_file'];
    $file->status = FILE_STATUS_PERMANENT;
    $file->filename = str_replace(' ', '_', $file->filename);
    file_save($file);

    $csv_file = file_load($file->fid);
    $file = fopen($csv_file->uri, "r");

    while(! feof($file))
    {
        $customer = fgetcsv($file));
        db_insert('your_db_table')
            ->fields(array(
                'column1' => $customer[0],
                'column2' => $customer[1]
            ))
            ->execute();
    }

    fclose($file);

    drupal_set_message('CSV data added to the database');
}

The Drupal 8 code that I am trying to use is as below:

public function submitForm(array &$form, FormStateInterface $form_state)
{
    $file = $form_state->getValue('csv_upload');
    $file->status = FILE_STATUS_PERMANENT;
    $file->filename = str_replace(' ', '_', $file->filename);
    file_save_data($file);

    $csv_file = \Drupal\file\Entity\File::load($file->fid);
    $file = fopen($csv_file->getFileUri(), "r");

    while (!feof($file)) {
        $customer = fgetcsv($file);
        \Drupal::database()->insert('your_db_table')
            ->fields(array(
                'column1' => $customer[0],
                'column2' => $customer[1]
            ))
            ->execute();
    }

    fclose($file);

    drupal_set_message('CSV data added to the database');
}

Errors include:

Fatal error: Call to a member function getFileUri() on null in /home/annuities/public_html/modules/custom_module/src/Form/CustomForm.php on line 90.

Line 90: $file = fopen($csv_file->getFileUri(), "r");

Warning: Creating default object from empty value in Drupal\custom_module\Form\CustomForm->submitForm() (line 85 of modules/custom_module/src/Form/CustomForm.php).

Line 85: $file->status = FILE_STATUS_PERMANENT;

Notice: Undefined property: stdClass::$filename in Drupal\custom_module\Form\CustomForm->submitForm() (line 86 of modules/custom_module/src/Form/CustomForm.php).

Line 86: $file->filename = str_replace(' ', '_', $file->filename);

The file could not be created.
Notice: Undefined property: stdClass::$fid in Drupal\custom_module\Form\CustomForm->submitForm() (line 89 of modules/custom_module/src/Form/CustomForm.php).

Line 89: $csv_file = \Drupal\file\Entity\File::load($file->fid);

Warning: array_flip(): Can only flip STRING and INTEGER values! in Drupal\Core\Entity\EntityStorageBase->loadMultiple() (line 227 of core/lib/Drupal/Core/Entity/EntityStorageBase.php).

I used the code below;

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

    $file = $form_state->getValue('csv_upload_file');

    $destination = $file[0]->toArray()['uri'][0]['value'];

    $file = fopen($destination, "r");

    while (!feof($file)) {
        $customer = fgetcsv($file);
        \Drupal::database()->insert('your_db_table')
            ->fields(array(
                'column1' => $customer[0],
                'column2' => $customer[1]
            ))
            ->execute();
    }

    fclose($file);

    drupal_set_message('CSV data added to the database');
}


Clean URL for custom content I have a custom content type movie. Now, when I visit any of the movie content, the url is like:

mysite/?q=node/someNumber

I want that every movie content will have url like

mysite/movie/somenumber

or,

mysite/?q=book/someNumber

How to do this?

I am using Drupal 7.

Enable Clean URL + get Pathauto module, which allows to define custom URL patterns for every type of content

If the Clean URL test fails, the web-server is not configured to support this feature. You need to configure the web-server to support Clean URL.

With Apache HTTPD as web-server, you have to enable mod_rewrite and configure the necessary rewrite rules. The rewrite rules can be found in the .htaccess file that comes with Drupal. Usually, theses rules are applied automatically, when mod_rewrite is enabled, but in some cases, the AllowOverride directive is too restrictive to allow this.

See Clean URLs in the Drupal Installation Guide for a more thorough introduction on how to get Clean URLs working in Drupal.


Ubercart 2.x: Given a product nid, retrieve its manufacturer I'm trying to figure out how Ubercart stores manufactures.

Currently it's set up as a Vocabulary, but I can't figure out how to grab that info programmatically given a product nid.

Any advice?

In Drupal 6 taxonomy terms are linked to the node object, Ubercart just piggy-backs off the way Drupal core handles this.

You can use the very handy taxonomy_node_get_terms_by_vocabulary() function to grab all of the terms associated with a node in a certain vocabulary. You would use it like so:

$vid = 1; // Vocabulary ID
$nid = 1; // Node ID

$node = node_load($nid);
$terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);


Import data into Select List using using Feeds and the Feeds XML Parser from xml file I have to import some data from a xml document.

I'm usuing the https://www.drupal.org/project/feeds and the https://www.drupal.org/project/feeds_xpathparser modules.

I have other fields which get the data with no problem at all. But I can't get a Select list to get the data from the xml.

XML LOOKS LIKE

<properties>
  <property>
    <type>House</type>
  </property>

  <property>
    <type>Flat</type>
  </property>

  <property>
    <type>Parking</type>
  </property>
</properties>

INFO OF THE field "Type" WHICH GET THE DATA:

Type:

List (text)

Control:

Selection List

Allowed values list:

House|House
Flat|Flat
Parking|Parking

THEN, IN THE FEED IMPORT SETTINGS:

-MAPPING: add the xpathparser selecting the field "Type"
-XPHATH XML PARSER - Settings: set the XPath for the field to "Type"

As far as I see everything is all right, but it doesn't work.

I have other fields in the same importer which get the data with no problem at all.

If you're on Drupal 7.x, you probably want to be using this module:

https://www.drupal.org/project/feeds_ex

This is the new home for no-longer actively maintained one (https://www.drupal.org/project/feeds_xpathparser)

I've been using feeds_ex and haven't had this problem.

Also, and I'm not sure about this, but I think the machine names for the list values should all be lowercase - but I could be wrong about this.


how to get the NodeID into views-view-field--field-image.tpl.php to create an  redirect this is my code:

  <?php $nodeurl = url('articles/' . $node->nid); krumo($node->nid); ?>
  <a href="<?php echo $nodeurl ?>"

    <div class="img-container <?php print $imageClass; ?>">

my code is not fetching a proper nodeID and when i krumo it (inspect passed elements) it brings back a null value. My code seems correct, can i get some help :)?

This is in a view correct? I believe you need to use node_load($nid) to load the node data first in order to fetch it. I would try something like this

$node = node_load($nid);
$nodeurl = url('articles/' . $node->nid);


How to exclude the user table using the drush sql-sync command How do I exclude Drupal's user table from drush's sql-sync command?

You can use --skip-tables-list flag on your drush sql-sync command

drush sql-sync @prod @dev --skip-tables-list=user

the table lists should be comma seperated.

For more options on sql-sync check this documentation.


Creating Multifield Search with Apache Solr Search I'm using Apache Solr Search on Pantheon and trying to figure out how I can create an "advanced" multifield search.

For example if I have a content type called Location, with "city" and "state" fields, how can I make those fields part of the search form, similar to an exposed filter in Views?

I successfully installed and setup Facets using Facets API module, but those just add clickable links. I'm looking for the user to be able to search by multiple fields.

I also tried the Apache Solr Views Integration module, but that only allows text fields as exposed filters.

If anyone has suggestions, documentation, or a tutorial on how to do this that'd be great. Obviously I could do it with Views but I do not want these searches hitting the Drupal database.

You can use Custom Search module. Create a search block with your custom filters (taxonomy list). And enable "Allow user input using the URL" in your Apache-solr settings page (ADVANCED SEARCH PAGE OPTIONS section).


How to edit Drupal core rdf.module functionality Using drupal's core RDF module there is a function (shown below) that add "xml:lang" attibute to tags. What I want to do is to change this functionality so that $variables['attributes_array']['xml:lang'] = 'en'; instead of leaving it blank like in the core module. What would be the best way to achieve this?

/*
 * Implements MODULE_preprocess_HOOK().
 */
function rdf_preprocess_username(&$variables) {
  // Because xml:lang is set on the HTML element that wraps the page, the
  // username inherits this language attribute. However, since the username
  // might not be transliterated to the same language that the content is in,
  // we do not want it to inherit the language attribute, so we set the
  // attribute to an empty string.
  if (empty($variables['attributes_array']['xml:lang'])) {
    $variables['attributes_array']['xml:lang'] = '';
  }
}

You can add the following preprocess function to template.php in your custom theme. The RDF module is preprocessing the variables used by the theme_username() function. Your custom theme can also preprocess these same variables and override the values set by the RDF module.

/*
 * Implements THEME_preprocess_HOOK().
 */
function YOURTHEMENAME_preprocess_username(&$variables) {
  $variables['attributes_array']['xml:lang'] = 'en';
}


How to find number of assigned content to all user I have book content type, where i attached user entity reference fied.
In which i can select user to assign the books.

How can i find list of users and its number of assigned books.

Thanks

Basically you need to add the entity reference field using relationship to the view. Then use aggregation to find the count.

Refer https://www.ostraining.com/blog/drupal/entity-reference-views/ on how to create view using entity reference field.
To find the count, you can use aggregation. For using aggregation you can refer https://drupal.stackexchange.com/a/31542/48290.


Order receipt e-mail language for guest checkout Is there a way to have the order receipt e-mail be in the language of the site version that was used for placing the order?

The order receipt e-mail that gets sent out (content of commerce-order-receipt.html.twig) for a guest is currently always in the default language. That means a user would order items from the French site, and get an English confirmation. It appears that no language data is saved for an order, so I guess there's no built-in way to do this.

Does anyone have any ideas?

This is a known problem. Orders need a language field.

That will be added as a part of https://www.drupal.org/project/commerce/issues/2603482


How do I clone a product? Is there any method yet for cloning existing products in Drupal Commerce 2?

Be careful with the https://www.drupal.org/project/entity_clone module. Because it may happen that you've made a ton of product clones and then decided to edit, let say, price of some variation on a clone or a "parent" product. The price will change everywhere. The same with deletion of variation. Moreover, the same with deletion of any of the clones or the "parent". All variations will be deleted everywhere. But that's not the end. If you try to delete any of variation-less clones you'd get fatal error. So, to delete this clone you need to save at least one variation.

That's because variations are entities which can be referenced by multiple products. Read more: https://www.drupal.org/project/commerce/issues/2941524

So, as I understand you need cloning for cutting off the time spent on variations creation, which is quite tedious work, I'd say. If so, you may try the Commerce Bulk module.


drupal_mail to users selected from database In my Drupal 7 site I use custom tableselect form to manage some events. User can review profiles of people who applied for event and approve their participation. I want to send them email notification via drupal_mail on form submission. I have implemented hook_form_submit and added following code

foreach ($values as $key => $value){

    $sql = db_select('users', 'u');
    $sql-> fields('u', array('mail'));
    $sql-> condition('uid', $value['uid']);
    $mail = $sql->execute();
    }
    foreach($mail as $m){
    dsm($m);
    drupal_mail('event_manager','event_approved', $m, language_default());
    }

But in this case I have an error :

  Warning: explode() expects parameter 2 to be string, object given in
  SmtpMailSystem->mail()

How can I fix the code to make it work?

On a first glance, it's because you are passing the whole object instead of the email address. Try this:

  $sql = db_select('users', 'u');
  $sql-> fields('u', array('mail'));
  $sql-> condition('uid', $value['uid']);
  $mail = $sql->execute();
}
foreach($mail as $m){
  dsm($m);
  drupal_mail('event_manager','event_approved', $m->mail, language_default());
}


Build an EntityFieldQuery that selects referenced entities I am looking for the ID of the entity of type A and I know the ID of entity B that references A.

I found a few nice sources about EntityFieldQuery. I was amazed that i was getting results from .NET in google :) (is it a sign of Drupal's maturity ? :). But didnt manage to find this. Please help ...

Some of the sources :

How to on d.o
Discussion about building an example
An example module on github

This is what it looks like with entity loads - you will understand i need that query :) The wrapper is there for practice mainly. Note that it loads the target entity - quite a lot of queries.

  $b = entity_load('B', array($id));
  $bm = entity_metadata_wrapper('B', $sl[$id]);

  $tsl = $slm->field_sl_tpref->value();
  echo $tsl->id;

You can use target_id instead of value to retrieve entities based on the ID of referenced entities:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', <type-of-the-entity>);
$query->fieldCondition('<name-of-the-field-referring-the-other-entity>', 'target_id', <id-of-the-referenced-entity>, '=');
$results = $query->execute();


Drupal as feed aggregator I'm interested to aggregate posts on my Drupal site with the built-in feed aggregator.
The feed aggregator can make different feeds based on categories which is nice; my problem is that, when users create a post, they cannot assign a category at the same time. They have to later on find the post manually via the feed aggregator and set the category.

Is there a way to allow users to assign categories while creating a post?

The aggregator is for importing feeds from other sites, but it sounds more like you're trying to create new feeds on your site from your content. For that use, you could use Views.


Searching on Taxonomy terms with the Search API module? I've been playing around with the Search API module for a little bit now, and it seems to be working fairly well, but I can't figure out how or why I am not able to search on terms even though they are selected among the search fields.

Does anyone have any hints or pointers on what I could be doing wrong?

On the field index page, at the bottom see Add related fields select the term field you want to search. When you save, this adds a number of items associated with the term fields. Then select Taxonomy >> Name to index as Fulltext. Now it is searchable.


Hierarchical select as radio buttons and checkboxes I have a need to display a hierarchical select of a vocabulary as a series of radio buttons representing the top-level terms.  When the user selects one of the radio buttons, the child taxonomy terms should be displayed below as checkboxes.

Do I need to build a custom AHAH form, or can I look at form altering the default hierarchical select widget?

For drupal 6 you may want to check out the module https://drupal.org/project/conditional_fields which basically lets you control which form elements depend on other form elements. It also has a handy GUI for doing this.

FYI drupal 7 has completely changed the game here and has implemented 'states api' - here is an example of what can easily be achieved - http://api.drupal.org/api/examples/form_example--form_example_states.inc/function/form_example_states_form/7


Can a theme name be started with a number? Can I start a theme name with a number? For example: "123go"

Does Drupal recognize folders & files that start with it?

Does it work in the temple.php as the start of a function?

oh, got it- "A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores."

php.net/manual/en/functions.user-defined.php

That answers that question. Don't start a theme name with a number because it can't be used as a function in template.php


Rebuild in Features tripping HTTP 500 Error I am trying to rebuild some features in Drupal 7.37 in preparation for migration and upgrade on a local dev environment using MAMP but I get an HTTP 500 error when attempting to view overrides. Watchdog reports errors with "undefined offset" in schemaorg.features.inc.

Thanks for any help pointing me in the right direction on this one.

This Drupal install was on a local environment using MAMP. The problem was solved when I increased the max_execution_time in MAMP's php.ini from 30 to 100.


Scrape articles from one Drupal site to other? Let's say I have already a Drupal website that has lots of articles and etc. And now I want to build another Drupal website under different domain, and when new article is added to the old site it would be somehow automatically scraped to the new website too?

Both sites are separate and not running under same database nor single installation.

I didn't find a module yet which would do what I need. It has to scrape articles into views lists and also somehow scrape views slideshows content and should be put in sidebars also somehow via views, I didn't find a solution yet, so that's why I asked here.

You do not need to install a module for this. This sort of thing is provided by the Drupal core. It is called an "Aggregator" and you find it as one of the core modules with the following description:

  Aggregates syndicated content (RSS, RDF, and Atom feeds).

It is not enabled by default.  You need to enable it.

Here is a rundown of the UI:

administer your list of news feeds. Admin → Configuration → Web Services → Feed aggregator
add a new feed. Admin → Configuration → Web Services → Feed aggregator → Add feed
add a new category. Admin → Configuration → Web Services → Feed aggregator → Add category
configure global settings for the news aggregator. Admin → Configuration → Web Services → Feed aggregator → Settings
control access to the aggregator module. Admin → People → Permissions
set permissions to access new feeds for user roles such as anonymous users. Admin → People → Permissions
view the Aggregator page. Admin → Configuration → Web Services → Feed aggregator
update the feed manually. Admin → Configuration → Web Services → Feed aggregator

You need to set up cron to update the feed automatically.

If the site you want to use as the source for your feed is running Drupal 7, the export feed is already in place.  The URL should be http://example.com/rss.xml.

Near the bottom of the page of any Drupal 7 (unless you've taken steps to remove it), there should be a symbool like this:

If you click on it, you should be able to inspect your outgoing feed (provided your browser knows about RSS feeds).

You can of course use this to aggregate content imported from more than one site, but it will also work fine if you just to import content from your own, old site.


PDOException: SQLSTATE[HY000] [2002] No such file or directory in _registry_check_code() Drush is running on MAMP, PHP 5.6.6.

Inside /Volumes/Doxy/htdocs/omegadoen/sites/all/themes/omega

I run:

drush omega-wizard

I get:

  Additional uncaught exception thrown while handling
  exception. Original PDOException: SQLSTATE[HY000]
  [2002] No such file or directory in drupal_is_denied() (line 1917 of
  /Volumes/Doxy/htdocs/omegadoen/includes/bootstrap.inc).Additional
  PDOException: SQLSTATE[HY000] [2002] No such file or directory in
  _registry_check_code() (line 3169 of /Volumes/Doxy/htdocs/omegadoen/includes/bootstrap.inc).Drush
  command terminated abnormally due to an unrecoverable error.   [error]

What now?

For simplicity check drush status with verbose and debug parameters:

drush -vd status

If you're using different profile, don't forget to include it as -l http://foo.

If you still have a problem, it's an issue with bootstrapping your Drupal.

First check your SQL connection if it's working:

drush sql-cli

If it does not, check your db credentials in your Drupal settings file.

If it does, there is a problem with SQL connection through the socket.

So in MAMP you've to do:

Check value of socket in my.cnf (menu: File/Edit Template), it's usually set as:

socket      = /Applications/MAMP/tmp/mysql/mysql.sock

Double check if your MySQL can find this file:

$ mysql_config --socket
/Applications/MAMP/tmp/mysql/mysql.sock

Double check if your PHP has the right mysql.sock set-up:

$ php -i | grep mysql.default_socket

Link the socket into your /tmp and see if that helps:

sudo ln -s /Applications/MAMP/tmp/mysql /var/mysql

Test the socket file:

mysql --socket=/var/mysql/mysql.sock

Still the problem? Add the following setting into your $databases:

$databases['default']['default'] = array(
  // ...
  'unix_socket' => '/var/mysql/mysql.sock',

Troubleshooting

Try: drush sqlq "SELECT @@version_comment LIMIT 1"
Try: drush ev "Database::getConnection('default', 'default');"
Try: mysql --socket=$(php -r 'echo ini_get("mysql.default_socket");')
Check permissions on Unix socket: stat $(mysql_config --socket)
Debug: on OS X with sudo dtruss -fn mysqld, on Linux with strace
Debug with XDebug:

echo '<?php xdebug_start_trace("/tmp/foo.log");' > init.php
drush -c init.php ev 'Database::getConnection("default", "default");'
or set xdebug.show_exception_trace=1 in your xdebug.ini

Check MySQL settings:

echo '<?php phpinfo();' > init.php
drush -c init.php  ev 'Database::getConnection("default", "default");' | grep mysql

Run: php -r "new PDO('mysql:host=localhost;port=3306;charset=utf8;dbname=dbname', 'root', 'root');"
Try to rebuilt your registry


How to implement a calendar based system for loaning of equipment? I have looked MERCI over and it appears to be a great module but sort of like swatting flies with sledgehammers. We are a public library support agency and, among other items, we offer month long loans of 3D printers.

I'm looking for a way to implement a simple item registration system, that is calendar based so monthly calendars can be printed.

I like Basic Cart but need more of a library loan approach than a sales approach.

Any suggestions?

Below is a summmary of the modules you may want to look at. These modules have a stable release for D7, and also for D6 (quotes are from their project pages):

Availability Calendars.

  ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.

  An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Simple Reservation.

  ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

  The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.

  There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

MERCI.

  ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.

Resource Conflict.

  ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

Booking Systems Comparison

Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.

This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).

How to pick the module that fits best

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.

So do your homework to pick the right one for you. E.g. by using criteria such as those I often use for selecting module, as mentioned in the community documentation about Maintenance Scorecards.

Here is the intro about it (from that page):

  ... contains a list of 23 criteria (=28-5) that might help to evaluate
  the maintenance and support of contributed modules. Below is an
  attempt to apply those criteria to each of the native charting modules
  ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

Disclosure: I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph).


How Can I change the fields order without using CCK I want to change the order of the fields in each node. I know that I can use CCK but I would like to do this in hook_node_load

Is it possible?

Thx :)

In my views cck will always overwrite the weight you assign programmatically, best way should be arranging the cck fields in order you want.
If you want to change order on the fly using javascript can be an option too,but not sure if it is good option
for example

jQuery('.field-name-field-test-taxonomy').insertAfter('.field-name-field-simple-text-field');

where ".field-name-field-test-taxonomy" and ".field-name-field-simple-text-field" are the wrapper div for cck fields respectively.with out the above js code the default taxonomy field was coming before the simple-text field but with we simply change the order.
hope it helps.


how to get uri of an image field in a views_view_list twig template using drupal 8? I have a twig template generated from views-view-list.html.twig!
Its a view uses ECK entities.

Available variables:
- attributes: HTML attributes for the container.
- rows: A list of rows for this list.
  - attributes: The row's HTML attributes.
  - content: The row's contents.
- title: The title of this group of rows. May be empty.
- list: @todo.
  - type: Starting tag will be either a ul or ol.
  - attributes: HTML attributes for the list element.

I would need to access the image field of my eck entity (field_background_image) in this template, because it is necessary for the slideshow logic to display the thumbnail. I tried a lot of different ways.

This is how my template looks like

    <{{ list.type }}{{ list.attributes }}>

      {% for row in rows %}

{{ row.content }}

      {% endfor %}

    </{{ list.type }}>

I can access the title property this way (is there a better way?):

{{ row.content['#slider'].title[0].value }}

I would like to access the field_background_image property of my entity.

row.content['#slider'].field_background_image[0] is a Drupal\image\Plugin\Field\FieldType\ImageItem.
I would need to get the uri value of the field_background_image field so that I can use the ImageStyle on it:

ImageStyle::load($imageStyle)->buildUrl($imageField[0]['#item']->entity->uri->value)

I don't find this in the tree..

Finally this was my solution.

The template:

    <{{ list.type }}{{ list.attributes }}>

      {% for row in rows %}

{{ row.content }}

      {% endfor %}

    </{{ list.type }}>

Twig filter:

class ImageStyleTwig extends \Twig_Extension
  {

/**
 * Generates a list of all Twig filters that this extension defines.
 */
public function getFilters()
{
  return [
    new \Twig_SimpleFilter('imagestyleurl1', array($this, 'imageStyleUrl1')),
    new \Twig_SimpleFilter('imagestyleurl2', array($this, 'imageStyleUrl2')),
  ];
}

/**
 * Gets a unique identifier for this Twig extension.
 */
public function getName()
{
  return 'imagestyle.mymodule_general.twig_extension';
}

/**
 * Get the url of the image by an image style
 */
public static function imageStyleUrl1($imageField, $imageStyle)
{
  return ImageStyle::load($imageStyle)->buildUrl($imageField[0]['#item']->entity->uri->value);
}

public static function imageStyleUrl2($imageField, $imageStyle)
{
  return ImageStyle::load($imageStyle)->buildUrl($imageField->entity->uri->value);
}

}


Why does nothing change when I attempt to restore a backup? I have a drupal 7.43 installation and it has been doing regular backups using the Backup and Restore module.  I wanted to do a restore but I'm blocked at every turn it seems.  I go to Configuration >> System >> Backup and Migrate >> Saved Backups and click on "restore" next to the one I want to restore from.  I get a new page where I choose "Entire Site" to restore to, as that is what I'm backing up, and then click "Restore." That takes me to a white page.  When I reload my site, nothing has changed, so I assume this means failure, although I have no way of knowing what failed or why that I can tell.

So I tried drush:

drush bam-restore archive scheduled drupal.xxxxx.net-2016-03-21T09-44-17.sitearchive.tar.gz

This gave me a mysterious error:

  Restoring will delete some or all of your data and cannot be undone. ALWAYS TEST YOUR BACKUPS ON A NON-PRODUCTION SERVER!
  Are you sure you want to perform the restore? (y/n): y
  PHP Fatal error:  Call to undefined function file_directory_path() in /var/www/drupal.wealthychef.net/public_html/sites/all/modules/backup_migrate/includes/sources.archivesource.inc on line 211
  Drush command terminated abnormally due to an unrecoverable error.
  Error: Call to undefined function file_directory_path() in
      /var/www/drupal.wealthychef.net/public_html/sites/all/modules/backup_migrate/includes/sources.archivesource.inc,
      line 211

Can someone help me understand how to restore my site?

This sounds like a bug of Backup and Migrate module, since file_directory_path() no longer exists in Drupal 7.

So instead of file_directory_path() you should use:

file_stream_wrapper_get_instance_by_scheme(file_default_scheme())->getDirectoryPath()

or:

variable_get('file_public_path', conf_path() . '/files')

So please upgrade your module to development version (but it's not fixed yet at time of writing) or use this patch available at: #2618516 - Fatal error when restoring "Entire Site" which goes like:

--- a/includes/sources.archivesource.inc
+++ b/includes/sources.archivesource.inc
@@ -208,7 +208,7 @@ class backup_migrate_files_destination_archivesource extends backup_migrate_dest

       // Move the files from the temp directory.
       if ($filepath && file_exists($filepath)) {
-        _backup_migrate_move_files($filepath, file_directory_path());
+        _backup_migrate_move_files($filepath, variable_get('file_public_path', conf_path() . '/files') );
       }


How to link Question node to current page? I would like users to be able to ask questions related to current page without going to another page as it works now in the Relevant Answers module. There is a related issue: http://drupal.org/node/1826492

I can create a custom block with form in it, and create new Question node on submit.

How can I link that new node to current page?

Make sure your Question-content type as a field called "node_reference_field" with the EntityReference module.

Once that's done, you just need to make sure the nid of the current node is stored in this field. Since you're using a custom block with a generated form, it won't be that hard.
I suggest you try something like:

$node = node_load ($form_state['nid']);
$form['node_reference_field']['value'] = $node->nid;

I'm not sure about the coding, but with the EntityReference module, you aren't far from a solution.


Is Organic Groups 7.x ready for production? I am about to build a community and planned on using organic groups. I was using drupalmodules.com to download modules, and I noticed that that the reviews for organic groups 7.x are terrible. http://drupalmodules.com/module/organic-groups. Is anyone using organic groups 7.x, and what are your experiences with it?

I've used OG6 in the past and am starting to use OG7 now for a website.  I'd say in general, both with the 6 and 7 versions that the learning curve in figuring out how to use Organic Groups can be steep for a newbie, since it's a complicated module with a lot of features, and a lot of related, supporting modules like OG menu, OG Extras, etc.

Give yourself time to play with all of those.  Don't expect to setup your perfect site in a day if you've never used it before.  It may be that the 6 folks who reviewed the module on the site you referenced had such expectations.  Also, those are 6 reviews out of over 24,000 sites currently using OG.  :-)

My recommendation: do your own testing and make up your own mind before believing a review 100%.  Some of those reviews are probably quite valid, but OG is a useful module and may be able to do everything you want for your site.


How to view what query was ran when a form is submitted? Im using drupal 7, I'm trying to find out where abouts in the database certain values are submitted.

Is it possible to view what sql query was ran after a form was submitted?

Thanks for any help

Install the devel module https://drupal.org/project/devel, and choose the option display query log. The queries will be shown on the bottom of each page.

In admin/config/development/devel:

Check 'display query log'

Sometimes, I prefer just switching on logging in my.cnf for MySQL, because it shows the complete query as executed. If you do that, do not forget to switch logging off again when you are done. Otherwise, you'll fill up your disk/partition.

In the [mysqld]section, add:

log=/var/log/mysqld

Restart mysqld.


Alternative to Galleria module? I'm trying to use the http://drupal.org/project/galleria module in conjunction with its fullscreen theme, but I get the error I pasted below, I tried many fixes but not working.

Is there another module to show a gallery similar to this one: http://galleria.io/themes/fullscreen/

Could not extract width/height from image: http://localhost/mysite.com/sites/default/files/styles/thumbnail/public/images-fullscreen/slide-1.jpg. Traced measures: width:0px, height: 0px.

When this happened to one of my sites, I corrected it by upgrading to the latest version of the galleria library. There also might be an issue with your css. Several hints to track the problem down can be found here.


Disallow HTML in comments I'd like to disallow all HTML and only allow plain text in comments across the site for all users, authenticated or not, but I still want to use other HTML filters for other content types. How can I achieve that in Drupal 8?

I've created a custom text format called "No HTML" and set it as the default format for comment bodies at admin/structure/comment/manage/comment/fields/comment.comment.comment_body. But instead of disallowing all HTML, it gives the option to change the text format to any other format available to the user.

How can I get comments to only use my "No HTML" text format for all users without disabling the other text formats for other content types?

The Allowed Formats projects allows you to control the available text formats per field, so you can limit it to plain text. Better Formats is a similar module.

You could do the same with a form alter and set #allowed_formats on the form element. Or you could remove the default comment body field and replace it with a plain text field. Although there might be some code relying on the name/existence of the default body field.


Add js depend jQuery in a specific content type I need to add js file with jQuery syntax on a specific content type.

I tried on twig template but I get jQuery or $ not a function,

If I have js native syntax only, it is working great but not with jQuery syntax.

I think that this is not the right way to add a js depend jQuery file to a specific page.

I an wondering, What is the right way to do it?

Thanks a lot.

Checkout https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module especially section Attaching a library in a twig template

See also lib/Drupal/Core/Render/theme.api.php where the library is like $build['#attached']['library'][] = 'core/jquery';

{{ attach_library('core/jquery') }}


Is it possible to bypass the admin approval step based on a particular condition? Potential scenario:

Allow users with a particular email address or token to skip the admin approval step and have their account approved ie: it sends the password/login link out immediately and they don't receive the awaiting approval email.

All other users with other email addresses need to be approved by an admin.

One potential solution I've thought of is to act on hook_user_insert to unblock and send the password email the user hook_mail_alter to disable the initial awaiting approval email.

I just feel this option is a bit hacky and I'm wondering if there is a better way of doing things.

Take a look at User Restrictions module for Drupal 7 and Access Rules for Drupal 6.

UPDATE

For registering users based on unique code check out regcode module


Ajax callback returns value but wrapper isn't filled I'm stuck because whatever I do my wrapper is never filled with my callback, any idea ?

  $form['show_liste_produits'] = array(
   '#type' => 'button',
   //'#attributes' => array('onclick' => 'return (false);'),
   '#value' => t('Lister les produits'),
   '#name'  => 'awesome-button',
   '#ajax' => array(
      'callback' => 'stockerAll',
      'wrapper' => 'listeProduits',
      'method'   => 'replace',
      'effect'   => 'fade',
    ),
  );

  $form['listeProduits'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => array('listeProduits'),
    ),
  );

function stockerAll($form, $form_state){
 return 'test';
}

Thank you in advance !

EDIT:
In fact in the network tab I get this, maybe the selector isn't working ?
Moreover, my empty container isn't displayed after page load actually, maybe is it the source of the problem ?

Edit your code into the code below:

 $form['show_liste_produits'] = array(
     '#type' => 'submit',
     '#value' => t('Lister les produits'),
     '#ajax' => array(
         'callback' => 'stockerAll',
         'wrapper' => 'listeProduits',
     ),
);

$form['listeProduits'] = array(
    '#type' => 'container',
    '#attributes' => array('id'=> 'listeProduits'),
);

If it doesnt work,make sure first if stockerAll is called. Insert watchdog('test','test'); in the stockerAll function . After doing so, run the program, check your drupal database, particularly the watchdog table and check whether 'test' is in the latest log.

function stockerAll($form, $form_state){
    watchdog('test','test');
    return 'test';
}

If stockerAll is called, clear cache of the browser to make sure the updated code is the one executing. Else, there's something wrong with the way you invoke your function.


How to parse a URL's content into a Drupal node I'd like to create a node type in which I'd have an URL field, title and some description. Once I create a new node using this content type, Drupal would parse the contents of the URL I've added in the URL field. It'd work almost like one of these read it later services.

Is this possible, if its how? I've been looking into feeds, but its not exactly what I'm looking for (as it deals with rss/atom rather than url).

Background: Basically I'm creating a personal wiki using Drupal and wanted the ability to parse content directly to a node type. This way I can categorize the way I want as well as being able to create views, aggregate different content, etc. This is for a personal project and the site wouldn't be public.

Yes, it is possible using hook_node_insert or hook_node_presave. You will just need to implement it like:

function hook_node_insert($node) {
  if ($node->type == 'CONTENT_TYPE_MACHINE_NAME') {
    // get the URL content here
  }
}

You can do it using the hook_node_presave too. The only difference is that it is called before even the node is saved into the database.


Webform dynamic select options based upon another element's state Say there are two select elements with dynamic options (via an options alter hook, sourced from an external resource): A and B.  There is also a datasource that provides a relationship that determines the options in B that should shown when a particular selection in A is chosen.

The source data for each element in addition to the relationship data source is not able to be predicted or controlled by Drupal.

For example:

A Options at a particular instant

| name | code |
| Group 1 | 1 |
| Group 2 | 2 |
| Group 3 | 3 |

B options at a particular instant

| name | code |
| Thing 1 |  1 |
| Thing 2 | 2 |
| Thing 3 | 3 |

The relationships at any given time.

| group | thing |
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 2 |
| 3 | 3 |

So if group 1 is selected for A, then things 1, 2, and 3 should be options for B

If group 2 is selected for A, then things 1 and 2 should be options for B

If group 3 is selected, then only thing 3 should be an option for 3.

We are currently implementing this requirement through the core FAPI and ajax callbacks, but would like to covert it to use Webforms.

What would be the recommended approach to take in order to solve this with Webforms?  Please bear in mind that modifying the source data is not an option, as it is not able to be predicted nor controlled by our unit and adjustments must be reflected in realtime.

No one has contributed back a solution for Drupal 8. I think the best approach is going to be to organize cascading select menus using a CSV and implementing something like Cognito form's cascading dropdowns menus.

Another supported approach is the Webform Simple Hierarchical Select module but it requires a taxonomy.


Multiblock Module D7 $edit Using the multiblock module, I haven't been able to retrieve the $edit variable my custom hook_block_configure() or hook_block_view(). According to the readme:

add an optional $edit
argument to your hook_block_view and hook_block_configure functions.

I have, like so:

function donation_form_block_configure($delta = '', $edit = array()) { ... }

But alas, $edit is all ways null. I'm simply looking for the multiblock id during the configuration and viewing.

the module aint workin.

hacked it to fix.

$block = module_invoke($block_info->module, 'block_'. $op, $block_info->orig_delta, $edit);


How to change fields permission using some action in the Rules module? I installed the Field Permissions module to grant access of the individual fields to the roles.

I need to change the permission of some fields when an event occurs. How do I can add the field edit permission to the Action component of the Rules module?

To my knowledge, there is no way you can "add the field edit permission to the Action component of the Rules module" (as in your question), which is somehow confirmed in the Post installation Support forum via the issue about "Field Edit Permissions Based on Rule?" also.
However, in one of the comments of that link, there is an interesting work around that might work in your case also:

Create a user role that has editing permissions for the field, then assign that user role to a user with Rules when the conditions you require are met.
You'd then possibly need to remove that role after updating the content depending on your workflow.

PS: I'm assuming this question is about D7.


Create different URL alias based on CCK field So I have a typical blog entry content type and I've added a CCK checkbox for some extra functionality. I'm using the pathauto module to automatically set the URL alias for the blog entry content type.

What I would like to do is alter the URL alias created depending on the value of the CCK checkbox. If the box is checked, I'd like to change the URL alias. If not, let pathauto do it.

Possible? Can this be done in the template.php file of my theme?

I'm assuming you're well-versed in the settings that Pathauto gives you (like it's own "automated alias" checkbox, and the settings that change what happens when a node is updated).  I'm assuming those settings don't meet your needs.

This should be possible, but not in the theme layer.  You'll need to write a module, probably a relatively small one.  You'll need to implement hook_nodeapi in D6 or one of the hook_node* family in D7, and maybe hook_pathauto, to make sure the right thing happens.

Drupal 6

hook_pathauto()
hook_nodeapi()

Drupal 7

hook_pathauto()
hook_node_presave()