Programmatically pass parameters to Apache Solr integrated with Search API

After digging deep into the search_api_solr module I found a spot where it's applying options to the solr parameters inside the search method of the SearchApiSolrBackend class here

  foreach ($options as $option => $value) {
    if (strpos($option, 'solr_param_') === 0) {
      $solarium_query->addParam(substr($option, 11), $value);
    }
  }

I noticed that it only applies the parameter if it's preceded by 'solr_param_' and if it is it strips out the 'solr_param_' before applying it to the actual parameter.
All I had to do was add 'solr_param_' to the beginning of my option like so.

$query->setOption('solr_param_spellcheck','true');

Once I did that, getAllExtraData() returned what I needed.

  array(1) { ["search_api_solr_response"]=> array(2) { ["response"]=>
  array(4) { ["numFound"]=> int(0) ["start"]=> int(0) ["maxScore"]=>
  float(0) ["docs"]=> array(0) { } } ["spellcheck"]=> array(1) {
  ["suggestions"]=> array(16) { [0]=> string(5) "goood" [1]=> array(4) {
  ["numFound"]=> int(1) ["startOffset"]=> int(11) ["endOffset"]=>
  int(16) ["suggestion"]=> array(1) { [0]=> string(4) "good" } } [2]=>
  string(5) "goood" [3]=> array(4) { ["numFound"]=> int(1)
  ["startOffset"]=> int(42) ["endOffset"]=> int(47) ["suggestion"]=>
  array(1) { [0]=> string(4) "good" } } [4]=> string(5) "goood" [5]=>
  array(4) { ["numFound"]=> int(1) ["startOffset"]=> int(60)
  ["endOffset"]=> int(65) ["suggestion"]=> array(1) { [0]=> string(4)
  "good" } } [6]=> string(5) "goood" [7]=> array(4) { ["numFound"]=>
  int(1) ["startOffset"]=> int(93) ["endOffset"]=> int(98)
  ["suggestion"]=> array(1) { [0]=> string(4) "good" } } [8]=> string(5)
  "goood" [9]=> array(4) { ["numFound"]=> int(1) ["startOffset"]=>
  int(111) ["endOffset"]=> int(116) ["suggestion"]=> array(1) { [0]=>
  string(4) "good" } } [10]=> string(5) "goood" [11]=> array(4) {
  ["numFound"]=> int(1) ["startOffset"]=> int(129) ["endOffset"]=>
  int(134) ["suggestion"]=> array(1) { [0]=> string(4) "good" } } [12]=>
  string(5) "goood" [13]=> array(4) { ["numFound"]=> int(1)
  ["startOffset"]=> int(154) ["endOffset"]=> int(159) ["suggestion"]=>
  array(1) { [0]=> string(4) "good" } } [14]=> string(5) "goood" [15]=>
  array(4) { ["numFound"]=> int(1) ["startOffset"]=> int(182)
  ["endOffset"]=> int(187) ["suggestion"]=> array(1) { [0]=> string(4)
  "good" } } } } } }

Not entirely sure why I have so many duplicate results here so if anyone has input on that that would be helpful. Otherwise I do have the data I need.


Architecture for login in. Accessing Drupal serivces from a phonegap mobile app

You are right to be using services.

I guess you've got this bit but i'll write it all the same: You need to obtain an anonymous user session via services and then use those details in the user login call.

Re the not being able to access across domains, its not jquery but actually the browser stopping this on your computer. But when you are using the webview component in your app it won't stop it.

Sounds like you are on the right track, just crack as your main problem shouldnt occur :)

Edit: On reflection maybe that isnt totally helpfull

You could consider using Sencha Touch for this purpose. http://www.sencha.com/products/touch/

It kind of pitches itself as something you could use instead of native code, but ibuilt some pretty chunky ipad stuff on it and it begun to chug. Don't expect all transitions to be as smooth etc.

However, it does give you some great data/store tools

Sencha 2 is just about out
check the documentation for the rest proxy
http://docs.sencha.com/touch/2-0/#!/api/Ext.data.RestProxy

this would make handling lists and viewing content very easy

a good example from sencha 1.1 is http://dev.sencha.com/deploy/touch/examples/oreilly/ as it shows how you might extend a 'panel' to be a node view equivalent for the webapp. The syntax will be different in 2.0 but its a good way of thinking

I'm beginning to ramble now. Take a look and i'll dig out some code snippets if you choose it


List all bundle types for entity field query?

If as per your example code you are just concerned with nodes then the bundles are just your node types.

If you want to get a list of node types you can use:

node_type_get_types()
or
node_type_get_names()

You can get the bundles from the array keys of the arrays returned from those functions.


Display selected fields from referenced node rather than just referenced node title

Using display suite, create a new display mode for Content Type B, and show only the Job and Image fields.

Modify display for Content Type A to use the new display mode.


You might need to do a change in my.ini file which is configuration file for your mysql server.

Change

open the my.ini file.
you might not have this (max_allowed_packet) line already there.
So you need to add this line at some point in this file.

max_allowed_packet=24M
Save the file
Restart mysql server.

Reference:
https://drupal.org/node/163145


This question is obviously very old, but I spent the last few hours figuring out the same issue and figured this might help someone else who is Googling this problem.

The problem for me was this:

In Modules, "Location Entity" should NOT be enabled.  "Location CCK" (in the Fields section) should be.

Then, when modifying the Content Types, do NOT rely on the "Location" field that is there by default (machine name = locations).  You have to add your own, additional Location field (field type = Location; widget = Location Field).

This solved the problem for me.  I created a View (Page) for a Specific Content Type with Format = GMap and Data Source = Location.module.

Then it finally worked!  Hope this helps.


Admin UI doesn't see the correct PHP version

You have to configure the web server to use the PHP version you want.
For example:
sudo a2dismod php7.2
sudo a2enmod php7.4

sudo service apache2 restart


Is there a module to hide URL path settings by content type?

I don't believe there is anything out there at the moment (perhaps my search wasn't extensive enough either), but you can hide the URL path settings fieldset yourself easily with one line of code:

<?php $form['path']['#access'] = FALSE; ?>


The autonumber isn't related to the number of records in the table, but rather the AUTO_INCREMENT value of the table's primary key column.

If you have a completely new table, and add 100 rows, the next ID will be 101. If you just remove all the rows in that table the next ID will still be 101, unless you TRUNCATE the table, or reset the AUTO_INCREMENT column.

For an easy way to test, fire up your preferred DB client, and insert a record into the database. If you get 1 as the next insert ID, there's a bug with your Drupal installation/DB engine. If not, it's just what's mentioned above.


How to access a node's menu link title in Views?

Out of the box, there isn't a way.
The only thing that may possibly help you is the
Menu Node Views

The Menu Node Views module provides Views integration for nodes
assigned to the menu system. This module is in alpha development.

Else, a workaround is the only way.


For my circumstance i have adopted to use the block_alter hook to define the new suggestion for the template. Since homepage only contains the unique views template and the others wouldn't.

function THEME_theme_suggestions_block_alter(&$suggestions, $variables) {
  $path_check = \Drupal::service('path.matcher');

  if (in_array("block__views", $suggestions) && $path_check->isFrontPage() == FALSE ) {
    $suggestions[] = 'block__views__blah__custom';
  }

}


In a Rule, how can I prevent executing subsequent actions if the first action fails?

To provide conditional logic, you need the Rules Conditional module.

There's an open issue to document this further, and there's another meta issue which looks at integrating the conditional logic into the Rules module itself.

  This module provides Rules plugins for conditionally altering execution flow directly inside a group of actions. Provided plugins include:

Conditional
    If/(Else) If
    Else
Switch
    Case
    Default case
While


check_url basically checks for dangerous protocols in the url and escapes any special characters as HTML entities for output. Normally it's not needed unless outputting a raw external / absolute URL. For relative URLs, Drupal adds the base url automatically.

better to use first(a) option.


How can I save/load my Entity from a different database in Drupal 8?

At least if the "external" database is on the same server, there is an easy solution. The base_table of an entity can refer to a different database using . as a separator.

Just adapt the EntityType annotation in the comment above your Entity class. The following example uses the table myentity_table from the my_database database for this Entity's data:

@ContentEntityType(
 *   id = "myentity",
 *   base_table = "my_database.myentity_table",
 *   [...]
 * )


Correct way to alter markup as html within theme_preprocess_container?

You can't modify a markup object, but you can use the create() method on a new markup object to replace the old one.

$variables['children'] = \Drupal\Core\Render\Markup::create('
Manually set
');

By the way, you are modifying a twig debug message which won't be there in a production environment.


How to use entity_metadata_wrapper in hook_boot

Here's a solution.

Add this to the top of your hook_boot() function:

function hook_boot() {
  global $user, $base_path;
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
...
}

drupal_bootstrap keeps track of what level it has been called so this trick effectively pushes hook_boot to being later in the boot process.


Drupal 8, make comment subject a required field

Here is how, you will need to create a custom module , and add this ... to yourmodule.module file ...

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
  if ($form_id === 'comment_comment_form') {

    $form['subject']['widget'][0]['value']['#required'] = TRUE;

  }
}


How to access files from a custom block without code

I might be misunderstanding, but in a custom block you should be able to use standard img tags to display an image you've uploaded to your site.


How to NOT share content between multi sites?

I run several multi-sites and nothing is being shared between them except core and the modules and themes below sites/all/.  If more than this is shared (your question specifies "everything"), then you've not set up your multi-site right.

I've written a tutorial about setting up a multi-site here. I hope the instructions are clear enough to follow.

Setting up a multi-site where the primary site is in a sub-directory is not different from setting up any other multi-site, provided your DocumentRoot points to the right place.

From your latest comment, I finally understand that you're trying to do the same thing as the person at http://drupal.org/node/1882182.

In that case, you need to understand that this person is not using the subdirectory method.  He is using the  subdomain method.  You can't mix these methods, you must use one or the other.

And if you're using the subdomain method, you must not use a symbolic link (as you indicate in your question that you're using). Instead, you must configure DNS and your vhost to point to the directory that is your DocumentRoot for Drupal (in your case, it sounds as this should be  /var/www/html/sub1/.  This will take care of the fact that your Drupal core is installed in a sub-directory with a plain HTML-site in the web-root.  You must also create the following sub-directory in the Drupal sites directory: sub2.mysite.com.  Copy the default.settings.php into sub2.mysite.com. Then make sub2.mysite.com your working directory and immediately copy default.settings.php to settings.php.  Make sure that both are writeable by the web server user.  The sub2.mysite.com subdirectory will hold your settings.phpfor sub2.mysite.com. Then go to your ISPs control panel and configure DNS for sub2.mysite.com to resolve to your main site's IP-adress. Finally create the following ServerAlias: ServerAlias sub2.mysite.com in your main site's vhost configuration file.

You should now be able to point your web-browser to http://sub2.mysite.com/ and be greeted with default Drupal installaton screen.  You can then proceed and install the multi-site instance you've created.  If you get anything else than the  default Drupal installaton screen at this point, something has gone wrong and you need to find out what this is.

(All this assumes you're using Apache2 as your web-server.  If you're using something else, you need to figure out the equivalent of DoccumentRoot and ServerAlias on your brand of web-server.)


Log out URL returns 503, redirects to path with double slash

You should use URL() to create logout url. For example,

url('user/logout')


The short answer is: Yes, both your examples are OK to use as a business model with Drupal.  There is also no advertising requirement.

For a longer and more comprehensive answer, including the fine print, you'll find it all answered authoritatively in the Drupal licensing faq.  I understand that you've read that, but didn't find it clear enough.  I shall try to expand on it somewhat.

The most important bit is this:

  Drupal and all contributed files hosted on Drupal.org are licensed under the GNU General Public License, version 2 [GPLv2] or later. That means you are free to download, reuse, modify, and distribute any files hosted in Drupal.org's Git repositories under the terms of either the GPL version 2 or version 3, and to run Drupal in combination with any code with any license that is compatible with either versions 2 or 3, such as the Affero General Public License (AGPL) version 3.

GPLv2 basically says that you've free to use the licenced material in any way you like, including commercial use (i.e. where you make money). Unlike some other free software licences (e.g. the BSD license), there is no "advertising" clause, so you don't have to put up any "Powered by Drupal" signs.

However, there is one important legal restriction tied in with GPLv2 you need to be aware of: GPLv2 or later is a so-called "Copyleft" license.

"Copyleft", in brief, means that if you make any materials (i.e. the Drupal core and any custom development you've done to make it a fully functional website) available to a client, the materials must be made available to the client in source form, and under the same [Copyleft] terms (i.e. GPLv2 or later).

However, the requirement that any material you give your client has to be licensed under the same terms may in some situations be a problem.  This means that your client is free to use the licenced material in any way your client like, including modifying and reselling it (also reselling it without giving you a cut of the proceeds).

I should add that usually, this is not a problem.  Your client is probably not a Drupal developer (that's why they hired you), so they if they resold it, they would not have the skills to maintain it.  But it is a real legal implication of GPLv2 or later you should be aware of.

Also, note at GPLv2 or later doesn't say you have to give you client access to the material.  If you include hosting in the package you sell. And in particular, if you sell it as SaaS (your example 2), then no material changes hands and your client don't have access to anything they can resell.

Providing a website as SaaS without giving access to the material is permitted under GPLv2 or later.

Note that the Gnu Affero General Public License version 3 (AGPLv3) requires SaaS providers to give clients access to, and permission to resell, any material the service is based upon.

(AGPLv3 in not used by the Drupal core, but may be used by some contributed modules offered by third parties as it is upstream compatible with GPLv2 or later.  However Drupal.org does not permit contributed modules that is under APGLv3 only to be hosted on Drupal.org)


Use Drupal Pathauto

After enabling it go to admin/config/search/path/patterns and under Default path pattern (applies to all content types with blank patterns below) fieldset you'll get what you want.

Add your desired format there:

[site:name]/[node:title]

Once the configuration is done, click on admin/config/search/path/update_bulk and select Content paths from the given options.


Contact attached to every node of a particular type

Try installing Form Block module which give you possibility to expose a form as a block. And you can configure appearance of that block on every node of a particular content type.

  To enable adding of a form to a node, select the option "Enable data
  entry from a block" in the admin configuration page for a given
  content type. Visit the block administration page and enable/configure
  the block for the form.


hook_pathauto_alias_alter() on bulk update

Issue can be with the setting for Url aliases, when  you run the bulk update.
You need to keep it on the " Create a new alias. Delete the old alias. ". SO it will run update your old aliases. Please check if it works for you.


How to insert an RTMP url from an adobe streaming server (rtmp://example.com/myvideo.flv) in drupal 7?

You can use JWPLAYER , and here is an example for how you setup the streaming

1- in the page header you include the jwplayer js library
2- follow the embedding guide "http://www.longtailvideo.com/support/jw-player/28839/embedding-the-player"
3- use the RTMP changes as it's documented here http://www.longtailvideo.com/support/jw-player/28854/using-rtmp-streaming/

So your simple code will look like this;

 jwplayer("myVideo").setup({
     file: "rtmp://example.com/application/mp4:myVideo.mp4",
     image: "/assets/myVideo.jpg",
     height: 360,
     width: 640
    });


How to alter text filters conditionally based on content type?

You could go with the following code inside your filter's callback function:

if(arg(0) == 'node' && arg(1) > 0){
  $result = db_select('node', 'n')
  ->fields('n', array('type'))
  ->condition('nid', arg(1),'=')
  ->execute()
  ->fetchAssoc();
  dsm($result['type']);
}

Good luck!


Can forms be added to a page of quick tabs?

Should be possible via custom code. You can read up on how to build quicktabs programmatically here:

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

For the node editing pages you will want to use the example for Custom contents (HTML or renderable Array) on that page, where you get the form using the core function drupal_get_form('node_BUNDLE_form') and add it as the "renderable array".

For the webforms you could try to work with the Callback tab type, or again by loading the webform and building the render array.

For the static content i'd recommend to use nodes as this is always better than hardcoding things, so use the Node tabs type.


Do migrate module migrations continue in background if terminal session ends?

I believe not. That is why Migrate supports a reset option migrations if they are orphaned or otherwise fail. Typically you run migrations as a shell user (yourself) on the system. Unless you're using something else to keep your processes alive -- they die when the terminal they're connected to die.


Rules UI, accessing a Variable created in another rule

The variable you created in one rule will not automatically be available to other rules.

However, if there is a rule that creates a variable that you may need to reuse frequently, one thing you can do is create it as a rules component.  Then you can reuse that setup multiple times.  It can also keep your rules leaner and cleaner!


Check if the current user has permission to edit current node

I've found it and working great.

  $node = \Drupal\node\Entity\Node::load(NID);
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $check = $node->access('update', $user);


Webform POST handler, add API/header creds?

Just adding an answer in addition to @Ryan Hartman's comment. Extend the RemotePostWebformHandler class and its ::buildConfigurationForm() method:
/**
 * Custom Webform submission remote post handler.
 *
 * @WebformHandler(
 *   id = "custom_remote_post",
 *   ...
 * )
 */
class CustomRemotePostWebformHandler extends RemotePostWebformHandler {

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    $form['api_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API Key'),
      '#description' => $this->t('The API key for basic auth.'),
      '#default_value' => $this->configuration['api_key'] ?? NULL,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    $this->configuration['api_key'] = $form_state->getValue('api_key') ?: NULL;
  }

  ...

Alternatively implement the form element provided by the Key module so you can securely store sensitive secret keys.


Found the solution after extensive search and trial & error:

/**
 * Define the new view modes
 *
 * implements hook_entity_info_alter()
 * @param $entity_info
 */
function my_module_entity_info_alter(&$entity_info) {

    $entity_info['node']['view modes']['grid'] = array(
        'label' => t('Grid'),
        'custom settings' => TRUE,
    );

    $entity_info['node']['view modes']['list'] = array(
        'label' => t('List'),
        'custom settings' => TRUE,
    );
}

/**
 * Tell Drupal to also look for template files in the modules folder
 *
 * implements hook_theme_registry_alter
 *
 * @param $theme_registry
 */
function my_module_theme_registry_alter(&$theme_registry) {

    $path  = drupal_get_path('module', 'my_module');
    $theme_registry += drupal_find_theme_templates($theme_registry, '.tpl.php', $path);
}

/*
 * Implements template_preprocess_node().
 */
function my_module_preprocess_node(&$variables){

    // Add the theme hook suggestion to include view mode
    $variables['theme_hook_suggestions'][] = 'node__'.$variables['type'].'__'.$variables['view_mode'];

  }
}


Entity form presents all taxonomy terms instead of vocabulary

$fields['voc_type'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Voc Type'))
    ->setDescription(t('Voc tag'))
    ->setSetting('target_type', 'taxonomy_term')
    ->setDisplayOptions('form', [
        'type'    => 'select',
        'options' => $array,
        'weight'  => -6,
    ])
    ->setDisplayConfigurable('form', true)

    // I think you're missing this:
    ->setSetting('handler', 'default:taxonomy_term')
    ->setSetting('handler_settings', [
      'target_bundles' => [
        'my_vocabulary' => 'my_vocabulary'
      ]
    ]);

I don't think you need to manually gather the options and set them like that. The target_bundles setting should take care of that.


Correct way to import an RSS feed and display it in a view?

The proper way to import an RSS feed and have its data displayed in a view is by creating nodes from the feed data. This is what the Feeds module accomplishes.

You will need to define two content types: one to be used by the feed importer (ex. "Facebook Feed Importer") and one for the feed items themselves (ex. "Facebook Feed Item"). In the feeds importer:

Under Basic settings, attach the feed to the Facebook Feed Importer content type.
Set the node processor bundle to Facebook Feed Item.
Map the fields.

See this tutorial for more details in setting up the importer. If you have troubles using the Feeds: Facebook Parser, give the Feeds JSONPath Parser a try.

Once you have everything configured correctly, make a new Facebook Feed Importer node, enter in the feed URL, and save the node. View this node and click import. The RSS data should be imported as Facebook Feed Item nodes. If you get errors, or 0 nodes created, you probably have an issue with your mappings or importer configuration.

By importing the feed data into your website as nodes you have more flexibility in how you can display this information to the user. Instead of having one large string of data for a feed item, you have a node containing fields for each part of the feed item which can then be customized in your views or anywhere else on your site however is required.


If you are getting alert from the JS file than it means your JS file is loading properly, and the problem of hide seems to be causing because hide to be called in the document.ready as following:

// Jquery wrapper for drupal to avoid conflicts between libraries.
(function ($) {
  // Jquery onload function.
  $(document).ready(function() {
    $(".image-overlay").hide();
  });
})(jQuery);


How can I make a fieldgroup visible only to admin users?

You are probably using 1.x version of field_group module (which is the recommended version).

This problem has been solved (for most cases) in this issue. You could try the 2.x-dev version or use a simple JQuery script to remove the empty elements.


Views relationship outputting duplicate nodes?

Maybe You can try to use the Query Parameter and check the "Distinct" option to have distinct result :


View contextual filter not working inside Panels

I had the same problem and figured it out. Enter /your/path/{parameter} for your page path and the Page Context link will change to a Page parameter link. You can use any word for {parameter}, it is just a variable name. You specify the type of the parameter under Page parameter. It would have saved everyone an enormous amount of time, if this was included in the instructions underneath the path field.


How to display mini panes in specific pages of my site

There are many ways this can be done.

Blocks are pieces of content which can be placed in specific areas of the page called regions. You can choose where to put these blocks in the block section of the admin

The standard block admin will allow you to put conditions on who can see the blocks and what paths they are displayed or hidden on. However this can get a little difficult to manage with many blocks and conditions.

Many people use the context module for such situations. This allows you to override the standard block admin and define a context under certain conditions (path being one of them) and define blocks which are displayed under these conditions.


how to just print the value of author in node template

For most cases How do I get the raw field value in a twig template? will do. But since here according to node.html.twig

  author_name: Themed author name field.

I believe you can get the unthemed author name by using {{ node.getOwner.getDisplayName }}


How to create a field which contains the entity created date

You could use the Computed Field module to display the date on your page. Create a field and set the php code to display the date in readable format.

Call your field something like 'Date created' and enter code like the following under Computed Code (PHP):

$entity_field[0]['value'] =date("Y/m/d",$entity->created);

Do not store the value in the database. You do not need to derive the value for views as the created date is available to views directly.

The last modified date is available as well as $entity->changed.

As an alternative, you might have a look at the Node Display Fields module, which has several widgets to display the type of information you are looking for.


href link assigning callback action - ajax

For anyone needing help on this, as the information out there seems to be either related to forms only or seems rather over convoluted... ajax callback can be added to normal links, by defining the link as outlined above (in the question) - but adding the '/nojs/' prefix to the Url defining portion of the code and adding the class 'use-ajax' in the attributes section of the code e.g. :

// Define the link.
$url = Url::fromUserInput('/nojs/ajax_call_url');
$the_link = Link::fromTextAndUrl('Submit Application',$url);
$the_link = $the_link->toRenderable();

$the_link['#attributes'] = [
  'class'=>'use-ajax',
];

// Add the link to your render array.
$output['link1'] = array(
    "the_link"=>$the_link,
);

Now in the 'name of your module'.routing.yml file add the route to where your ajax callback function is... as '/nojs/' is used (as it has to be by the looks of things) it means your path must be defined with the prefix '/ajax/' followed by the path of your choice e.g.:

path: '/ajax/call_ajax_url'

the _controller attribute in the routing.yml file, will be defined to point to where your ajax callback command is defined... e.g. will point to whatever object and function holds the

    $message="hello";
    $response=new AjaxResponse();
    $response->addCommand( new HtmlCommand("#current-msg",$message);
    return $response;

Hope this helps someone - as it took a while for me to find the info necessary to resolve this issue.


Content type with multiple users - create a view of all users that relate to content of that type

I'm not entirely positive this is the type of relationship you want for this data.  If you use a node_reference field on the user rather than a user_reference on the node it would be pretty straightforward to create a view of Users who party.

Query all users and then add a Relationship to the field_party node reference.  Require the relationship with a Delta of 1.

This type of reference would seem to make more sense for your use case as well, since this would enable any user to administer their own party affiliations rather than the party manage the list (but then this is an analogy and I don't know the particulars).

Either way you are hitting up against the boundaries of what is possible using references.  I'd encourage you to take a look at the Relation Module which is designed to handle these kinds of bi-directional relationships, e.g. Display the members of the Party, Display the parties an individual is a member.


How to bulk create an extra node for each user

Shouldn't be too difficult if you're ok with writing a custom module, I can't think of any other way to iterate through your user base.

Create the node type for storing your statistics with:

Title (compulsory, unfortunately.  consider using Automatic Nodetitles)
Entity Reference field that references a user
Date field for storing the date
Other field/fields to store your statistics

Write a custom module that does the following things:

Iterate through all of your users
Check to see if the user is active
Queries the database to see how many nodes the user has.
Creates a new node containing the information you wish to store.

See how you go and of course ask more, detailed questions about each step showing what you have tried if you really can't work it out through the documentation and existing questions/answers available here and elsewhere.


How to remove the "No front page content has been created yet." message from the front page?

Who would have guessed? There's a module for that. Check out the Empty Front Page module. With only 10 lines of code, it must be one of the simplest modules out there.


Hierarchical select ajax conflict in custom bootstrap theme

It was Colorbox which was conflicting with HS. I disabled the colorbox module and it worked perfectly. I don't know why this happens, but this should be raised as an issue since both are contrib modules.


I finally found how to handle it : there is a hook_file_download where i can add and set header for the file :

function mymodule_file_download($uri){

// Getting file info
  $info = image_get_info($uri);

  // For images files
  if(isset($info['mime_type']) && strpos($info['mime_type'], 'image/') === 0){
    // cache max-age : 1 day
    // expire-date : now + 86400 s
    // etag using a hash of the file size variable
    return array('Cache-Control' => 'max-age=86400, private',
                 'Expires' => gmdate('D, d M Y H:i:s', time() + 86400) .' GMT',
                 'Last-Modified' => gmdate('D, d M Y H:i:s', time() - 86400) .' GMT',
                 'ETag' => strtr(md5($info['file_size']), 0, 10));
  }
}


Exception\UnknownExtensionException: The module does not exist or is not installed

I have agree with @4k4 you can fix this with database

If your module have been deleted from the system use this query

delete from `key_value` where collection = 'system.schema' and name = '$extension_name';

for example:

delete from `key_value` where collection = 'system.schema' and name = 'config_tools';
delete from `key_value` where collection = 'system.schema' and name = 'git_config';


Drupal7: How to add the alt and title attribute to an image by code

Since you are rendering a field , you can use below code

<?php
$image = field_get_items('node', $node, 'field_history_image');
$output = field_view_value('node', $node, 'field_history_image', $image[0]);
print render($output);
?>

OR

$view = field_view_field('node', $node, 'field_history_image');
print render($view);


I haven't done it to make inline CSS, but you could try creating a new region in your .info, and using drupal_set_content to add structured content.  You can then parse / format it in a template_preprocess_page, and then print it in your page.tpl.php.  I've had to resort to similar tricks in the past to work around this.

I suspect your best place to call drupal_set_content from is a hook_nodeapi(&$node, "view")


I think your are printing wrong the array $items. It should be something like

print $items['#file']->filename;

The same is happening with the image issue.


Computed code db query issue -- working in PHPmyadmin but not field

What you wrote is not PHP code, which is what a computed field is expecting.
I would rather use the following code.

$entity_field[0]['value'] = db_query("SELECT entity_id FROM {field_data_field_review_venue_reference} vr WHERE vr.field_review_venue_reference_target_id = :id", array(':id' => $entity->nid))
  ->fetchField();


How to send an email on every 10 contents that are waiting for admin approval?

I have get all the users (uid) of particular role from the users_role table.

i.e :

$query = 'SELECT DISTINCT(ur.uid) FROM {users_roles} AS ur WHERE ur.rid IN (:rids)';
$result = db_query($query, array(':rids' => array(3,8)));

Next step, I have count nids from workbench_moderation_node_history table.

i.e  I have made one function like get_train_users() in which i have returned the above $result array.

$trainusers = get_train_users();
foreach ($trainusers as $key => $value) {
   $tresult [] = db_query ('SELECT COUNT(nid) AS con,uid FROM  {workbench_moderation_node_history} WHERE uid = :uid AND state = :state' ,array(':uid' => $value, ':state' => $state))->fetchAll();
}

Now, In last step, I am counting the count of con, Like if it is greater then 10, then i am sending the mail when cron runs.

That's it.


How to schedule a Rules component at the end of the month?

Introducing last day of 23:59 works for me (last day of is the last day of the current month, and 23:59 just before the day ends). You can see the full reference of DateTime relative formats here: http://php.net/manual/en/datetime.formats.relative.php

In general, you can pass anything recognised by strtotime() as the scheduling date.


Creating a directory for a vocabulary term?

I would bet that you have the module Pathauto enabled. It allows you to create path aliases for mach of your site stuff like nodes and taxonomies. Go to Configuration > Search and metadata > URL aliases > Patterns. That's where you enter the alias patterns for content, taxonomies, etc.   Set the default alias to [term:vocabulary]/[term:name]

It should be mentioned for any case that the default Drupal path for taxonomy terms is taxonomy/term/[term:id]


Why does this simple javascript execute multiple times?

Behaviors will be executed on every request, including AJAX requests.

you can use the once function to make sure it is only triggered once.

(function ($, Drupal) {
  Drupal.behaviors.mei_library_turn = {
    attach: function(context, settings) {

       $('main', context).once('mei_library_turn').each(function () {
          console.log('ready1');
       };)

      // There would be a lot more code in here, but I've stripped it all out to debug.

    }
  };

})(jQuery, Drupal, drupalSettings);


best practice: what directory should the theme be located for a site install profile

Normally, the theme would go in:

/profiles/YOURPROFILE/themes/YOURSUBTHEME

Also include the base theme at the same location:

/profiles/YOURPROFILE/themes/omega


Does drupal_get_path_alias only work if you are requesting a page, or can it also work if you are requesting a form?

For Drupal 6 there was a Sub-path URL Alias module.

  The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias. For example, if node/1 is aliased to content/alias, this module rewrites the link to the node edit page node/1/edit to use the aliased URL content/alias/edit instead. This also includes Views URLs taking a node as argument (node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal URLs.

I'm not sure if there is any for D7. If not porting it would be the option to go for.


Possible to run views_embed_view() for a specific role

In view check the option of "Access" and select roles. Now even if you call the view with views_embed_view() It wont display if the user is not part of the role that have access.


Timeout in sites, perhaps related to cron

Even if you say its not: This issue is most commonly not only Drupal 8 related. You will find issues for Drupal 7 reporting near the same behaviour. It turns out that cron starts after the expired period with first page request. If this happens, the cron seems to take endless time and seems to interfere with the page request in the same moment. Many experienced users run their crons from Drush manually or combine it with server crons. But generally spoken :

There are 3 possible points to look at and to modify (and you already named some of them), which all can interfere each other or can be responsible for it each at their own allone:

Take a look at your php and apache settings for memory, cache size
and sql query time settings. Cron is a big wave coming. From my
experience a smooth Drupal experience can be only granted by
increasing it over the given amount suggested.
Turn off automatic cron frequence (as you sad, mostly set by 3
hours, set it to -none-) in the admin/config pages, but make sure
that you run cron by yourself manually often enough (thats how I
generally do it). For some reasons and some unclear circumstances
(mostly server related) this is often the only option to prevent
this behaviour.
Make sure that you have turned off all unneeded modules on
production sites. Even if some suggestions say its not related, my
experience is, that turning off help, update, dblog (use syslog
instead) etc. at production sites makes Drupal faster and prevents
such overheats.


How to get product variation of a single product in view

You need to add a context to tell the view which product you want to show. Either from the URL with product id in url, or static product id number, or some other way.

The context filter for views relies on a url or some other way to set a value. In this case you want to select one of your products that has variations. So, if your url is /myproducts/1, the context filter can be set to use 1 for the product id and show only that product along with only its variations.

How to pass Views contextual filter via URL?
https://i.stack.imgur.com/8cLtw.png

Use Provide default value from URL, then choose which part of the path will have the product id in it. Then when you link to this view, use the url that way.

On your index page view, you can make the links to products this way so it passes the product id to your page.


The default path or root directory of any Drupal site is the same directory/folder which contains the site itself. ie. Same directory which houses the "sites" directory. If I put a php file there called "my_code.php", any reference to the file will be seen by everything as default. Its when other directories are created and the file placed there which make a file's location more specfic. So if I'm in a php file in another directory and I put in a statement like:

include 'my_code.php';

Drupal will start by looking in its default root directory. If I create a directory there called "my_php_files" and put the "my_code.php" file inside, then my reference to include that file would be:

include 'my_php_files/my_code.php';

Default permissions are normally 755 for directories and 644 for files.


$node isn't available on user pages. But when $showpage is set, you are checking a property on the $node object. This gets the two errors you are describing.

I'm not sure what you are trying to do but you can troubleshoot by breaking out your booleans. I find it helpful to break logic onto multiple lines whenever possible, so that other people (and I) can read it later.

From:

if (((!empty($node)) || (!empty($showpage))) && (($node->type != 'article') && ($node->type != 'basic_page'))):

To:

if (!empty($node) || !empty($showpage)) {
  if ($node->type != 'article' && $node->type !='basic_page') {
    // do that stuff
  }
}

So - when $showpage is not empty but $node is, as on a user page, $node is undefined.

I'm not exactly sure what you are trying to do but I think it is along the lines of "show this stuff on node pages that are not basic page and not article, or when the $showpage variable is present.

In which case:

if ((!empty($node) && !in_array($node->type, array('article', 'basic_page'))) || !empty($showpage))

Or more readably,

if(function_exists('views_get_page_view') && views_get_page_view() ||  arg(0) == 'user') {
  $showpage = 'yes';
}
elseif (!empty($node) && !in_array($node->type, array('article', 'basic_page'))) {
  $showpage = 'yes';
}

if (!empty($showpage)) {
  // do that stuff
}

It isn't a one-liner, but the longer code is easier to read, troubleshoot, and prevent errors.


do the sum of two commerce_price field with programming api

There is no basic price addition function, though we have API enhancements on the roadmap for Commerce 2.x. I'd take a look at what commerce_order_calculate_total() is doing to figure the order total price field; you have to sum the amounts, like you've already discovered, and you then use commerce_price_components_combine() to merge the two price fields' components arrays together. Hope that helps!


Judging by grep -R exit * in the drush folder, I think not. However, there is hook_drush_exit(), see docs/drush.api.php.


How can I programatically select the node template to render a node in Drupal 7

Unless I am missing something here, this is a classic job for hook_preprocess_node(), eg...

function YOURMODULEORTHEME_preprocess_node(&variables) {

  if ( /* whatever logic */ ) {
    $variables['theme_hook_suggestions'][] = 'node__YOURNODETYPE_public';
  }

  // other preprocessing here

}

...which would cause Drupal to look for a node--YOURNODETYPE-public.tpl.php template when whatever logic was true.

Read Working with Template Suggestions and Theme Suggestions for a lot more info on all of this.


How to favor exact matches in entity reference autocomplete?

Here's a way to alter the query for entity reference autocomplete. You can add an expression that returns the string length and then sorts by this.  This way, if a string contains "DIS", and it sorts by the string length, it will start with 3, and the only item that contains the string and is of the shortest length that contains the string (3) is the exact match, so it will show your exact match first, and then other relevant items that contain the string.  For example "ADIS" or "DISV".

/**
 * Implements hook_query_TAG_alter().
 *
 * Favor exact matches and shorter matches in node reference
 * autocomplete.
 */
function mymodule_query_entity_query_node_alter(AlterableInterface $query) {
  $routeMatch = \Drupal::routeMatch();

  if ($routeMatch->getRouteName() != 'system.entity_autocomplete' ||
    $routeMatch->getParameter('selection_handler') != 'default:node' ||
    $query->getMetaData('entity_type') != 'node') {
    return;
  }

  if (is_object($query->getMetaData('entity_reference_selection_handler')) && $query->getMetaData('entity_type') == 'node') {
    $tables = $query->getTables();
    if (!empty($tables['node_field_data'])) {
      $query->addExpression('CHAR_LENGTH(node_field_data.title)', 'shortest');
      if ($groups = $query->getGroupBy()) {
        $query->groupBy('shortest');
      }
      $query->orderBy('shortest');
    }
  }
}

//You can use the same basic template for other entity types:

/**
 * Implements hook_query_TAG_alter().
 *
 * Favor exact matches and shorter matches in mycustomentity entity reference
 * autocomplete.
 */
function mymyodule_query_entity_query_mycustomentity_alter(AlterableInterface $query) {
  $routeMatch = \Drupal::routeMatch();

  if ($routeMatch->getRouteName() != 'system.entity_autocomplete' ||
    $routeMatch->getParameter('selection_handler') != 'default:mycustomentity' ||
    $query->getMetaData('entity_type') != 'mycustomentity') {
    return;
  }

  if (is_object($query->getMetaData('entity_reference_selection_handler')) && $query->getMetaData('entity_type') == 'mycustomentity') {
    $tables = $query->getTables();
    if (!empty($tables['mycustomentity_field_data'])) {
      $query->addExpression('CHAR_LENGTH(mycustomentity_field_data.title)', 'shortest');
      if ($groups = $query->getGroupBy()) {
        $query->groupBy('shortest');
      }
      $query->orderBy('shortest');
    }
  }
}


Organic Groups D7 : How to get custom group list of login user?

You can use og_get_groups_by_user function.

$current_user_groups = og_get_groups_by_user();


What I ended up doing was updating drush to 8.0.5 and that solved it.


How to hide roles from user_profil_form while keeping value?

In my experience, unsetting the field works fine to disallow access to a field while keeping values on update. For example:

/**
 * Implements hook_form_alter.
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'user_profile_form') {
    unset($form['account']['roles']);
  }
}


How to check spelling of user typed text in a form textbox

You can use HTML spellcheck Attribute for the textfield. The spellcheck attribute is new in HTML5.

  The spellcheck attribute specifies whether the element is to have its spelling and grammar checked or not.

You can use this attribute in your textfield like follows. I've tested this and working fine.

  $form['check'] = array(
        '#type' => 'textfield',
        "#attributes" => array("spellcheck" => "true")
      );


Main page teaser with module paragraphs?

The “manage display” teaser configuration page did not show the number of paragraphs to be displayed in the teaser view since the "Display Suite" module was not installed. I missed the display suite module because it was not mentioned in the cited article about paragraphs. :-(

It is, however, easily possible to also generate reasonable teaser views without having the Display Suite module installed: Just configure a content type with 2 fields for the page content: The first serves as single teaser/introduction field and the second serves as vehicle to choose among multiple and per CSS differently formatted paragraphs for the following content. The first field I call “intro field” in the following.

For the intro field (to me) there seem to be certain restrictions: If one wants to use a flexible paragraph item for this purpose, it seems to be only possible to show or hide the element on the teaser or full content page, respectively. (Within this respect, text_with_summary appears to make no sense as element of a paragraph bundle).

On the other hand, one could also use an unwrapped text_with_summary field as the first part of an article. This enables the full teaser functionality where one can select from mere shortening or providing an alternative abstract. Most important the manage display page will now let you choose “summary or trimmed” as teaser.


How do I allow users to see other users' views based on taxonomy fields

It is possible with views relationship and contextual filters. You can add a relationship that references users and publications and then add user id to filter the publication based on the result


How do I enable the PHP filter only for webforms?

I suggest is in your custom module add more description to your field that user enter php code with Not surround it with<?php ?> then in your submit handler that runs before other submit handler ( add it with array_unshift) use php eval then put your returned data in your field.

  Eval :mixed eval ( string $code ) eval — Evaluate a string as PHP code

  code

Valid PHP code to be evaluated.

The code mustn't be wrapped in opening and closing PHP tags, i.e. 'echo "Hi!";' must be passed instead of '<? echo "Hi!"; >'. It is

  still possible to leave and reenter PHP mode though using the
  appropriate PHP tags, e.g. 'echo "In PHP mode!"; ?>In HTML mode!

Apart from that the passed code must be valid PHP. This includes that all statements must be properly terminated using a semicolon.

  'echo "Hi!"' for example will cause a parse error, whereas 'echo
  "Hi!";' will work.

A return statement will immediately terminate the evaluation of the code.

The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain

  visible after it terminates.

  Return Values ¶

  eval() returns NULL unless return is called in the evaluated code, in
  which case the value passed to return is returned. If there is a parse
  error in the evaluated code, eval() returns FALSE and execution of the
  following code continues normally. It is not possible to catch a parse
  error in eval() using set_error_handler().


How to set manual crop to be compulsory for image?

I resolved my problem by using hook_node_validate.


Does elysia cron need to be executed through Drush cron?

The module page is fairly clear ...

  For the basic install you only need to enable the module and Elysia
  Cron will be up and running.

  You can stop here if you don't need a great precision over task
  execution and you don't have to execute a task more often than once an
  hour. For example, if you need only the "Once a day", "Once a week" or
  "Once a month" schedule rules the basic install is fine. (For D6 users
  that want to stop here: you should have installed Drupal crontab as
  described in Drupal INSTALL guide).

  However to get the full potential out of elysia cron and have the full
  control over you tasks a further step is needed: you need to configure
  the system crontab to execute drupal cron every minute. Follow the
  Drupal guide about this: http://drupal.org/cron The only difference is
  that you should use the "* * * * *" rule part instead of "0 * * * *"
  or "45 * * * *" as described in the guide.

Cron is a server thing, not a Drupal thing. Hook_cron is a nice PHP interface to stuffing custom tasks into the file http://www.mysite.com/cron.php which Drupal's Poor Man's cron or ElysiaCron can use to run your tasks.

As the above notes -- if you just need daily runs, weekly runs, monthly runs -- simply enable the barebones Elysia or Drupal cron. For more fine grained control over cron tasks they recommend a system crontab entry that polls Drupal cron every minute. Elysia's task management logic checks what tasks it has to do in X timeperiod every minute (whats Done, what is to begin, whats running, etc). This is the power of Elysia cron and also UltimateCron.

Whenever a browser hits cron.php you are subject to timeouts -- even if programming attempts to avoid it (such as the Batch API, which can sometimes timeout and fail -- eg what happens when your webserver (Apache) is under load and the next cron.php call is never successfully handled?).

By running via Drush you are 100% free of worrying about webserver timeouts -- because its now a server side PHP script which may run indefinately.

1 advantage of running through Drush is you can pipe output from your
cron tasks (there shouldnt really be any) to a custom file.

You can invoke a Cron run directly using Drush via:
drush cron for all options to Drush cron see drush help cron


I finally managed to get this working. Under show available tokens, I previously had selected -- All --.

I have since changed this to be just the fields that I'm interested in having edited and it works as expected now.

My theory is that I have a lot of content types with a lot of fields and it was hitting some sort of memory error. However, I never saw an error reported.


How to hide row cell when using table in forms?

I've just implemented it using a theme preprocessor to alter the tag from <td> to <span> and I've added the hidden and aria-hidden attributes. Hidden by itself works but it isn't supported by < IE10.

So as to prevent the loops on every table I've added a class to the table as well so I'm checking for 'form-table' first.

/* Implements MODULE_preprocess_HOOK */
function mymodule_preprocess_table(&$variables) {
  if ( ! in_array('form-table', $variables['attributes']['class']) )
    return;

  // Iterate the variables looking for form elements that have the type hidden
  foreach ($variables['rows'] as $key => &$row ) {
    foreach ( $row['cells'] as &$cell ) {
      if ( $cell['content']['#type'] == 'hidden' ) {
        $cell['attributes']['hidden'] = TRUE;
        $cell['attributes']['aria-hidden'] = 'true';
        $cell['tag'] = 'span';
      }
    }
  }
}


Drupal Rules, create the SUM of a field decimal values

You could enable PHP filter module (in core package), what will expose a 'run PHP' rule. There you could run some queries. Have a look at db_select and db_query for how to construct them (there are good advices in the comments as well.).

Proceed with caution though as you are communicating directly against the database. Sanitize the in- and outputs.

If it is only for display purposes, you could achieve a similar effect with Views and aggregation enabled. Enable aggregation in the advanced section. Add the final_value field, and select SUM. This is a much safer approach.

UPDATE

I suppose you are triggering the rule on the save event of the Order-node? In that case the Order is in the $node variable and you could go as follows;

$node->field_name = $calculated_value;
node_save($node);


How to add a custom class or id to a menu

Menu Attributes is definitely a way to do this.

This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
You should use this module when

You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
You want to give a menu item an ID so you can easily select it using jQuery
You want to add additional classes or styles to a menu item

The module currently allows you to set the following attributes for each menu item:

Id
Name
Target
Rel
Class
Style
Accesskey


Acquia works on a three-environment system. When working in such a system, code moves up, from dev -> stage -> prod, while databases move down from prod -> stage -> dev.

You should always consider content on dev and stage, such as nodes, users, taxonomies etc, as temporary. This is because the way to migrate content is by migrating the entire database from prod -> stage/dev, or sometimes from stage -> dev.

In order to get your user on all environments, you would create the user on prod, then migrate that database to stage and dev. You will then be able to log in with your user on those environments.


How do I use dependency injection on \Drupal::moduleHandler() to a Controller?

In a controller you inject services by using the service container. For example ModuleHandler:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;

class MyController extends ControllerBase {

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Constructs a MyController object
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   */
  public function __construct(ModuleHandlerInterface $module_handler) {
    $this->moduleHandler = $module_handler;
  }

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

Then you can avoid \Drupal calls by using the injected service:

$this->moduleHandler->alter('mymodule_myfunction', $plugin_items);

You can inject any service, existing ones from core/contrib or services you've defined in custom code in a *.services.yml file.

To find a core service name I usually look into core.services.yml, because that's the quickest way when you are working on a drupal project in your IDE.

You can use Drupal Console to list all services, not only from core:

drupal debug:container

You can also use the Devel module, which allows you to search for a name:

/devel/container/service


The service "redirect.request subscriber" has a dependency on a non-existent service "path.alias_manager"

In Drupal 8.8 path.alias_manager was deprecated and in Drupal 9 it was removed. You need to update the Redirect module to a version compatible with Drupal 9.
The current version contains the correct service definition having path_alias.manager as dependency:
modules/contrib/redirect/redirect.services.yml
redirect.request_subscriber:
  class: Drupal\redirect\EventSubscriber\RedirectRequestSubscriber
  arguments: ['@redirect.repository', '@language_manager', '@config.factory', '@path_alias.manager', '@module_handler', '@entity_type.manager', '@redirect.checker', '@router.request_context', '@path_processor_manager']
  tags:
    - { name: event_subscriber }


The placeholders @current, @total, etc are described in the file includes/form.inc in the description of the batch_set() function.

  progress_message: Message displayed while processing the batch.
  Available placeholders are @current, @remaining, @total,
  @percentage, @estimate and @elapsed. Defaults to t('Completed
  @current of @total.').

You can add custom placeholders by using the t() function like this:

$my_custom_variable = 'contents of my custom variable';

$batch = array(
  'title' => t('Generate reports'),
  'operations' => array(
    array('create_report_callback', array($time_min, $time_max)),
  ),
  'init_message' => t('Starting report generation...'),
  'progress_message' => t('Generating @my_custom_placeholder report. Operation @current out of @total.',
     array(
       '@my_custom_placeholder' => $my_custom_variable,
     )
  ),
  'error_message' => t('Error detected. Please try again!'),
  'finished' => 'create_report_finished',
);


Injecting Views blocks into another View template

You could create a new View field in modules/yourmodule/lib/Drupal/yourmodule/Plugin/views/Field and "attach" it via hook_views_data_alter() or hook_views_data(). This field would returns a hardcoded view or dynamic, depends on your needs. Another way would be to use Views templates.


Need to save node twice to get wanted result

Happy you solved it without walking around it via AJAX, I think it was a good call. I am still gonna pick up on this thread though, simply out of stubbornness, please bear with me. :-)

So, your hook_node_presave entry point is fine and in all practical aspects you probably will not need to read further down. However, your tokens should have been available from the very beginning to Pathauto. The problem was - following your code from this revision - the use of the menu_get_object() function. I assume the following caused the problem:

You created and saved a new node with your migration code
Your hook_tokens implementation was called from the Pathauto module during node_save
menu_get_object was called and returned nothing
New node was created with the wrong URL path

The reason menu_get_object returned nothing is because the new node was not yet available via Drupal's routing. This is expected since all new nodes need to be properly saved once to get a route like node/NID ). This also explains why your code worked properly for a - now - existing node, with a registered route.

Your code would actually have worked fine if you had used the $data parameter, you could have picked your node object from there like this:

// $node = menu_get_object();
$node = $data['node'];

I tried this quickly in my sandbox and I could both reproduce the original problem and also solve it.

Conclusion: Your code, if you still want to use it, and get rid of the additional hook_node_presave implementation, should work fine if you apply the above change.

Cheers!


Select List, 'Other" option text field, any text written in textfield 'Illegal Value' error is given

Are you using http://drupal.org/project/select_or_other ?

Is the field set as required? Take a screen pic of the config for the field.


Render field by name in custom content node template

Ended up installing a fresh copy of Drupal and re-adding the content type (through the UI as before). After that it worked fine.

Not sure why that happened, no time to debug, will just continue with this install.

I suspect either I broke the the 'Frontpage' view while fiddling, or one of the Modules was breaking it, perhaps Twig Field Value.

I need to now access a multi value field in Twig, thinking something like {{ content.field_name.0 }}. I need to access the array directly without the use of a foreach loop, because they fit into different parts of the html layout.

Thanks for the responses!


You need to run patch -p1 < patchname-issuenum-version.patch from the directory containing the core directory, not from core/mdoules/some/ or core/modules/some/. (I take core/mdoules/some/ is a typo in the question body.)

Patches for Drupal core are created from the Drupal root directory, so when you apply a Drupal patch, you need to change directory to that one.


There are several options, choose depending on your requirements:

You can use module Blocked IPs Expire to add an expiration date to IP blocks when adding them. The Drupal cron job will remove the blockings after expiry.
You can remove all of the IP blockings at once with this drush command:

drush sql-query "TRUNCATE TABLE blocked_ips"

You can remove just some IP blockings (e.g. an IP range) with similar drush commands. For example to delete all IPv4 blocks:

drush sql-query "DELETE FROM blocked_ips WHERE ip LIKE '%.%.%.%'"

Note that auto-banning users and IP addresses after a number of unsuccessful login attempts is a different Drupal Core mechanism, resulting in entries in table flood – more details. To remove these bans, the Flood Unblock module can help you. (But that mechanism is out of the scope of this question anyway.)


How can I get Panelizer to link my panels to a specific URL instead of the Content option?

I found out that I can make a user-uploaded image linkable to a fixed location that I choose. If I create a view that takes in the user-uploaded picture, and then add a link through views, Panelizer will let me place the view in a pane. This means I can have a linkable image in a pane. I have included step-by-step pictures.

This shows up upon the creation of a view. Click the add button by the fields in the left column to add the picture from a content type.

This shows you that a content node needs to be picked. In this case, it is a picture that the user uploads

Upon the selection of the picture views will ask how to display it. I have selected "Output as a link" This will then open up this part of the menu:

Here you can select the URL you want the link to go to. For example, somewhere on your site or to drupal.org :)

You then need to save everything. Then, go back to panelizer, or panels. There select a cog wheel and add content. This page should look like this:

Then, it will bring up a window where you will need to click on the views option:

Then you should see these windows:


Programmatically disabling webform component - Drupal 7

I have never had luck trying to set the disabled flag via a FormsAPI hook using the array indexes.  Looking at the code above, it would also seem that you are setting the incorrect 'disabled' for the form array - #disabled is what is checked during the rendering process.

But, like I said, never had much luck with it anyway.  What you may end up needing to do is set the #attributes array for the form element, specifically identifying the disabled property as in the html element tag:

<input type='text' disabled />
// becomes
$form['element']['#attributes'] = array('disabled' => '1');

obviously with the form indexes specified as needed.


How can I prevent some configuration settings getting overwritten?

I believe that Config Ignore could help you out here.

Spoiler: I am the maintainer of that module.

Install the module, go to admin/config/development/configuration/ignore and add the names of the config entities that you would like to not to change, when you import.

In this case:

swiftmailer.transport
system.performance

Save, remember to export config_ignore.settings.yml to the config folder (yes, some of us tend to forget that bit) and you should be golden.


Is there an alternative Drupal 7 module for the Advertisement module?

Just released is the SimpleAds module for Drupal 7. This module provides a way to feature advertisements on a Drupal website. It displays graphical ads in configurable blocks. It records and reports useful statistics. It is easy to configure and does not depend on other contrib modules.


Ended up just using a custom hidden form as suggested by 4k4 and am populating/submitting it via jquery/ajax.


Get data from a field using query in Computed field and use it as an array

You can pass any value of node or something else in jquery like

$node_id = 5;
$node = node_load($node_id);
$settings = array(
    'title' => $node->title,
    'custom-data' => 'ABC',
);
drupal_add_js(array('mymodule' => $settings), 'setting');
drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.js', 'file');

And get that value in jquery like (you have to put this code in mymodule.js)

(function($) {
        Drupal.behaviors.mymodule = {
            attach: function(context, settings) {
                var title = Drupal.settings.mymodule.title;
                console.log(title); // or perform some operation as you prefer
                var custom_data = Drupal.settings.mymodule.custom-data;
                console.log(custom_data );
            }
        };
    }(jQuery));


Cannot Add Registration to cart: SQL Error with Registration and Drupal Commerce

So, the error was the result of missing registration states. I found the details in this post on the Entity Registration Issue Queue Pdoexception Error. I added a default "active" registration state, and this solved the problem.


make view modes for commerce enabled by default when exporting with features

That info is stored in the field_bundle_settings_node__contenttypenamehere variable.  So make sure you export that for each of your content types.


Yes it's possible.

You need to go to the Field Collection module directory and copy field-collection-item.tpl.php. Then paste it into your theme directory and rename it to field-collection-item--myfieldname.tpl.php.


Use inline_template instead of markup, or a theme function (as suggested by Ivan Jaros in a comment also).
Refer to class InlineTemplate for way more details. Here is a partial quote of it:

Provides a render element where the user supplies an in-line Twig template.
Properties:

#template: The inline Twig template used to render the element.
#context: (array) The variables to substitute into the Twig template. Each variable may be a string or a render array.

Usage example:
$build['hello']  = [
  '#type' => 'inline_template',
  '#template' => "{% trans %} Hello {% endtrans %} <strong>{{name}}</strong>",
  '#context' => [
    'name' => $name,
  ]
];


Views Exposed filter Multiple times on a Page Or Different id for views exposed filter if added one more time

While adding a filter there is a dropdown at the top as 'For', by default 'All displays' are selected, by selecting the specific block that particular filter will be displayed on selected block only. Please try and let me know if it worked.


D7+ i18n: What is the normal way: a single node with 2 translations or a different node for each translation

I believe this is the normal way. In /admin/content it lists the content and you can sort by language.

It knows which belong to which because it writes that info into the node table in the database by defining the 'tnid': The translation set id for this node, which equals the node id of the source post in each set.


You can use module Rename Admin Paths

  This module allows you to:

  rename path like '/admin/...' to '/something/...' rename path like
  '/user/..' to '/something else/..' It can be effective against
  registration spam bots or malicious people.

  This small module just implements hook_outbound_alter and
  hook_inbound_alter to rename paths. A settings form allows to choose
  replacement term for "admin" and "user".


Typically, unless you are using a specific contributed module, the pager is a template file that comes with views. You can override theme_pager for the specific view (or all your paged views) and add the additional div.

https://api.drupal.org/api/drupal/includes!pager.inc/function/theme_pager/7

Examples on how to do this:
https://www.drupal.org/node/387786


Cron is not working - leading to user/0/edit instead

I think your not logged in, that's why going to  " user/0/edit " path because you have not permission to run cron.
Please check it.


How to get user permissions for the role Administrator?

See the Role::getPermissions() method code:

  /**
   * Returns a list of permissions assigned to the role.
   *
   * @return array
   *   The permissions assigned to the role.
   */
  public function getPermissions() {
    if ($this->isAdmin()) {
      return [];
    }
    return $this->permissions;
  }

So, if the user has all permissions the returned value is an empty array.

Why? I really don't know and I can't find the answer, maybe other user knows Why Role::getPermissions() method return an empty array for admin users?.

The good news is that you can get all the Administrator permission with this code:

array_keys(\Drupal::service('user.permissions')->getPermissions());

Test this code (You'll need the Devel module to use dpm()):

$administrator = Role::load('administrator');
if($administrator->isAdmin()) {
  dpm(array_keys(\Drupal::service('user.permissions')->getPermissions()));
}


Revert back to the previous dev version of a module using composer

You have to refer to the dev branch and reference the SHA of the version of dev you want in Composer.

Example:

composer require drupal/field_group:3.x-dev#COMMITSHA

This will fetch the dev branch of version 8.x-3.x at this specific commit. To get that commit itself, you’ll have to find it on the git page for the project ( which now goes to GitLab).

I can’t find the exact one you are looking for (I’m on mobile) but here is an example.

https://git.drupalcode.org/project/field_group/commit/a4bd38698187c30184d5c76fd884be86e2091fe7

So you’d do:

composer require drupal/field_group:3.x-dev#a4bd3869


Yes you have to use Oracle Driver.

  This is a driver that allows Drupal to use an Oracle Database instead
  of MySQL as the primary backend.

Refer to these links :

Link 1
Link 2

I hope these links may definitely solve your query.


Get the titles of the nodes whose node IDs are contained in a field

A few remarks:

You said that $node->field_xlnum[0]['value'] contains a list of nid separated by comas so you don't need to explode it in order to use them in a IN clause. If you do so, $attr will be an Array().
You put test as an argument in your query, isn't this a variable $test or a string 'test'
You should better use db_placeholders for putting multiples values inside a IN.

$attr = explode(",", $node->field_xlnum[0]['value']);
db_query("SELECT n.nid, n.title
  FROM {node} n
  WHERE n.nid IN (" . db_placeholders($attr, 'int') . ")
  AND type = %s
  ORDER BY n.created DESC", $data, 'test'
);


I'm assuming creative_customize_comment_form() is a custom form function, so it probably exists in either:

A file inside a module that's not enabled, so Drupal can't find it
An include file in the module that's not automagically included during the page build.

The solution to the first is obviously to enable the module.

The solution to the second is to Make sure the appropriate file is included in the page build, using module_load_include(), e.g.

module_load_include('inc', 'creative_customize', 'creative_customize.pages');
// Now call drupal_get_form()...

Without more information I can't think of any other reason (other than the function name itself being incorrect) that drupal_get_form() would fail.

Source: https://api.drupal.org/api/drupal/includes!module.inc/function/module_load_include/7


Yes. You can call all function is write in file .module. If function don't write in file .module. You need use function module_load_include and you can call it.


Menu callback error : Undefined offset: 4 in _menu_translate()

What is the % parameter in the url used for - a feed item maybe?

For that type of UI, you may need to add a load function and use a named parameter instead for the %

e.g:

/**
 * Implements hook_menu
 */
function planet_extension_menu() {
 // ...
 // ...
    $items['admin/structure/feeds_admin/manage/%pe_feed_item/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('delete_feed',4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'planet_extension.admin.inc',
    );
 // ...
 // ...
}

/**
 * Menu callback load function for pe_feed_item argument
 * This function loads the feed item
 * which is then passed as a page argument to the menu callback function
 */
function pe_feed_item_load($fid) {
  // Load feed item somehow from feed id and return it, e.g:
  return db_query("SELECT * FROM {pe_feed_item} WHERE fid = :fid", array(':fid' => $fid))->fetchObject();
}


How to display user submitted nodes in the node detail view of the same user?

I tried the following and it seems to work:

Create a new block view
Add a Contextual filter of type Content: Nid
Add a relationship of type Content: Author (Required)
Add a relationship of type User: Content authored that uses the previous relationship and is required
Under Format you set Show: Content | Full Content - You must also use the User: Content authored relationship for this one

You could also change the number of related nodes that will be shown and also you might wan't to add a filter of Content: Type to restrict what kind of nodes to display. Notice that you could create a template for a specific content-type ie node--<YOUR_CONTENT_TYPE>.tpl and load and execute the view from there.

In you node.tpl file you would load this view doing something similar to:

$view = views_get_view('YOUR_VIEW_NAME');
$view->set_display('YOUR_VIEW_BLOCK_NAME');
$view->set_arguments(array($node->nid));
$view->execute();
echo $view->render();

Note I think you should specify every field you wan't to use, in other words you shouldn't use Show: Content | Full Content - because this will result in an infinite loop. I don't think this is a complete solution, but perhaps it will point you in the right direction.

If you are using fields in the view you could create a separate template named views-view-fields--YOUR_VIEW_NAME--YOUR_VIEW_BLOCK_NAME.tpl that will be used to output the actual fields.

To exclude the current node from the listing you need to modify your contextual filter.

Click the More button for Content: Nid and choose exclude you should also make this filter use your relationship for Content: Authored


There's no official documentation for Oracle (I don't think), but INSTALL.mysql.txt states you need the following permissions for MySQL in Drupal 7:

SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER

I came across an INSTALL.oracle.txt on http://drupalcode.org, but I can't vouch for it's accuracy. It says to run the following with regards to permissions:

grant dba, create any trigger, drop any table, select any table, select any sequence, create user to drupal identified by drupal;
grant connect, resource to drupal with admin option;
alter user drupal default tablespace users temporary tablespace temp;

Show both of those files to your DBA, it should be enough for him to go on.


You could add a regular webform field to capture the calculation result, filling it via Javascript.
Then you hide the field via CSS.

Storing a bunch of html has a security risk though.


How to create a rule to remove a product by sku, or remove a product to the cart

You are making the assumption a commerce order in cart status contains products. In fact a commerce order consists of line-items that in turn link to products. These line items also contain also the unit price and the amount of the product (and some other details). It can be done but it requires some juggling with Rules as there is not a remove from cart rules.

So your Rules should fire on the event A product is removed from cart. Your condition should be to check for the product SKU, and in the actions you will have to run through all line items and delete the right one.

So you need to add a Loop through each line item on the commerce order to find the right product.

This is the easiest if you create a Rules component where you send the current line-item and the SKU to remove. Then in that Rules component add the following conditions:

Entity had field. (Make sure the line item has a product field)
Data comparison. (Make sure the product SKU matches the input SKU)

Action:

Delete an entity. (Delete the line item to remove it from the order, see Rule action to remove a product from the cart? (using the commerce module)).

On the main Rule, use the following actions:

Set a data value (to set your SKU to remove, this will be sent to the component).
Add a loop (Provide it with the commerce-order:line-items to loop over those)
In the loop, add your component as an action and provide it with the loop's current item and the SKU to remove.

Final note:
As it appears you will always be selling these products in pairs, you might find the Commerce Product Bundle interesting. It allows you to combine two products into one. I suppose it will remove both products also when removed from the cart.


My webhosting won't allow "Options" in .htaccess

Options -Indexes prevents users from seeing which files exist in a directory. You shouldn't use this feature to secure your site, it mainly exists for aesthetic reasons. It is technically never necessary.

Options +FollowSymLinks is not necessary in a vanilla Drupal installation, chances are you do not need this one either.

Have a look at the documentation of the Options directive for more details.


Show teasers to anonymous visitors but not allow access to the body/node

One way to do this is to use Panels.  Override the front page and the default node template; create two variants for each, one for anonymous and one for authenticated users (using selection rules).

Then, for the front page for anonymous users, only use teasers and remove the links to the full content.  For the anonymous node template, limit everything to teasers.

For authenticated users, enable everything just as you'd like them to see it.

Note: this is not a full tutorial on Panels, but should hopefully provide some hints to get you started.

Keep in mind that doing this will cut the search engines off from your non-teaser content as per Clive's comment.


How to assign twig templates dynamically on basis of field value of custom block?

See https://drupal.stackexchange.com/a/211157/31 for an existing related answer.

You implement the theme suggestions hook, the block_content entity is in $variables['elements']['content']['#block_content'] as shown there, then you can access your field values from there and provide any kind of template suggestions that you want.


How to get the URL of an entity being created at hook_entity_insert() stage?

The URL object is there, you're just calling it wrong.

The code for this is a little complicated:

  $path = $entity->toUrl('canonical', ['absolute' => TRUE])->toString();
  $params['message'] = $path;

For more info, see this issue.


Using custom properties is not an hack; quite the opposite, it is a perfectly fine way to achieve what you want. It allows you to identify the form elements that need to be altered, which is what you want.

In fact, custom properties are normally used from Drupal, which uses the following code for fields associated to an entity.

  $element = array(
    '#entity' => $entity,
    '#entity_type' => $instance['entity_type'],
    '#bundle' => $instance['bundle'],
    '#field_name' => $field_name,
    '#language' => $langcode,
    '#field_parents' => $parents,
    '#columns' => array_keys($field['columns']),
    '#title' => check_plain($instance['label']),
    '#description' => field_filter_xss($instance['description']),
    // Only the first widget should be required.
    '#required' => $delta == 0 && $instance['required'],
    '#delta' => $delta,
  );

Custom properties are also the Drupal 7 way to pass variables to theme functions. For example, the following code is using theme_table() to render part of a page.

  $build['node_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No content types available. Add content type.', array('@link' => url('admin/structure/types/add'))),
  );

Passing $build to drupal_render() produces the same output produced by the following code.

$html = theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No content types available. Add content type.', array('@link' => url('admin/structure/types/add')))));

The alternative would be adding a #after_build or #process function to the form elements, but those functions are called before the form element is rendered, which means they can just alter the form element properties.

Those functions get access to the content of $form_state, and get $form_state['input']['form_id'] or $form_state['input']['form_build_id']. This is what the documentation for drupal_build_form() says about $form_state['complete form']:

  A reference to the $form variable containing the complete form structure. #process, #after_build, #element_validate, and other handlers being invoked on a form element may use this reference to access other information in the form the element is contained in.

To add a #after_build function (which gets $element and &$form_state as parameters), you should implement hook_element_info_alter() to change the form element definition.

Notice that theme_form_element() is defined as theme wrapper for every form element, similarly to what done with the following code for the textfield form elements.

  $types['textfield'] = array(
    '#input' => TRUE,
    '#size' => 60,
    '#maxlength' => 128,
    '#autocomplete_path' => FALSE,
    '#process' => array('ajax_process_form'),
    '#theme' => 'textfield',
    '#theme_wrappers' => array('form_element'),
  );

As side note, every theme function has its own preprocess functions; for example, for theme_textfield() those functions are hook_preprocess_textfield(). They can suggest a different theme function to be used by adding values to the $variables['theme_hook_suggestions'] array. ($variables is the parameter passed as reference to the theme preprocess functions.) Unfortunately, the theme and the theme preprocess functions don't get any reference to the form being build.

References

drupal_build_form()
form_builder()
system_element_info()
theme()


Why don't menu tabs show for a view generated page?

Those tabs are used for node editing. When you create a "page" from the views module it is general collecting a series of nodes on the page, so it is not displaying the single node tabs.

You might consider using this module. Block Edit

It generates view/edit tabs for blocks and views.

Hope this helps!


is it possible to have two input fields per label in a Drupal form?

You cannot have a label for two form fields, as the label is output with HTML code similar to the following one.

Category: *

The attribute for accepts a single form element ID; you cannot use the following HTML, for example.

Category/Recipients: *

If you don't want to use a label for the second form element, you can simply use an empty string for the #title property.

As for saving those values in the database, a label is not used when saving the value of a form element, but it is used only on the user interface. The code for saving the content of a form element doesn't use the label value, but the identifier associated to the form element.
In your case, the form submission handler would get the value entered from the user for the $form['example_textfield'] element from $form_state['values']['example_textfield'] where in Drupal 5 would have used $form_values['example_textfield'].


You need a patch that hasn't been merged yet.

Issue is here - https://www.drupal.org/project/read_time/issues/2819071

The patch was created here -  https://www.drupal.org/project/read_time/issues/2819071#comment-13416093
You need anther module, so read that ^

In case you haven't applied a patch before, here's the link to the documentation on drupal.org about it. https://www.drupal.org/patch/apply

--

Another option, change your view from Fields to Content. Add a view mode to your content type if you need to with only the fields you need.


How to make a relation between nodes in drupal 7?

Entity Reference module works well. But If you need to create a view, you may use Entity View Attachment module. This module attaches a view to a node.


How can I generate a usable dynamic PDF from a Drupal view?

I had never had any success with the html>pdf generating tools for PHP coming out looking 1:1 without issues ranging from style to markup to server side error with the libraries and/or incompatibility with PHP versions, package errors and whatnot.

Another option is to use PhantomJS or an equivalent tool to use a headless browser to output a PDF file for you. Note though, that PhantomJS is possibly going to no longer be maintained, as Chrome now has a headless equivalent.

However, there is a module for Drupal 7 and 8 that provides this functionality (disclosure, I am a maintainer) but it may take a little elbow grease on your end to get it to work the way you'd like. A base js controller for PhantomJS is provided, but you can alter it. If all you need is an equivalent of doing File > Print to PDF in the browser, this will do it without as much hassle as all the PHP libs.

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

As an alternative to that, there is a hosted service provider with an API you can use as well (disclosure - I have nothing to do with it) that might suit you.


Try the Profanity module, here is a quote about it from its project page:

  An alternative to Wordfilter and Phonetic Word Filter, this module
  provides...

  Filters any Entity!
  The ability to create multiple word lists.
  Features exportable.
  An input format filter for either replacing matched words with a repeated character or phrase.
  Super quick no regex processing (for simple matching).
  A function to use for custom form item validation/detection.
  Tokens for title/label properties per Entity allowing you to specify which lists to process with.
  A rule condition for "Text contains profanity" so you can do clever things    when bad words are detected (add to moderation queue).
  Ability to filter Entity titles before view/render.
  A view field for each Entity title, profanity filtered.
  Validation to prevent users registering with a username containing profanity.
  Works with Search API by providing a filtered entity title property to be indexed.
  Integration with Search API Views to provide a field for profanity filtered    Excerpt.

Note that it has Rules integration so you can send emails etc.


The code above returns undefined variables/indexes on things that are obviously defined.

As long as your PHP installation is not buggy, that's not possible. If the variable is defined, PHP won't tell you it isn't defined.

  as soon as I refresh the page the errors go away which seems rather strange to me.

It's not strange - messages are held in the session so if you're doing something that invokes them in a template file (when the messages for the current page have already been prepared), you should expect to see this delayed reaction. Logic should never been in a template file, always a preprocess or process function.

Best practice is really a matter of opinion, but these are the two standard options for accessing fields on any entity type, Field Collection included.

field_get_items()
EntityMetadataWrapper

Both alleviate the need to access the arrays directly, thereby decreasing the possibility of developer error.


How to use drupal_add_html_head() to add the same metatag multiple times?

The tags are stored by key, so using a different key for each should do the trick:

$delta = 0;
foreach ($images as $image) {
    $element = array(
        '#tag' => 'meta',
        '#attributes' => array(
            "property" => "og:image",
            "content" => $image,
        ),
    );
    drupal_add_html_head($element,'facebook_share_image:' . $delta++);
}


A circular redirect was been caused which stopped the redirect to front working. Checking the redirects already created and removing the offending ones fixed the issue.


Adding website logo as the first top level menu item in tb megamenu

You are looking for Menu Icons module.

  This module allows you to upload an image in the menu-item's
  configuration form. After uploading the image, the icon data will be
  added to the menu link's options array.

  When a menu link is goes through the theme layer, it will receive an
  extra class which by default is used to attach the images as a
  background image to the corresponding menu item. These class names are
  also compatible with Nice Menu's.


Is there a way to export a list of all pages and files?

You can use Views Data Export

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV
  Microsoft XLS (or really simple HTML understood by Excel)
  Microsoft DOC
  Basic TXT
  XML

and export as CSV. I recommend you watch this video tutorial.

Your client can then view the CSV file in Excel.


Send email after 100 webform submissions

Have you tried using Webform Rules ?

This should expose webform results to rules, then create a new rule with conditions "if submission ID is 100, 200 etc" then... action: Send email.

You would either need a way to find the nth of 100, or depending on how many submissions you are expecting, just check against a comma separated list, eg "100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200" etc


How can I use the "Taxonomy display" view on the Panels taxonomy override page?

In this case, you don't need to adjust the module weight-- you need to remove the override on the taxonomy term pages.

Are you already overriding the taxonomy term display in Views?  If so, just disable that view and the error should go away.

EDIT: If you still want to use the taxonomy view in Panels, you should edit the view as follows (I do this on one of my sites):

Open the edit screen for the Taxonomy display view.
Click page.
Where it says clone page, click the triangle and select disable page.
Click Add.
Choose Content pane.
Add the content pane.
Click Argument input.
For the first argument, choose From panel argument and First.
For the second argument, choose From panel argument and First. (identical to the settings for the first)
Go to your panel and add this content pane instead of the page (it will appear under View panes).

Why do you have to do this?  Because otherwise Views and Panels will fight each other over who controls the page.  By using a content pane, you avoid assigning a URL path in Views, allowing Panels to override the path successfully.


How to add an 'if' statement for a content type in a custom views-view.tpl.php?

You can access it by adding Node Type field to views and access it using $row variable in views-view.tpl.php.

$rows: The results of the view query, if any

Or $views is also accessible in each and every views template file.


How to completely disable 'further instructions sent to email' message after sign up

You can use rules redirect the user to a pre-defined URL upon registration. This should over-ride whatever default behaviors you are seeing now...

Back up your database.
Enable Rules
Navigate to admin/configuration/workflow/rules
Add new Rule

Event: 'After saving a new user account'
Action: 'Page Redirect' (optionally 'force redirect')


See
https://drupal.stackexchange.com/a/202185/45409

In Drupal 8, you can get url arguments based on what's in the routing.

To get the id alone:

$nid = \Drupal::routeMatch()->getRawParameter('node');

If you plan to load the node object, you can simply get it this way:

$node = \Drupal::routeMatch()->getParameter('node');

To find the parameter names, you can use:

$possible_parameters = \Drupal::routeMatch()->getParameters();

To find the node type, use:

$node->bundle();


Module to upload a file for attachment to many nodes as a bulk operation

If you want to do it a little easier, Views Bulk Operations might be helpful. But otherwise, adding the file to one node, then adding a reference to the file from all the other nodes is the best solution (this way the file isn't independently added to hundreds of nodes, creating hundreds of duplicate files).

You should also check out how FileField Sources adds references to existing files for inspiration.


how to change the value of the form in the preprocess functions or get the value of the function preprocess

You pass extra arguments when building the form using the drupal_get_form.

For example:

drupal_get_form('comment_email_form', 'default_value');

function comment_email_form($form, &$form_state, $default_value)
{
    // $default_value is here the string 'default_value' value passed as extra argument
    // ... rest of your form
}


Media Module Bulk Upload for Image Field

I'm also faced the same issue. But after applying this patch (check your media module version) it works great.


Why is Rules reacting on Commerce Events multiple times and out of order?

Solved!

I had upgraded to PayPal WPP, but also left PayPal Express Checkout enabled.

This caused EC to not display where it normally does, i.e. on every page starting with the cart, but to only display on the Review page where other payment methods can be selected. However, the Rules events for EC were evaluated in their normal place in the process.

Thus the Events were being evaluated even though they had apparently not occurred.

The multiple evaluations of the Event "Calculating the price of a product" is normal.


You're going to see this error when you try to upload an image file that PHP has an issue with, either because it is larger than the allowed maximum file size in PHP or because trying to process the image (ex. for creating thumbnails) is consuming more memory than you have allowed in your php.ini.

There is a monster thread on this topic over at Drupal.org but the key takeaways are to try and increase these two values (php file upload or memory limit) or to switch your imageapi library from PHP GD over to ImageMagick to avoid the memory constraints.


CommerceKickstart; Slideshow content/pages disappear if I add a Product Reference field under Slideshow Content Type

if you want an slideshow that will display products you may want to create an slideshow that will display "product displays" and add to it an relationship with the products entity, then grab from there stuff like "add to cart" button, images, prices etc.

fields in the view may be in form of :

[product_display] - title
[product_ref] - price
[product_ref] - img
[product_ref] - commerce line item "add to cart"


Can an embedded video be made responsive?

We use Fitvids in combo with Video filter to make youtube videos responsive.  You can either add the JS yourself or use the Drupal module version, it works either way.

In the case of using the Drupal module, you'll add the video filter HTML selector to the UI for fitvids and then your video will be responsive.

For example, on my site, I have a video using video filter:

[VIDEO::https://www.youtube.com/watch?v=y0bA_KH-D-I]

... and then in the video filter UI, I have added the slector for the video here:

/admin/config/media/fitvids

In my case video filter is using embedded-video as its wrapper HTML element so I added .embedded-video to the fitvids UI in Drupal.

For more info see:

https://github.com/davatron5000/FitVids.js/
http://fitvidsjs.com
https://www.drupal.org/project/fitvids


Using the modules you described:

Create a index containing all the nodes that are group content
Edit the fields of this index and add a relationship to 'Groups' (at the bottom of the page)
You will get additional (group)fields available
Check the one named "Groups » title" and change the type to "string" (instead of default fulltext)
In the Facet tab, make the facet available, and place the block.

This should do the trick!


Import image with migrate tools changing its name

Two options:

_image_fixed:
  - plugin: str_replace
    source: imageName
    search: "jpg"
    replace: "png"

source_full_path:
  - plugin: concat
    delimiter: /
    source:
      - constants/source_base_path
      - @_image_fixed

Or:

source_full_path:
  - plugin: concat
    delimiter: /
    source:
      - constants/source_base_path
      - imageName
  - plugin: str_replace
    search: "jpg"
    replace: "png"


How to get the number of items in a user's cart from commerce?

you will have to use hook_preprocess_hook to achieve this by passing the variable to the template.

function template_preprocess_TEMPLATE_NAME(&$variables) {
    $variables['YOUR_VAR_NAME'] = $YOUR_VAR;
}

Then you can access your var in the template like so:

{{ YOUR_VAR_NAME }}