How do I get the content of a Panel variant to display on as Content?

OK I think I figured this out:

'Content' is actually Nodes. Don't know why they arnt just called 'Nodes'.
There area different types on Nodes, these are called Content Types. You can add fields to a Content Type. Don't know why they're not called 'Node Types'.
You can use Panel Variants as a kind of template for a Node. You can set Selection Rules to tell it which Nodes to apply it's self to.
Here, in the Panel Variant you can attach Pane Component (my module) to a region.


Double click quickly on the entity save form two entity get created

Try Hide Submit

  Features:

  Hide or disable the submit button after it has been clicked

  Display a message and/or image while waiting


How do you recycle a css file from a different theme into your new theme?

As @cilefen pointed out you need to do a couple of things.

Put the form.css on sites/all/themes/my_theme/css/.
Update your sites/all/themes/my_theme/my_theme.info file to have stylesheets[all][] = css/form.css.
Clear the cache.

Oh and make sure that my_theme is set to default or at least active in the page that your are working.


How to restrict access to files to files of a node while keeping the node itself viewable?

The answer ended up being the function file_get_file_references(), referenced in /core/modules/file/src/FileAccessControlHandler.php

https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/file_get_file_references/8.2.x


I don't see, how you initialize the datepicker (probably in */providers/support/js/datepicker.js file), but for this functionality you should use maxDate and minDate options of datepicker library.


Can you suggest any alternative for Statistics module?

Have a look at the Visitors module. Here are some reports you get from it:

  View pages that have recently been visited.
  View pages that have been hit frequently.
  View pages count per month, day of month, day of week, hour.
  ...

Especially these reports should be what you're looking for (it includes hits for paths corresponding to a view):

Top pages (table with columns Title, Path and nr of Hits).
Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor).

Checkout the above (source) links to get an idea of which data are available.

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module.


Go to your content type you feed and click on "Manage Display". There you have different possibilities to change the way how your content looks in different view modes. You probably need to activate the view mode for RSS Feeds to change anything.


How can i check if css class exists on page and add new one to the body

function mytheme_preprocess_html(&$vars) {
  $vars['classes_array'][] = 'new-class';
}

or

if ($('body.mydivclass').length > 0) {
  $('body').addClass('new-class');
}


Manually adding sdk for AWS SDK PHP Module

Assuming you have git installed, you should be able to run the following from within your /sites/all/libraries directory:

git clone git://github.com/amazonwebservices/aws-sdk-for-php.git awssdk

Alternatively, you could use the Zip button on the Github project page or the link it points to to download the zip file and put it in a subdirectory of libraries directory called awssdk.


Why the core migrate modules won't be enough?

This is asking two questions. 1) What do I need beside core for migrating to D8 from D7. 2) What is Drupal Upgrade.

If all your fields and data in D7 are core fields, then you do not need anything from contrib. If you have non-core fields i.e. userpoints, then you'll need source and destination migrate plugins for those non-core field types. Same applies to any non-core Drupal data.
Core does not currently have a UI. It is in the works, but until then if you want a UI, use Drupal Upgrade. Or you can use drush and migrate_tools. Mike Ryans's blog post provides a  break-down of the current module landscape for D8 migrations.

Lastly, if you are trying to suck in strait SQL data, the above mentioned blog post provides some suggestions.

  In migrate_plus, open up migrate_example/README.txt and it will guide
  you through the basics of implementing SQL-based migrations. It's
  simpler than you think!


Lots of 500.shtml page not found errors in logs

The 500 error page is show when the server has an internal error.

Your server is looking for a file named 500.shtml because a directive set that as the page that must be shown when the server has an internal error. The .htaccess file used by Drupal set the page for the "page not found" error to /index.php with the directive ErrorDocument, but it doesn't set any error page for any 500 codes, which is the set by the server using a different file; for Apache, this means the access.conf file, or any files included by that file.

For what can cause an internal error, it could be a server directive, or a wrong argument passed to such directives. Other causes could be:

directory permissions
file permissions
a wrong transfer mode used when transferring the Drupal PHP files to the remote server when using FTP
the line endings of the files that don't match the one used from the Operating System that is hosting the server


Take a look at Apache Solr View Count module which does exactly the same.

  This module allows you to index the node view count to Apache solr
  index as a custom field and let you sort SOLR results. The module
  requires Apache solr search module.

Disclosure: I'm one of the module maintainer.


Automatic nodetitles and location tokens?

I have taken some good looks at your issue.
At the moment I find that the code for Location CCK is problematic, I managed to make it work with the following modification:

diff --git a/contrib/location_cck/location_cck.module b/contrib/location_cck/location_cck.module
index b302960..443b6a0 100644
--- a/contrib/location_cck/location_cck.module
+++ b/contrib/location_cck/location_cck.module
@@ -657,9 +657,9 @@ function location_cck_tokens($type, $tokens, array $data = array(), array $optio
   $replacements = array();

   // Make sure we have a node.
-  if (isset($data['entity_type']) && $data['entity_type'] == 'node') {
+  if ($type == 'node') {

-    $node = $data['entity'];
+    $node = $data['node'];

     // Get the available fields from the location module.
     $available = location_field_names(TRUE);

The token that worked after this patching was specific to the CCK field I added to my content type:

[node:field_my_location_field:city]

Alternatively, for your goal "...to have automatic node titles taken from user contributed content...", you can use the Node Locations submodule, this works as expected out of the box. The following tokens

[node:location:city]
and
[node:location:city:0]

both worked fine in combination with Automatic Nodetitles.

Hope this helps!


AJAX doesn't work for "flag" field print in node.tpl

It might be too late to add the required JS in the node template.
Try adding your flag link to hook_preprocess_node in template.php instead.

e.g

function MYTHEME_preprocess_node(&$vars){
  $vars['flag_link'] = flag_create_link('prova', $vars['node']->nid);
}

then in your node template

<?php print $flag_link; ?>


How to debug why some content is not migrated from D7 to D8?

This issue was due to not factoring in languages when migrating.
So if you have the same issue you'll probably need to look at your i18n migrations.


I've used this code and worked fine:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['submit']['#value'] = 'CUSTOM BUTTON VALUE';
    //dpm($form);
  }
}


Whether or not a page is cacheable is determined by drupal_page_is_cacheable().

Set a breakpoint there and dig into call stack / step through the conditions to determine the reason why nothing is saved to the cache_page bin.

Also take a look at drupal_page_footer() which calls into drupal_page_set_cache() in order to store the built page in the page cache.


prevent script to run twice after 2 ajax loads

I figured it  out. The wrong code came out of misunderstsatnding .once function. "nav" means a class that the selector #colorbox #block-book-navigation would be marked, so code is not fired multiple times on that selector.
http://codekarate.com/blog/drupal-7-prevent-duplicating-javascript-behaviors
Correct code should be:

(function ($) {
  Drupal.behaviors.myCustomJS = {
    attach: function(context, settings) {
      $('#colorbox #block-book-navigation').once('nav', function() {

        $("#colorbox #block-book-navigation a").each(function(){
            $(this).addClass("colorbox-node");

       });

      });
    }
  };
})(jQuery);


How do I check the content type of a file using hook_file_presave

The file itself has no reference to the parent node (it can be referenced by multiple entities). But you can get the node type you are adding or the node you are editing when you upload the file from the route:

function modulename_file_presave(\Drupal\file\FileInterface $file) {
  if ($file->getMimeType() == 'image/jpeg') {
    switch (\Drupal::routeMatch()->getRouteName()) {
      case 'node.add':
        $content_type = \Drupal::routeMatch()->getRawParameter('node_type');
        break;

      case 'entity.node.edit_form':
        $node = \Drupal::routeMatch()->getParameter('node');
        $content_type = $node->getType();
        break;

      default:
        $content_type = NULL;
    }
  }
}


How to restrict tagged content based on user?

Seems like using the Taxonomy Access Control module is the most straight forward solution to answer your question. Some details about this module (from its project page):

Access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.

Together with using this module, you should also define 3 roles, i.e.:

Lead, granted to any user considered as "Lead".
Worker, granted to any user considered as "Worker".
Manager, granted to any user considered as "Manager".

With those roles and permissions in place, you have everything to configure your access rules as provided by the Taxonomy Access Control module.
PS: note that this has nothing to do with content type "Person" (as in your question). Not sure why you need/use that content type, but to get the above to work you don't need that.


How to embed HTML and CSS in a custom form element?

Markup strips away some tags and attributes. Here is a way to do it.

Add a class to your form

$form['#attributes']['class'][] = 'crisis';

Add css rule to your theme's css

.crisis {
    display: none;
}

if you do not have a library and a .css file to use, you need to create them. Define a library in your theme or module in your THEMEorMODULE.libraries.yml

crisis:
  version: 1.x
  css:
    theme:
      css/crisis.css: {}

create css/crisis.css file and put your css rule(s) in it

and attach the library to your form

$form['#attached']['library'][] = 'THEMEorMODULE/crisis'

and clear cache

NOTE: The above (pseudo)code is not tested.  For more information please have a look here


@sonfd Xdebug helps print out the values beautifully. No more print_r() or kint() errors.


Exposed filter : search term with select which 'field' to search by

I have created a custom module inspired by your question. You can find it here

It is not created/approved as a full project on Drupal.org. But it will approved soon. Download the module, enable it. Under filter add a filter that says Exposed fields Filter then select the fields you want to expose to visitors. Only those field will appear to visitors which you select here.

I hope it helps you for now.


You can actually disable user's ability to provide summary. I found this while pursuing the first solution:

Administration » Structure » Content types » Basic page

you should see "Manage Fields" tab. Click on it, and you should see a table. The row for Body should show Widget Type as "Text area with a summary" which is a link that allows you to edit it.

Rather than changing the Widget Type which is not possible if you already have one or more entries, go to the "Edit" tab.

About half-way down the tab is a checkbox: "Summary input"
("This allows authors to input an explicit summary..."). Uncheck it, and save. Your content edit page for Basic Page should be free of "Edit summary" options.


custom module to create multiple forms with pop-ups

You are partial on the right path, I would suggest following a guide like https://www.deeson.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7 and then work your way towards what you need based on that.


How do I put the user registration form on my front page?

You just need to add a "New custom content" to a panel pane and add the following code to the body (you need to have PHP format selected):

<?php

if(user_is_anonymous()) {
  $form = drupal_get_form('user_register_form');
  print drupal_render($form);
}

?>

It works :)


Are you retrieving that form via AJAX ? Then you get the HTML, but in your page is not present the JavaScript/CSS files. You need to add them before, so they are ALREADY present in whatever page the block is placed.


Attaching below code:

custom.module

<?php

use Drupal\Core\Form\FormStateInterface;

function custom_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    if ($form['#id'] == "YOUR_FORM-ID") {
      $form['combine']['#autocomplete_route_name'] = 'custom.autocomplete';
      $form['#attached']['library'][] = 'custom/custom';
      $form_state->setCached(FALSE);
    }
  }
}

custom.routing.yml

custom.autocomplete:
  path: '/want/autocomplete'
  defaults:
    _controller: '\Drupal\custom\Controller\WantAutoController::autocomplete'
  requirements:
    _permission: 'access content'

custom.libraries.yml

custom:
  version: 0
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery

js/custom.js

(function ($) {
    Drupal.behaviors.custom = {
        attach: function (context) {
            $("#FIELD-ID").autocomplete({
                select: function (event, ui) {
                    if (ui.item) {
                        var itemLink = $(ui.item.label).attr('href');
                        window.location.href = itemLink;
                    }
                }
            });
        }
    };
}(jQuery));

src/Controller/WantAutoController.php

<?php

namespace Drupal\custom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Returns tree responses for nodes.
 */
class WantAutoController extends ControllerBase {

  function autocomplete(Request $request) {
    $db_conn = \Drupal::database();
    $matches = [];
    $string = $request->query->get('q');
      $alias = \Drupal::service('path.alias_manager');
      $db_conn = \Drupal::database();
      $query = $db_conn->select('node','n');
      $query->leftJoin('node_field_data', 'nfd', 'nfd.nid = n.nid');
      $query->fields('n');
      $query->fields('nfd',['title']);
      $result = $query->execute()->fetchAll();
      if ($results) {
        foreach ($results as $row) {
          $path = $alias->getAliasByPath('/node/' . $row->nid);
          $linkTonode = '' . $row->title . '';
          $matches[] = ['value' => $row->title, 'label' => $linkTonode];
        }
      }
    return new JsonResponse($matches);
  }

}

Here in the autocomplete we are building value with "a" tag. And while searching autocomplete field our autocomplete return with "a" tag also. We are also building js here to click on that value and redirect.


Entity view displays are throwing dependency errors during installation

No, removing the dependencies is not the solution.

As I said in my comment, automatically doing something when config is installed or imported is an anti-pattern that should be avoided when possible.

Just create all the config through config/install and don't trigger automatically creating displays through pre/post save hooks/methods and your problems should go away.


Views maybe isn't the best solution to your problem. Drupal has a built in way to create menus. When you created your two menus and maybe placed them on your site with Menu Block, you then may apply the flyout functionality with CSS or jQuery or have a look at Superfish maybe.


There isn't an interface to change this, but you can do it by importing a config file. You need to get a hold of contact.settings.yml file. Default looks something like this:

default_form: feedback
flood:
  limit: 5
  interval: 3600
user_default_enabled: true

You can see the flood limit and interval which you can change and then import the file using the config management system.


Set value for start/end date field labels in hook_form_alter

Something similar to below might help,change combo field title from 'to:' to none:

function mymodulename_date_combo_process_alter(&$element, &$form_state, &$context) {
    $element['value2']['#title'] = t('');
}

To change From and To date field labels,implement

function mymodule_date_part_label_date(&$vars) {
    if ($vars['element']['#field']['field_name'] == 'yourfield_machine_name') {
      if ($vars['element']['#date_title'] == 'Date Start date') {
        return t('Date (From:)');
      } elseif ($vars['element']['#date_title'] == 'Date End date') {
          return t('Date (To:)');
        }
    } else {
        return t($vars['element']['#date_title']);
    }
}


How to add a RSS Feed to a solr search view in drupal 7?

as a temporary solution I created a new view with the same content added a rss feed to that. now I do have a rss feed but not on the page I want it to be.

I'll accept this answer until a better one shows up.


How to access variables in a fieldset with variable_get

Since you are setting #tree to TRUE, the values will be saved in the bi_mx_enhancement_government_ws persistent variable, which will contain an array. For the code you are showing, its value will be similar to the following one.

array(
  'base_url' => 'https://'
);

Instead of variable_get('base_url', 'https://'), consider using the following code.

$values = variable_get('bi_mx_enhancement_government_ws', array());
$ws_base_url = $values['base_url'];

When you are now using variable_get('base_url', 'https://'), you should use $ws_base_url.

Since you seem to just use a single setting for that fieldset, I would rather use '#tree' => FALSE, if that form doesn't have any other form field which is using base_url as identifier.


You can use the following modules

Context : It allows you to highlight a menu item if certain condition has been met.
Menu position : This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

Reference:

Menu Position


Moving Exposed Views Filter into another region of the page

There is a module called 'Views Better expose filters' which allows you to create blocks from view exposed filters.

Project can be found at: http://drupal.org/project/better_exposed_filters
or
drush dl better_exposed_filters; drush en better_exposed_filters

There is also some excellent documentation at http://drupal.org/node/766974


Fields pending deletion error when disabling comment module

You probably did some batch operations or import. Running cron could solve the issue, or run the following command in drush:

drush php-eval 'field_purge_batch(1000);'

Change the '1000' value to larger numbers if you did for example an import of more nodes.


Use Firebug to inspect the generated HTML to get the block name|module !


I think the easiest way to create this in views will be to just manually read it and re-create using the views UI.


How to create a single page using Drupal Commerce containing product, billing infor payment method?

The checkout flow uses panes, and there is nothing hindering you to put all of the panes in a single page and skip the review page if you wanted to. This can be setup in the checkout settings with a simple drag and drop interface. Should be fairly simple to setup the way you want to out of the box.


I haven't tried to do exactly this before but something tells me it would be tricky. This is from the Batch docs:

The API is primarily designed to integrate nicely with the Form API workflow, but can also be used by non-Form API scripts (like update.php) or even simple page callbacks (which should probably be used sparingly).

I remember trying to set batches outside of a form context before and always resorted back to using a form as I could never get them to work.

You might have more joy than me though so you could try simply doing a batch_set in the finished callback like you suggest. Assuming you're adding some data to the $context variable in your first batch's callback function (such as the node ID) you should be able to pick that context data up again in the finished callback and pass it though to your second batch's setup function.

Hope that makes sense!


Store custom messages displayed by \Drupal::messenger()->addMessage() in the database

The first thing to determine is whether you need your messages to be content or configuration. Content is (usually not) migrated between environments. It is created on an environment, and is unique to that environment. So your development environment may have one set of messages used for testing, and your production environment has another set of messages, used live.

Configuration on the other hand is migrated between environments. So you would create the messages on one environment, and when configuration is exported from that environment, the existing messages would be included in that export.

You probably want content entities.

How to create a new content entity type: https://www.drupal.org/docs/8/api/entity-api/creating-a-content-entity-type-in-drupal-8

How to create a new configuration entity type: https://www.drupal.org/docs/8/api/configuration-api/creating-a-configuration-entity-type-in-drupal-8

If you create a new content entity type, give the entity two fields, message_key and message_value. You will then load the entity as follows:

$entity = \Drupal::entityTypeManager()->getStorage('my_entity_type_id')->loadByProperties([
  'message_key' => $message_key,
]);

$message_value = NULL;
if ($entity) {
  $message_value = $entity->get('message_value')->value;
}

If you create a configuration entity, the ID of the entity will be the message key, and the entity only needs one more field for message value. The code above would be adjusted slightly:

$entity = \Drupal::entityTypeManager()->getStorage('my_entity_type_id')->loadByProperties([
  'id' => $message_key,
]);

$message_value = NULL;
if ($entity) {
  $message_value = $entity->get('message_value')->value;
}

The entity type you choose will become the storage mechanism for your messages, which you can then recover with the above methodology. Don't run $message_value through the t() function, as variables should not be run through that function, and translations of the message values are handled as translations of the entity, rather than the t() function.


Implementing Taxonomy hierarchy in View and Search

I would look into using Search API for this and build up facets using the Facets API.

Once you have Search API installed you need to create a search index, choose which fields to index and what facets to create.

With the search index in place you can from Views create a Search view that uses your index as base.

Place the facets where you want them and tell them to show up at your search views url.

There is a guide that explains how to setup Search API here. In the guide they use Apache Solr as backend for the search index. That is not necessary, you can use the database as backend but I recommend using Apache Solr as backend as I've stumbled on a few bugs in the database backend which work with Solr.

You would be able to do searches such as this:

Good luck


How to alter commerce order view access?

You should be using hook_commerce_entity_access_condition_ENTITY_TYPE_alter() for commerce orders.

You receive the following parameters:

$conditions: The OR conditions group used for the view access query.
$context: An array of contextual information including:

account: the account whose access to view the entity is being checked
entity_type: the type of entity in the query
base_table: the name of the table for the entity type

So it becomes:

hook_commerce_entity_access_condition_commerce_order_alter(&$conditions, $context) {
  // If we are not allowed to view the order, leave.
  if (!user_access('some_permission', $context['account'])) {
    return;
  }

  $orders = array(99);

  // add a condition
  $conditions->condition(db_and()
    ->condition($context['base_table'] . '.order_id', $orders, 'IN')
  );
}


How do i add custom jquerry script to omega theme?

There are (at least) two ways to add a JavaScript file to an Omega subtheme. The Omega Theme Documentation Handbook adds it as a library that can then be toggled on in the theme settings. I tend to use drupal_add_js, with a slight workaround to point it to the subtheme (more about why that's necessary in the Docs issue queue).

As a library

First, add the file to a js folder in your theme. The path to mine was sites/all/themes/webbykat/js/webbykat.js.

Second, add a reference to the new file in your theme's .info file. During this step, you'll also add some identifying information for your new file, like a name and a description, as well as its weight. Here's what mine looked like:

libraries[MYTHEME_custom][name] = Some custom name
libraries[MYTHEME_custom][description] = Some custom description
libraries[MYTHEME_custom][js][0][file] = script.js
libraries[MYTHEME_custom][js][0][options][weight] = 15

Be sure to clear your cache after you update your .info file.

Please note: If you're adding more than one file, you'll need to up that number for each file - libraries[MYTHEME_custom][js][0][file] = script.js and then libraries[MYTHEME_custom][js]3[file] = secondfile.js. Be sure to adjust it next to the weight as well. (Thanks, Screenack, for pointing that out in the
comments.)

Third, now that the Omega theme is aware of your new file, formally inform Omega that you'd like to use it. Under Appearance > Settings > [Theme name],  go to the Toggle libraries tab. Check the box next to the name of your file. Save.

With drupal_add_js

In template.php, you might think you could use drupal_add_js to add it like this:

function MYTHEME_preprocess_page(&$variables) {
  drupal_add_js(path_to_theme() . '/js/script.js');
}

However, path_to_theme doesn't reference the active theme (more on that here), so we need a slight workaround. Instead, use the following:

function MYTHEME_preprocess_html(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/js/script.js', array(
    'scope' => 'header',
    'weight' => '15'
  ));
}

Scope tells the function that the file should be called in the header or footer, and the weight tells it what order it should be called in relative to other files.

I prefer the two methods above because one is featured in the Omega documentation, and the other allows you to control what pages the JavaScript is called on if you want to (post on that to come). But as a developer friend pointed out, if you just want something quick and dirty to get a JavaScript file called on every page of your site, scripts[] = js/script.js in the .info file works too.

Source


How can I exclude some entities in "drush entity:delete" command?

ok mate you want other options and here is the answer:

if you look at

vendor/drush/drush/src/Drupal/Commands/core/EntityCommands.php

you can see the what the function does....

now you need to learn how to make a custom drush commands i assume you are using drush 9  so you can just run:

"drush  generate drush-command-file"

or read: https://www.axelerant.com/resources/team-blog/how-to-write-custom-drush-9-commands-for-drupal-8

this will create:
modules/custom/YOURMODULE/drush.services.yml
and
modules/custom/YOURMODULE/src/Commands/YOURMODULECommands.php

now have a look at the following working example ...

<?php
/**
 * Command delete some stuff
 *
 * @param $entity_type
 *   Argument for entity type.
 * @param $exclude
 *   Argument for exclude delete of ids.
 *
 * @param array $options
 *   An associative array of options whose values come from ...
 *
 * @option option-name
 *   Description
 *
 * @usage deletethings-commandName foo
 *   Usage description
 *
 * @command deletethings:commandName
 * @aliases delete-my-stuff
 */
 public function commandName($entity_type, $exclude,  $options = ['option-name' => 'default']) {
$this->logger()->success(dt($entity_type));
$this->logger()->success(dt($exclude));
$exclude_ids= [];
if ($exclude !== 'none') {
  $exclude_ids = explode(',', $exclude);
}

// now do the delete stuff
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
if (is_object($storage)) {
  $all = $storage->loadMultiple();
  if (count($all) !== 0) {
    foreach ($all as $entity) {
      $id = $entity->id();
      if (!in_array($id, $exclude_ids)) {
        // kill with fire.
        $entity->delete();
      }
    }
  }
}
}

With that you can run:

drush  delete-my-stuff ENTITY_TYPE 5,6,10

example: drush  delete-my-stuff node 5,6,10

this would then allow you to delete all items of your entity except for "5,6,10" - which are ids you want to keep

or drush  delete-my-stuff ENTITY_TYPE none (to delete all)

remember to run drush cr and drush cc (1) so drush will recognise the new command


Force render the block programmatically?

Not sure what version of Drupal you are using but here is how I rendered a block in drupal 7.

<?php
  $block = block_load('MODULE_NAME', 'DELTA');
  $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
  print $output;
?>


This will be done by hook_menu, See the example below for creating tabs (MENU_LOCAL_TASK). This is how tabs will be created.

    // For the default local task, we need very little configuration, as the
  // callback and other conditions are handled by the parent callback.
  $items['examples/menu_example/tabs/default'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'title' => 'Default primary tab',
    'weight' => 1,
  );
  // Now add the rest of the tab entries.
  foreach (array(
    t('second') => 2,
    t('third') => 3,
    t('fourth') => 4,
  ) as $tabname => $weight) {
    $items["examples/menu_example/tabs/$tabname"] = array(
      'type' => MENU_LOCAL_TASK,
      'title' => $tabname,
      'page callback' => '_menu_example_menu_page',
      'page arguments' => array(t('This is the tab "@tabname" in the "basic tabs" example', array('@tabname' => $tabname))),
      'access callback' => TRUE,

      // The weight property overrides the default alphabetic ordering of menu
      // entries, allowing us to get our tabs in the order we want.
      'weight' => $weight,
    );


White screen of death: Fatal error: Allowed memory size of X bytes exhausted

I know this may be late, but it helped me. Most times a module causes WSOD, I couldn't just disable modules to test which it was, since I may have lost data in the process. What I did was to temporarily edit this function in module.inc, in the core includes directory

function module_invoke_all($hook) {
  $args = func_get_args();
  // Remove $hook from the arguments.
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {

        print "Starting loading $module
";

        $function = $module . '_' . $hook;
        if (function_exists($function)) {
          $result = call_user_func_array($function, $args);
          if (isset($result) && is_array($result)) {
            $return = array_merge_recursive($return, $result);
          }
          elseif (isset($result)) {
            $return[] = $result;
          }
        }

        print "Finished loading $module
";

  }

  return $return;
}

And I added those 2 print statements in the code above, then refresh the page, the module which didn't reach the "Finish loading $module" statement is the one with the problem... it was devel in my case.

After finding the module, you can go into the system table and look for that module, set it's status = 0 and bootstrap = 0 or run the query:

UPDATE system SET status = 0, bootstrap = 0 WHERE name = 'module_name' LIMIT 1

Reference: Debugging Drupal White Screen of Death (WSOD)


Show Taxonomy Terms belonging to search_api search result nodes

This may have drawbacks but I had a situation where i wanted to show the multiple tags that related to content that i had indexed.

Having looked through https://www.drupal.org/node/1378656 i opted to try by using https://www.drupal.org/project/views_field_view

Happy to report it worked

Here is the recipe:

create a new View based on Content for types involved and set just the relevant 'term' field as the display (you don't need to create any views displays).
set Contextual filter to nid with 'provided default value = raw value from url' (outcome should be if you enter the nid you should see relevant tags in preview). Save
install/enable https://www.drupal.org/project/views_field_view
over in the view that is rendering the search results (searchapi)
made sure you have Indexed Content: Node ID field already in your Fields, and set to not display
add a new field of type Global: View
in the 'view settings' of this field, find the view you made above, set the right display or use Master if you didn't make any (because you didn't need to),
in Contextual Filter, check your Replacement Patterns where you should have [%nid] == Indexed Content: Node ID (rendered), and enter [%nid]
save and I hope you get to smile like i just did.


How do I create templates in my custom module?

hook_theme is your friend, it allows you to modularize your markup in two ways:

Allows you to define a template file for your markup.
Allows you to define a theme function.

No matter which way you go, you will call for the markup the same way. so lets say you wish to modularize markup for recent activity. You will do the following in your custom module:

function custom_module_theme() {
   return array(
     'activity' => array(
       'variables' => array('variable1' => NULL, 'variable2' => NULL),
       'template' => 'custom-module-name-recent-activity',
     ),
   );
 }

You will create custom-module-name-recent-activity.tpl.php in your module directory where you will have $variable1 and $variable2

Your custom-module-name-recent-activity.tpl.php will look something like this:

 <?php print $variable1; ?>

 <?php print $variable2; ?>

And then from your module when you have done your processing and have established $variable1 and $variable2 (you can pass as many as u want), you will simply do:

theme('activity', array('variable1' => $variable1, 'variable2' => $variable2));

Hope this helps, I wonder now if I should have linked to some tutorial. But hey its Saturday :)

(And if you are using Drupal 6, change 'variables' to 'arguments' in the code above.)


You could use the core Statistics module as described here.

You could use Visitors module.

I use Google Analytics but this might be too heavy if you need a basic solution.


How do I pass the language through ajax request

You will need to change the URL of your AJAX call to include the language prefix. So this:

url: "/gallery/view",

Will be this:

url: "/ja/gallery/view",


I decided to bite the bullet and run everything with Batch API. This meant the site was painfully slow for probably 2-3 hours, then slow for another hour or so. The profile type deletions became faster as there were fewer left to delete (since cache rebuilds were less intense the fewer field instances that were required).

I set up the batch using something like the following:

// You can remove the limit if you want, but this is a very long operation,
// so it's nice to do it in smaller chunks during traffic lulls.
$types = db_query("SELECT type FROM {profile_type} LIMIT 100")->fetchCol();
$batch = array(
  'operations' => array(
    array('mymodule_bulk_delete_profile_types', array($types))
  ),
  'finished' => 'mymodule_bulk_delete_profile_types_finished',
  'title' => t('Removing Profile Types'),
  'init_message' => t('Beginning profile type deletion...'),
  'progress_message' => t('Deleting profile types...'),
  'file' => drupal_get_path('module', 'fn_profile') . '/includes/fn_profile.utility.inc',
);
batch_set($batch);
batch_process();

Then, I had two batch callbacks (the processing function and the finished function), like so:

function mymodule_bulk_delete_profile_types($types, &$context) {
  $context['finished'] = 0;

  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($types);
    $context['results']['count'] = 1;
  }

  if (!isset($context['sandbox']['types'])) {
    $context['sandbox']['types'] = $types;
  }

  $key = $context['results']['count'] - 1;
  $type_to_delete = $context['sandbox']['types'][$key];
  $profile_type = profile2_get_types($type_to_delete);
  profile2_type_delete($profile_type);

  $context['results']['count']++; // Increment the counter.
  $context['finished'] = $context['results']['count'] / $context['sandbox']['max'];

  // Show message updating user on how many profile types have been deleted.
  $context['message'] = t('Deleted @count of @total profile types.', array(
    '@count' => $context['results']['count'],
    '@total' => $context['sandbox']['max'],
  ));
}

function mymodule_bulk_delete_profile_types_finished($success, $results, $operations) {
  // Display any warnings.
  if (!empty($results['warnings'])) {
    foreach ($results['warnings'] as $warning) {
      if ($warning) {
        drupal_set_message($warning, 'warning');
      }
    }
  }
  // Set operation successful message.
  if ($success) {
    if ($results['count'] == 0) {
      $message = t("No profile types were deleted.");
    } else {
      $message = t("@count profile types deleted successfully.", array('@count' => $results['count']));
    }
  } else {
    $message = t("There were problems deleting profile types.");
  }
  drupal_set_message($message, 'status');
}

At the beginning, it was taking between 50 seconds and 80 seconds to delete a profile type. Towards the end of the batch, it was only taking about 20-30 seconds. The site now only uses about 30-40 MB (according to devel.module) when clearing all caches; it was using about 190 MB before, and taking over 2 minutes to rebuild the caches!


How to use ungrouped date fields as data for Charts Views?

I found a partial workaround for this by using hook_views_pre_render.

function hook_views_pre_render(&$view) {
   if($view->name == 'stuff'){
      $results = &$view->result;
      foreach ($results as $key => $result) {
      $now = time();
      $end = strtotime($result->field_field__end_date_[0]['raw']['value']);
      $daysuntil = date("j", $end-$now);
      $result->field_field_end_date[0]['rendered']['#markup'] = $daysuntil;
     }
   }
}

The previous function is  for a chart that displays node serials as x-axis labels and number of days for yaxis, which is calculated as the difference  between now and a end date.


RSS item elements not being not being read by XML Reader

After some research i did manage to find my way out:
I implemented hook_views_rss_namespaces to add a custom namespace and the custom items under the namespace:

function Mymodule_views_rss_namespaces() {
  $namespaces['blogs'] = array(
  'prefix' => 'xmlns',
  'uri' => 'http://base.google.com/ns/1.0',
);
return $namespaces;
}

Note: Use the same 'prefix' and 'uri' as given in the above code or else namespace uri error will arise.


For precise control over views markup I usually take a departure from typical Drupal methods.   I set the view to be a table format,  then create my own view template.  The reason I use the table format is that it's really easy to work with and has a simple loop through each row of the results returned from the view.   From there, you can create your own markup using just the field values from each row.

Check this link:
https://api.drupal.org/api/views/theme!theme.inc/group/views_templates/7

Here's some shortcuts to get you started quickly. In your theme's directory, create a file called:
views-view-table--NAME-OF-YOUR-VIEW.tpl.php

Inside that file, start by pasting the source from this (click View source on the page):
https://api.drupal.org/api/views/theme!views-view-table.tpl.php/7

Then, clear your site's cache. Your view will now be using that new template and you can edit as required.


How do i get the node id using menu_hook

Although you pass a node id into the url, it get's converted to a fully loaded node by the time your callback function is called. You could read up on it on the documentation page for hook_menu, under section Auto-Loader Wildcards.

In node.module you will see this menu item for node edit:

$items['node/%node/edit']

Now, the path you are trying to register already exists in the node module, so that is where the WSOD comes from. You need to do a hook_menu_alter on it, or perhaps hook_form_alter if all you want to do is alter the node edit form.


Go to admin/structure/menu/manage/management; you'll see all the links currently in the menu.
Click "Add link"
Fill in the title, path and any other relevant data.
Click "Save"
Re-order the menu items if necessary
Repeat the process for as many links as you need to place under the new top-level item you just created.
If you're using the Admin Menu module, you might need to flush caches before changes take effect (but you might not).


Making responses to public nodes only viewable by the creator and the originator

A quick search on D.o. came up with this forum post asking to do the exact same thing: http://drupal.org/node/919914

They suggest using Node Comment and Content Access together to achieve it, but I'm not certain Content Access will give you the specific option you're looking for.

It would be a start though, and you might be able to hook into Content Access and create a new "Parent Node author" or similar option if you are up for a coding session.


How to pass multiple objects to hook_view()?

hook_load() gives you the node that was just loaded. The reason it gives you the node is so that you can modify it. So you'd do something like $node->myModule['colors'] = array ( some colors here... ); Read up on the API documentation.

See also the API docs for hook_view().

If you move on to Drupal 7, you can do all this stuff as fields. :-)


Showing both original base price and calculated price (inc. taxes), when using two price fields and rules

I have been thinking of this, but can you delay the setting of the price?

I suppose you are currently overwriting the price when the user is viewing the node? Can't you set the correct price when the product is added to the cart? That would allow you to show both prices next to eachother.

Optionally if you don't want regular users to see the wholesale price, use a module like Field Permissions to prevent certain roles from viewing certain fields.


How to add classes to image fields set to Unlimited and a "rel" attribute to the  tag that wraps them

Don't you want to use a module like Views Slideshow: Dynamic Display Block to produce what you're looking for ?

If not you should create a specific template for your field using a name like field--field-name.tpl.php (Drupal 7 Template Suggestions), put it in you theme folder and customize it.

You can use theme_imagecache() if you're on Drupal 6 or theme_image_style() on Drupal 7.

$img = theme('image_style',
             array('style_name' => 'thumbnail',
                   'path' => $content['field_image'][0]['#item']['uri']
                  ));

Then you wrap your images in a using l():

$attributes = Array('rel' => 'rel_text');

echo l('yourpath', $img, array('html' => TRUE, $attributes));


How to pass argument in service with dependency injection

While it would not be possible to use the http_client service it is possible to use the factory service (or create your own factory service if you choose not to rely on core methods).

The http_client_factory service provides a fromOptions method.

The Symfony2 documentation has a section on using parameters:

  Use the parameters section of a config file to set parameters:

parameters:
  mymodule.http_client.config:
    base_uri: 'http://httpbin.org'

services:
  mymodule.http_client:
    factory: '@http_client_factory:fromOptions'
    arguments: ['%mymodule.http_client.config%']
  mymodule.mymodule_call:
    class: Drupal\mymodule\MyModuleCall
    arguments: ['@mymodule.http_client']

Now the MyModuleClass will use Guzzle with Drupal's default configuration and custom configuration.

Note: it is also possible to provide your own factory service for Guzzle and to use that directly. This would be useful if you need to use your own overridden Guzzle\Http\Client class (I do this in a contrib module). This would probably be necessary to inject custom configuration such as handler stack (OAuth1).


Alternative ways to programmatically add user fields?

I found a solution using .yml files in your modules config/install directory.

1. Create the user field

go to Configuration -> People -> Account Settings -> Manage fields and press "+ Add field". I'd recommend giving the field a unique machine-readable name to prevent conflicting user fields.

Enable the user field in Manage Form Display and Manage Display if you want it to appear in the users edit profile and registration page.

2.Exporting the user field configuration

go to Configuration -> Development -> Configuration Synchronization -> Export -> Single Item

Once you get to a screen similar to the one below, set configuration type to "Field" then set the configuration name to the field you have created.

In your modules Config/install folder(create one if needed) create a new file named after filename highlighted in red below.

Finally Copy the yml text into the file you just created.

then set configuration type to "Field Storage" then set the configuration name to the user field you have created.

In your modules Config/install folder(create one if needed) create a new file named after filename highlighted in red below (don't copy the one in the example your user field will have a different name).

Finally Copy the yml text into the file you just created.

YOU NEED BOTH YML FILES TO PROGRAMMATICALLY CREATE A USER FIELD

I recommend doing this for each user field you want to programmatically add rather than copying the configuration and changing a few properties.

With this method you can uninstall the module that created these user fields.


Programmatically translate a string in hook_update_N()

Yes, you can check in the locale module how it's done and replicate to use the same queries like this :

/**
 * Translating some pagination strings.
 */
function hook_update_XXXX() {
  $translations = array(
   'last' => array(
     'fr' => 'dernière page',
     'en-en' => 'last',
   ),
   'first' => array(
     'fr' => 'première page',
     'en-en' => 'first',
   ),
 );

 foreach ($translations as $string => $values) {
   $source = db_query('SELECT lid, source, context, textgroup, location FROM {locales_source} WHERE source = :string', array(':string' => $string))->fetchObject();
  if (!$source) {
    watchdog('update_hook', 'Translation of string "%string" failed.', array('%string%' => $string));
    continue;
  }

  foreach ($values as $langcode => $translated) {
    $translation = db_query('SELECT translation FROM {locales_target} WHERE lid = :lid AND language = :language', array(':lid' => $source->lid, ':language' => $langcode))->fetchField();
    if (is_string($translation)) {
      db_update('locales_target')
      ->fields(array('translation' => $translated))
      ->condition('lid', $source->lid)
      ->condition('language', $langcode)
      ->execute();
    }
    else {
      db_insert('locales_target')
      ->fields(array(
        'lid' => $source->lid,
        'translation' => $translated,
        'language' => $langcode,
      ))
      ->execute();
      }
    }
  }
}

I'm using such code to update strings in code instead of having to this manually when deploying code. So a simple "drush updb" can do the job for me.

OR as I've found out recently, a faster version exists like this :

/**
 * Translating some strings.
 */
function hook_update_X() {
  $report = array(
    'skips'=> 0,
    'updates'=> 0,
    'deletes'=> 0,
    'additions'=> 0
  );

  // Translate strings.
  _locale_import_one_string_db($report, 'fr', '', 'Your shipping address book is currently empty.', 'Votre carnet d\'adresses de livraison est actuellement vide.', 'default', '', LOCALE_IMPORT_OVERWRITE);
  _locale_import_one_string_db($report, 'fr', '', 'Your billing address book is currently empty.', 'Votre carnet d\'adresses de facturation est actuellement vide.', 'default', '', LOCALE_IMPORT_OVERWRITE);

  // Clear locale cache.
  cache_clear_all('locale:', 'cache', TRUE);
}

For Drupal 8, please see this answer : https://drupal.stackexchange.com/a/220608/61138


Attachment node field vs. file fields in a content view

If I drop the relationship, I found that changing the file formatter to 'table of files' shows the size column. Magic. Gives me 98% of what I want, so I'm happy enough.


How to prevent the conversion of text URL to link on a single URL?

The only way I think it is possible to selectively disable the "Convert URLs into links" filter is to use CSS and add something like below to the body. Since CSS is applied client-side after Drupal has returned the page, the filter is effectively disabled for this one single link.

blah

Since you are using the 'Full HTML' format, you should be able to add CSS directly into the body field like shown.


When a variable parameter is changed in a Rules loop, the variable is unchanged outside the loop

Have a look at this example of a Rule (in Rules export format), which is a variation of what you're asking for:

{ "rules_show_list_of_fields" : {
    "LABEL" : "Show list of fields",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "StartOfList-" },
          "PROVIDE" : { "variable_added" : { "email_list" : "List of eMail IDs" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email" : "Current eMail" },
          "DO" : [
            { "data_set" : {
                "data" : [ "email-list" ],
                "value" : "[email-list:value][current-email:value]-"
              }
            }
          ]
        }
      },
      { "data_set" : { "data" : [ "email-list" ], "value" : "[email-list:value]EndOfList" } },
      { "drupal_message" : { "message" : "The value of the email_list variable is: [email-list:value]." } }
    ]
  }
}

Here is a summary of what this rule does:

Add a new variable email_list.
Init the email_list value with some prefix.
For each item within the loop, append the value of that item, followed by a separator character.
Add a suffix to the email_list value.

In my case I'm using a multi value text field with machine name field_email_addresses, which contains eMail Ids, and just want to dispay a Status message with a concatenation of those eMail IDs, separated by a "-", and with a prefix (=StartOfList) / suffix (=EndOfList). And I also use Rules Events "Update existing node".

BTW, You could use this rule as a template to group multiple eMails (to individual eMail IDs) in a single eMail to all of those eMail IDs.

Demo

Here is how the Status message looks like after you create a new node, or update an existing node (of type Article):

  The value of the email_list variable is: StartOfList-user2@example.com-user4@example.com-EndOfList.

Conclusion

The variable was created before the loop, and modified in the loop.
And I display the value of the variable after the loop, it is changed like I wanted it to be changed.

As per what is shown in my answer here, it seems something is wrong in your rule (which you did not show in your question).

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


db_select get all results count when also using a pager

Yes you can use setCountQuery if you need to define a count query to return the total number of rows in your resultset.

See the docs for PagerDefault::setCountQuery()


Entity Reference field using View to Mask Autocomplete with Last Name

Remove the contextual filter from your Entity Reference view.

The view should have all the available options. The autocomplete widget for the Entity Reference field will filter the available options based on the user input. If you change the widget type to "Check boxes/radio buttons" you can see the available options which may help diagnose the issue.


You could always change the group it's in:

function MYMODULE_js_alter(&$js) {
  $js['path/to/eu-cookie-compliance.js']['group'] = JS_DEFAULT;
}

Drupal's misc JS, jQuery etc, should all be in JS_SYSTEM, which has a lower weighting than JS_DEFAULT. There's also JS_THEME which has a height weighting than JS_DEFAULT.

The drupal_add_js() docs discuss the whole JS weighting thing in much greater detail.


Dynamic menu with latest Article in drupal7

I am sure there is a module do to something like that, but you could also create your own.

You could use hook_menu() to query for the items you want and return the correct menu structure. You would need to also make sure the menu cache is rebuilt on a node save.

hook_menu should return an array of menu items, often these are pretty static however there is nothing wrong with these arrays being dynamically generated.

So you can query the node table to get a list of nodes you want, loop through these items and dynamically create an array which contains the correct menu items.

very roughly:

function example_menu() {
  $result = db_query('select * from node where ...'); // put in your own select items and where clause
  $menu = array();
  while ($row = db_fetch_object($result)) {
    $menu['my_path/' . $row->nid;] = array(
      // See hook menu docs for what to put here.
    );
  }
  return $menu;
}


Upgrading Drupal 7.43 to 8 error: Source database is Drupal version 8 but version 7 was selected

I managed to solve it.
It was caused be an update on PHP, that caused blank pages or “white screen of death” (WSOD) in the admin, too.
After updateing to 7.59, everithing was OK.
This article helped me: https://www.drupal.org/node/158043


How to use field value as class? Drupal 7

This should be a start.

function mytheme_preprocess_node (&$variables)
{
  $node = $variables["node"];

  if (isset($node->field_foo["und"][0]["taxonomy_term"])) {
    foreach ($node->field_foo["und"] as $foo) {
      $term = $foo["taxonomy_term"];
      $variables["classes_array"][] = "term-" . str_replace(" ", "-", strtolower($term->name));
    }
  }
}

Note, this is barely tested  and your exact situation may vary.  It assumes field_foo is the machine name for your taxonomy reference, and your theme is flattening $variables["classes_array"] for use in node.tpl.php.


Have you tried turning off CSS aggregation and seeing what happens?

The fact that it's trying to load a stylesheet at "http://localhost/drupal/?og6o9k" makes me think it's an issue with how your public file system is setup. Like it tried to create a CSS file but failed. I would check which folder it's set to and make sure the permissions are correct.

It could also be an issue with the theme. Trying switching to another theme temporarily and see if that fixes things.

Lastly, you can try uninstalling and reinstalling a fresh version of Admin Menu.


Bringing CKeditor, embedded content (e.g. iframe) and responsive design together

You can override youtube videos using CSS and media queries. Infact, most videos from Youtube, Vimeo etc are all available in an iframe. In projects in the past, I allow clients to just copy and paste an embed field into a ckeditor field wherever they like, at any dimension they please.

But, once the screen width is reduced to mobile, my CSS takes over, and resizes the video to fit the mobile template, to reduce overlapping, and fix any issue with video height.

E.g.

@media only screen and (max-width: 767px) {

.field-name-body iframe     {width:100%;height:200px;}

}

Is that what you mean, or I have I not understood the question?


Try this CSS.

#admin-menu, #admin-menu .dropdown {
  z-index: 9999;
}

.logged-in #oa-navbar {
  top: 25px;
}


Multiple forms on the same page: hook_forms only works after cache_clear_all

I had the same problem and it seemed to be resolved after correcting an issue with the function definition. Make sure that $form_state is a reference.

function mymodule_a_form($form_id, &$form_state, $args) {
...
}

One of the other things that I noticed is that the cached module_implements no longer had a reference to my module, so when Drupal was looping through the implements and looking for a function called mymodule_forms(), it couldn't find it.  You can check to see if this is the issue by comparing the cached implements to the static version.

    $cache_implements = cache_get('module_implements', 'cache_bootstrap')->data['forms'];
    ksort($cache_implements);
    dpm($cache_implements, 'CACHED FORM IMPLEMENTS');

    $static_implements = drupal_static('module_implements');
    ksort($static_implements);
    dpm($static_implements['forms'], 'STATIC FORM IMPLEMENTS');

If that is the issue and your form declaration is correct then maybe try doing an include on the page that references your dynamic forms.

module_load_include('admin', 'mymodule', 'inc');


How do I get a paginated view to display rel="next/previous" tags?

You just need to override theme_pager_previous() and theme_pager_next() (easiest to do in your theme):

function MYTHEME_pager_previous($vars) {
  $text = $variables['text'];
  $element = $variables['element'];
  $interval = $variables['interval'];
  $parameters = $variables['parameters'];
  global $pager_page_array;
  $output = '';

  // If we are anywhere but the first page
  if ($pager_page_array[$element] > 0) {
    $page_new = pager_load_array($pager_page_array[$element] - $interval, $element, $pager_page_array);

    // Changes from core function start here.
    $attributes = array('rel' => 'prev');

    // If the previous page is the first page, mark the link as such.
    if ($page_new[$element] == 0) {
      $output = theme('pager_first', array('text' => $text, 'element' => $element, 'parameters' => $parameters, 'attributes' => $attributes));
    }
    // The previous page is not the first page.
    else {
      $output = theme('pager_link', array('text' => $text, 'page_new' => $page_new, 'element' => $element, 'parameters' => $parameters, 'attributes' => $attributes));
    }
  }

  return $output;
}

And the same thing for pager_next.


D7 - How to get mlid value from path of menu item

There's no build-in function for this. You can use menu_tree_all_data(), but it returns all the menu. After that you can compare in loops your path with the paths returend. But there is a better and easier answer. Here it is:

$mlid = array();
$q = 'your-path';
$menu_info = db_select('menu_links' , 'ml')
  ->condition('ml.link_path' , $q)
  ->fields('ml', array('mlid', 'plid'))
  ->execute()
  ->fetchAll();

foreach($menu_info as $key => $value) {
  $mlid[] = $menu_info[$key]->mlid;
}


Add Help Text for User Roles Field on User Edit Page

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

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


How can I load all Media of a certain type?

If you use entity query you can filter the entities by type before uploading them.

$ids = \Drupal::entityQuery('media')
  ->condition('bundle', 'YOUR_TYPE')
  ->execute();

$medias = Media::loadMultiple($ids);


Is it good practice to override simple db_query or EntityFieldQuery with a View

There is no simple answer possible to this question because it very much depends on circumstances. The customary response to such fears is to invoke the spectre of Premature Optimization and to advise you not to worry until you know you have a performance issue.

However, from an educational perspective it's probably worth at least looking at the query Views is executing and considering whether it is efficient: is it scanning every row of a large table because of the lack of an index, for example.

On the Views settings page there's an option to display the SQL for a query. You can copy and paste it into a tool such as PhpMyAdmin (removing the curly brackets peculiar to Drupal SQL queries) then put "EXPLAIN" in front of it to see what's happening under the hood.

But in general I would not bother to rewrite a query like this until there's a proven need to do so.


Avoid PDOException while connecting to an external database

issue is that db_set_active just sets active key in some array and doesn't do any connection. when you do db_select or any other query only then it connects.

your second code is good. also you could do something like this:

  db_set_active('external');
  try {
   //check connection
   db_select("select 1");
  }
  catch (PDOException $e) {
      //error. set default back
      db_set_active('default');
  }

as you know how to check if connection is there now you just need extra logic what todo when connection cannot be established


How can I set the view mode of a node through rules

What "Content is viewed" actually means, seems to be like so:

The event Content is viewed is what it is: the user has (already) started viewing the content.
The (system) event Drupal is initializing is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" BEFORE the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to
How to specify a Rules event like "Content is 'going to be' viewed"?

Be aware: this applies to D7 ... and D6 is another story (from the question context I'm not sure if this is fopr D6 or D7 ...).


How to allow HTML attribute with namespace using filter

One way to solve this problem is to have a custom filter which processes the linkname and convert to sc:linkname.

<?php

namespace Drupal\my_module\Plugin\Filter;

use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * Provides a filter to correct faulty and chopped off HTML.
 *
 * @Filter(
 *   id = "filter_html_attribute_namespace_fixer",
 *   title = @Translation("Add 'sc' namespace to HTML attribute 'linkname'"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE,
 *   weight = 10
 * )
 */
class FilterHtmlAttributeNamespaceCorrector extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    return new FilterProcessResult($this->addNamespace($text));
  }

  protected function addNamespace($text, $namespace = 'sc') {
    $html_dom = Html::load($text);
    $xpath = new \DOMXPath($html_dom);
    foreach ($xpath->query('//a[@*]') as $element) {
      foreach ($element->attributes as $name => $attribute) {
        if ($name == 'linkname') {
          $element->setAttribute('sc:linkname', $attribute->value);
          $element->removeAttribute($name);
        }
      }
    }
    $text = Html::serialize($html_dom);
    return trim($text);
  }

}


I am facing same problem and get solution as below. Create a tpl as give in Style output under theme information.

$arr_rows = $view->style_plugin->rendered_fields;
<?php foreach($arr_rows as $key=>$arr_row) : ?>
<?php print $arr_row['field1']; ?>
<?php print $arr_row['field2']; ?>
<?php print $arr_row['field3']; ?>
<?php endforeach; ?>


Dim background elements when displaying submenu

There's a bunch of options.  jQuery is probably the easiest but I could envision a way of doing it with CSS only using some combination of clever sibling and pseudo-class selectors.  You could also do it using an overlay element and some z-index work. Or just use JS/jQuery to dim the other element's opacity either using animate or adding a class that has an opacity transition.  The best choice depends on your requirements and how your HTML is structured.

But the question is a little vague and not particularly Drupal related.  If you want do the last case above, just do on('hover', function() ) {} and set the opacity / class of the elements to dim.


Let's call it a bug in Nexus theme.

If you sub-themed Nexus, copy the page.tpl.php from Nexus templates folder into your sub-theme's template folder, then make the following change to the copied file, just after the h1 tag for the title:

// look for this

  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>"><?php print $site_name; ?>

// then add this below it
<?php if ($site_slogan): ?>

    <?php print $site_slogan; ?>

<?php endif; ?>


Add and customize login block on page.tpl

you can do it like this:

$block = block_load('user', 'login');
$block = _block_render_blocks(array($block));
$block_build = _block_get_renderable_array($block);

print drupal_render($block_build);

this will generate a block with title and contexual links also..


CKEditor Font Size and Family buttons does not appear

For me, I put the center, left, and right align buttons in my "TOOLBAR CONFIGURATION".  But You also need to add the class attribute to the filter to "Allowed HTML tags" at the bottom of the page.

<p id class> <br> <u> <s> <em> <strong> <cite> <blockquote cite> <code> <ul class type> <ol class start type> <li class> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <drupal-entity data-entity-type data-entity-uuid data-entity-embed-display data-entity-embed-display-settings data-align data-caption data-embed-button> <img src alt data-entity-type data-entity-uuid data-align data-caption> <a class href hreflang !href id rel target title> <table> <iframe src frameborder width height scrolling allowfullscreen> <caption> <tbody> <thead> <tfoot> <th> <td> <tr>


getting a notice in reports for Commerce Paypal EC. IPN for Order ignored:

OK, so in your case, it sounds like the IPN notification is being skipped because the order is already in the "complete" status.

To keep the IPN processing, you may need to keep the default "pending" status for such orders. That way, the IPN notification can mark the order as complete.


Yes, that is how I envisage the end result, but I am looking for a
  solution to allow the node author to drop the picture into an input
  field and let Drupal deal with the float.

All you have to do is create a template file for your content type. Then add a class or an id for your image field. (copy the node.tpl.php file and paste, rename the copy to node--[your content type name].tpl.php such as node--articles.tpl.php) Then add this line, you will also need to print all the other fields you want to see.

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

So when someone view's the page, your image will automatically be wrapped inside floated.

(above answer assumes you're using Drupal 7)

Template file

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

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

CSS

#example{
    width: 400px;
    background: yellow;
}
#floated img{
    float: left;
    width: 150px;
    background: red;
}

If you want an easier solution, less advanced knowledge needed, then use Panels which will let you add a class to your image.

  The Panels module allows a site administrator to create customized
  layouts for multiple uses. At its core it is a drag and drop content
  manager that lets you visually design a layout and place content
  within that layout. Integration with other systems allows you to
  create nodes that use this, landing pages that use this, and even
  override system pages such as taxonomy and the node page so that you
  can customize the layout of your site with very fine grained
  permissions.

Panels Tutorials


Breadcrumbs disappear on cache clear, come back with subsequent cache clear

In a node use the breadcrumb builder directly:

\Drupal::service('breadcrumb')->build(\Drupal::routeMatch())->toRenderable();

The node gets cached already and the cache metadata of the breadcrumbs bubbles up to the node.

In a page it's preferable to place the block in a region (can be a region of its own) and then place the variable of the region in the page template.

If you want to use code to place the block, make sure you use the block for the correct theme (you have to query the block table with the property theme for this). Now it seems like you use the breadcrumb block placed first on your site, not necessarily the one for your theme.


From the module page:

  With this module you can output a view as a PDF document. Each field
  of the view can be placed on the PDF page directly in the
  administration interface. Therefore a new display called "PDF" is
  added.

So from within Views, add a PDF page display. Then add the fields you like.


Why are these paths different when you talk about "your project":

path 1:
C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\projects\web2\includes\cache.inc

path 2:
C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\webONE\includes\cache.inc)

This smells like something is horribly misconfigured.

I've made dozens of drupal sites, typically under Linux, but I have used WAMP myself in the past (not EasyPHP-DevServer). This makes me think it's an issue with the EasyPHP-DevServer and not drupal itself.

While you may not be familiar with it ... have you tried like copying your site files and DB to a Drupal 7 Quickstart project VirtualBox virtual machine, or  DrupalPro ... another off the shelf VM drupal-in-box ...


How to implement a simple shopping cart without Commerce and Ubercart?

The Basic cart module is the best solution for you...

  Basic cart is a very simple shopping cart / checkout process for
  Drupal, that just sends 2 emails after each order. Along with the
  shopping cart, this module also provides a block where you can view
  your cart's content. It's ideal for small websites with only a few
  products or other content types being sold, for example touristic
  offers.


How do I wrap classes around taxonomy terms?

You're looking for taxonomy-term.tpl.php.

This will allow you to customize the output of your term page.


How to get a machine name of a custom block

A custom content block has no unique machine name, only a bundle type, an UUID and an ID. Only custom content blocks placed in a region have a machine name, but this is NOT the machine name of the block, it is the machine name of the block placement (configuration)


D7 : Views exposed form with three taxonomy term fields as filters (checkboxes)

In your view I would not select any of the occasion field items and allow all the items with or without this field to populate. If the user wants to drill down into restaurants with this information you can have them use the select menu or whatever mechanism to choose the specific occasion. I think that starting off with no filter on the occasion field might be the way to go.


The variable names in the render array and theme hook need to match:

array(
  '#theme' => 'myTheme',
  '#test_var' => $this->t('Test Value'),
  '#doubles' => array('key'=>$myArray),
);

Iterating an array in Twig is pretty straightforward:

{% for key,value in doubles %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}


This option is available out of the box in view contextual filter settings. You can able to choose input to the contextual filter using checkbox setting "WHEN THE FILTER VALUE is not in the URL". Select Provide default value from URL and choose path component. In your case it is 3. See below screenshot for example.


8 - SQL error "String data, right truncated..." when creating/updating a node programmatically, but OK when inserting via the CLI. Why?

The CLI works because then you're not in strict mode and it just cuts the string off.

Your date format is wrong. It must be in the format defined by DATETIME_DATETIME_STORAGE_FORMAT
 and converted to the correct timezone DATETIME_STORAGE_TIMEZONE.


API error: "The 'administer nodes' permission is required."

First, administer nodes is the machine name of the permission.  On the Permissions page, the name of that permission is Administer content.  There's probably some historical reason why Drupal has some permissions where the machine name is different than the name shown in the UI, but it's horrible usability.
In any case, this is definitely too much access if you just want the user to be able to set the entity reference.  Normally, you probably want to give the user some combination of Content type (Itinerary): Create Content type (Itinerary): Edit, and Content type (Itinerary): Delete permissions, which will be under Node at /admin/people/permissions.
Actually, though, your code has another problem.  The error is about posting uid, which is not your entity reference, but the author of the node.
The format for setting the user id, as noted in the docs:
{
  "data": {
    "type": "node--article",
    "attributes": {
      "title": "Article by admin",
      "body": {
        "value": "Custom value",
        "format": "plain_text"
      }
    },
    "relationships": {
      "uid": {
        "data": {
          "type": "user--user",
          "id": "{{UUID of user 1}}"
        }
      }
    }
  }
}

You are missing the part about data and type.
And, even if you use this code above, it won't set an entity reference field.  To set the entity reference field, in addition to the author, you need to set the entity reference field like this (example of setting a node entity reference field on a taxonomy term flag; this is maybe not the best example for your case but its code I wrote recently that shows how to set an entity reference field; in this case, the entity reference field is flagged_entity):
  data: {
    type: 'flagging--my_flag_type',
    attributes: {
      entity_type: 'taxonomy_term',
      entity_id: drupalId,
      field_text: textFieldValue,
    },
    relationships: {
      uid: {
        data: {
          type: 'user--user',
          id: MyUser.id,
        },
      },
      flagged_entity: {
        data: {
          type: 'taxonomy_term--group',
          id: MyGroup.id,
        },
      },
    },
  },


Rules replacement pattern for image type field

Found the solution as follows:

To get the proper selector I switched to Data Selection mode.Then through hierarchy I got proper sector as [comment:node:field-photo:file:url], which is URL of image. By using img tag, I am able to display image.


Does you know how the CCK Private Fields module works? Any API?

Looking at the description page of this module, it seems that user can do what you want:

  Overview:

  This module allows users to mark administrator selected CCK fields as
  Public (visible to everyone), Hidden (visible to node author, hidden
  from everyone else) or Private (visible to node author and "friends";
  see requirements section below).

Regarding the option to "disappear" a user, I'm not really sure as there's a lot of place where a user can appear, however if you give this user a certain role, you can customize your views to exclude users with this role.


Pass argument when overriding controller in RouteSubscriber

Actually, I have found an error in my code.
Everything works normally, when the param name and type are set properly.
So the final code should be:

My sample page controller is this:

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\taxonomy\TermInterface;

/**
 * Class PagerController.
 */
class PagerController extends ControllerBase {

  /**
   * Handlepage.
   *
   * @return string
   *   Return Hello string.
   */
  public function handleDefaultPage(TermInterface $taxonomy_term) {
    return [
      '#type' => 'markup',
      '#markup' => 'term: ' . $taxonomy_term->getName(),
    ];
  }
}

And its routing is this:

my_module.pager_controller_handleDefaultPage:
  path: '/taxonomy/term/{taxonomy_term}'
  defaults:
    _controller: '\Drupal\my_module\Controller\PagerController::handleDefaultPage'
    _title: 'Taxonomy Pager'
  requirements:
    _permission: 'access content'
    _entity_access: 'taxonomy_term.view'
    taxonomy_term: \d+


I have created a rule that empty cart before adding any new item. So the only latest item will be in the cart. I think thats what you need to do. Any other conditions can be added one by one.

If you want to clear cart totally then you can use after adding product event

{ "rules_empty_cart_" : {
    "LABEL" : "Empty cart ",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_cart", "rules" ],
    "ON" : { "commerce_cart_product_prepare" : [] },
    "DO" : [
      { "commerce_cart_empty" : { "commerce_order" : [ "commerce_order" ] } },
      { "drupal_message" : { "message" : "Cart empty event executed.!!" } }
    ]
  }
}

Hope it will help!


How to upload pdf files and link to them?

I think the solution could be IMCE module which allows you to upload file/images... through CKeditor interface.

  Features

  Basic file operations: upload, delete
  Image(jpg, png, gif) operations: resize, create thumbnails, preview
  Support for private file system
  Configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions
  Personal or shared folders for users
  Permissions per directory
  Ftp-like directory navigation
  File sorting by name, size, dimensions, date
  Tabbed interface for file operations
  Keyboard shortcuts(up, down, insert(or enter), delete, home, end, ctrl+A, R(esize), T(humbnails), U(pload)).
  Built-in support for inline image/file insertion into textareas
  Multiple file selection(using ctrl or shift)
  Ajax file operations
  Themable layout using tpl files


A default value does not work in this case, as - strangely - this will override the context provided event id. Some default entity methods, such as delete, seem to require the route URLs and therefore fail when the parameter is not given.

The add_form route, which is automatically created by DefaultHtmlRouteProvider from the @ContentEntityType annotation, causes problems here. The easiest solution is probably to remove this route by deleting the line

"add-form" = "/admin/structure/event/{event}/participants/add"

from @ContentEntityType (under "links") – do not remove the add form in section "form" – and providing the route in modulename.routing.yml:

entity.participant.add_form:
  path: '/admin/structure/event/{event}/participant/add'
  defaults:
    _entity_form: participant.add
    entity_type_id: 'participant'
    _admin_route: TRUE
  requirements:
    _entity_create_access: 'participant'


How do I modify the _trackPageview output of the Google Analytics Drupal 7 module?

If your question is "how to pass custom values to Google Analytics ?", then why wouldn't you use the Custom Variables feature of Google Analytics, populated by custom tokens ?

Create custom token containing search categories (via hook_token_info() and hook_tokens())
In Google Analytics Module interface, in the "Custom Variables" fieldset, add your custom token


How to remove a menu path defined in hook_menu from naviagtion

Don't add type to the array in hook_menu, it will not be displayed as a menu, but still will be accessible (by code)

$items['menu/%/link1'] = array(
   'title' => 'Link1',
// 'type' => MENU_LOCAL_TASK,
   'page callback' => 'link1()',
   'page arguments' => array(1),
   'access callback' => TRUE, //'has_access',
);


Views slideshow with multi value imagefield

Try field slideshow. It bypasses views entirely, which makes it easy when all your images are in one node.

I don't think it works with the media module, yet, and you have to set your field type has to be "image". You select the slideshow options in the display fields portion.


How to replace a preprocess function entirely?

hook_theme() is for new theme implementations, not altering the existing ones, and 'override preprocess functions' can be used just from themes.

The hook you need to implement is hook_theme_registry_alter(). The example code shows how to remove a preprocess function for a theme implementation.

function mymodule_theme_registry_alter(&$theme_registry) {
  // Kill the next/previous forum topic navigation links.
  foreach ($theme_registry['forum_topic_navigation']['preprocess functions'] as $key => $value) {
    if ($value == 'template_preprocess_forum_topic_navigation') {
      unset($theme_registry['forum_topic_navigation']['preprocess functions'][$key]);
    }
  }
}

Removing all the preprocess functions would just require a line like unset($theme_registry['forum_topic_navigation']['preprocess functions'].

The same is true for Drupal 7. (See the example code given in hook_theme_registry_alter() - Drupal 7).


Troubleshoot hook_library_alter() not being called for the jQuery Update module

I had this problem as well and I tracked it down to a custom module calling drupal_add_js() right at the top of the module file. This meant that drupal_get_library(system, jquery) and in turn module_implements(library_alter) were getting called before the jquery_update.module file had a chance to get loaded and hence jquery_update_library_alter wasn't defined yet.

To find this I put the following lines into drupal/include/module.inc and cleared the cache.

...
function module_implements($hook, $sort = FALSE, $reset = FALSE) {
    if ($hook == 'library_alter') { debug_print_backtrace(); exit; }
...

You might have some other problem, but a call to drupal_add_js to early in execution was my issue.


Error after updating Webform from 8.x-5.0-beta15 to 8.x-5.0-rc1

Yes, flushing the cache via Drush should solve the problem.

If you can't use Drush, you must put your site in maintenance mode, set $update_free_access=TRUE, and run the pending updates via /update.php.

Also see

http://www.zymphonies.com/blog/update-drupal8-core
https://www.drupal.org/project/webform/issues/2907960


Every I did above was correct. I needed to have my users re-enter there location so geo-coding would be added to their profile.


How to easily create and reference a node / entity during creation of another one?

The References dialog module might be an option (if you're using the references project).

  This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog. This allows for a workflow where the user can create all the references to a node at the same time as she is creating it, a process which sometimes get's a bit backwards, when a user for instance needs to create all the facts for an article.

It doesn't do exactly what you've described, but it's pretty close.


How do I add a password field during registration?

Yes. Disabling email confirmation. Which you probably don't want.

Drupal doesn't really have mail confirmation. It just doesn't tell the user his password, and then he gets a password recovery link and can provide a password after that.

I've built a custom module for this that allowed it for a project, you basically need to add a field to users, prevent login if that is not set, set it on the first login through password recovery. Change the user registration submission to send a confirmation mail anyway. And care about some special cases, like admin created users. Not trivial.

There are contrib modules for this, for example https://www.drupal.org/project/user_registrationpassword. there's no official release yet, but maybe someone started porting it.


What was the motivation for developing the plugin API?

It is not modules vs. plugins. Plugins are competing against hooks, which they will eventually replace entirely, together with event subscribers and services. By the way, all are implemented by modules because you are not allowed to insert them in core directly.


How can I get the term ID out of the hierarchical select theming function?

The entity is a stdClass object, you need to use the -> accessor:

flag_create_link('hobbies', $term->$item['#options']['entity']->tid);


How to embed a block (with title) in a template file?

http://drupal.org/node/26502 - A nice write up on displaying a block using code. There are a couple of examples toward the bottom that show displaying the entire block (including the subject).

One in particular you could try, using Drupal's theme() function:

<?php
    $block = (object) module_invoke('[target_module]', 'block', 'view', "[target_block_ID]");
    print theme('block', $block);
?>


Can't find migrate setting in configuration

Using the Migrate Upgrade UI (easier)

  Migrate Upgrade is a UI for core upgrades from Drupal 6 and Drupal 7
  to Drupal 8. It's still under heavy development, so things may break.
  If something fails for you, check the issue queue first! There may be
  a patch. If not, check with the developers in #drupal-migrate on IRC.

  After installing Migrate Upgrade, visit your Drupal 8 site's /upgrade page. When you do you will see this helpful Home screen.

Source: Executing a Drupal 6/7 to Drupal 8 upgrade

Step 1) Install Upgrade Migrate module

Step 2) Go to yourwebsite.com/upgrade

Worth Noting

  If you have a Drupal 6 or 7 site you want to upgrade, install or update the Upgrade Status module to get a customized, up-to-date report on the status of your modules and themes in Drupal 8. Once you are ready, Drupal 8 core also includes the Migrate module to update existing Drupal 7 and 6 sites to Drupal 8 directly. Migrate is marked "experimental" in Drupal 8.0.0, but will be fully supported in an upcoming release

Source: Drupal 8.0.0 released


using jquery updated version in user edit page

I found a solution: First check the path, and then replace the JavaScript file.

function mymodule_js_alter(&$js) {
  if (preg_match('/user\/\d*\/edit/', current_path())) {
    $js['sites/all/modules/jquery_update/replace/jquery/1.5/jquery.min.js']['data'] = 'sites/all/modules/jquery_update/replace/jquery/1.7/jquery.min.js';
  }
}


How to add a button :"Get my location" in page views

You can use the IP Geolocation Views & Maps module for that task. It will provide you with a block that contains a button with the asked functionality. The user location will be determined via several methods:

  Finally IPGV&M provides a set of visitor location retrieval
  technologies, both IP and HTML5-based, so that you can track where
  past visits came from and where current visitors are located,
  superimposing their moving positions as markers on your maps.

Please read carefully about the requirements.


I hada look into my watchdog table. It said the sessions table was corrupted and needed to be repaired. So I did it, and after that I could login with the super user again. Thanks everybody for helping out, but it was something different this time.


Drupal installed as composer package, Custom themes/modules folder

Drupals extensions discovery looks only in some specific folders (see http://cgit.drupalcode.org/drupal/tree/modules/README.txt for more information).

But, you don't have to put your own modules inside of the core folder. You should use /modules instead.

The Drupals default directory is not ideal for a development workflow with composer in mind. Take a look at https://github.com/drupal-composer/drupal-project if you have not already.


Adding "terms" on the fly and/or mutiple term referance submission with "unlimted values"

I would recommend you try the Hierarchical Select module if you want to have a drop down select as well as have the ability to add new terms on the fly. You select this option when setting up the Hierarchical Select for the term reference field. It will add 'Add new term' to the select list.


If you want the fields approach, try looking at the module http://drupal.org/project/emfield
If you want to do it yourself in code, there are different approaches, the most basic one being adding a node template for your content type and adding your embed code there. Look at drupal.org for basic information about addding templates.


Default to original language in nodes list

See the solution to How do I get Views content items in "my language" but fall back to "default" if the content isn't translated? whether it helps just by configuring in admin. It seems to solve the same problem.

Unfortunately, I have the same problem, and I can't get the solution described there to work. Reading all the issues linked in meta Make multilingual views work, it seems to me that there is no built-in solution. I tried to implement a hook_views_post_execute() and to filter the ViewExecutable $view manually, like in the following, but it did not work - either still shows multiple translations per entity, or entities are missing:

# File modules/contrib/modulename/modulename.module
# Enabled in admin/extend
function modulename_views_post_execute(ViewExecutable $view)
{
  $contentLangcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();

  # trying either one of:
  # $Filtered = filterLangcodeOrEn($contentLangcode, $view->result);
  $Filtered = filterNodeOnce($view->result);

  $view->result = $Filtered;
  $view->total_rows = count($Filtered);
}

function filterNodeOnce($rows)
{
  $Nodes = array();
  foreach ($rows as $row) {
    $Nodes[$row->nid] = $row;
  }

  return array_values($Nodes);
}

function filterLangcodeOrEn($contentLangcode, $rows)
{
  # group by nid
  $EntitiesLangcodesRow = array();
  foreach ($rows as $row) {
    $EntitiesLangcodesRow[$row->nid][$row->node_field_data_langcode] = $row;
  }

  # select
  $Filtered = array();
  foreach ($EntitiesLangcodesRow as $LangcodesRow) {
    if (isset($LangcodesRow[$contentLangcode])) {
      $Filtered[] = $LangcodesRow[$contentLangcode];
    }
    else if (isset($LangcodesRow["en"])) {
      $Filtered[] = $LangcodesRow["en"];
    }
  }
  return $Filtered;
}


FieldCondition in an EntityQuery for media is causing a website error

There's no fieldCondition method, condition works for all fields:

$query = \Drupal::entityQuery('media')
  ->condition('status', 1)
  ->condition('field_flagged', 1);
$result = $query->execute();


Is there a way to pass a form #value to the form #action in Drupal 7 form API?

In FAPI, #action changes the form's action parameter, which, you should not override if you want to make Drupal handle the submission.

In your case, you need to define a custom submit handler and redirect the user in that function. You could do something similar by changing the form's method to GET, but it is not possible to define a complex path like the one you want.

Remove this line:

$form['#action'] = url('http://example.com/name_storage/' . $form['first_name']['#value'] . '/'. $form['first_name']['#value'] . '/' . $form['passcode']['#value']);

Then, add a new submit handler like this:

function my_module_form_submit($form,&$form_state) {
  $values = $form_state['values']['first_name'] . '/'. $form_state['values']['last_name'] . '/' . $form_state['values']['passcode'];
  $form_state['redirect'] = 'name_storage/' . $values;
}

To set the redirect parameter to an external URL, you can do this:

$values = 'http://example.com/name_storage/';
$values .= $form_state['values']['first_name'] . '/'. $form_state['values']['last_name'] . '/' . $form_state['values']['passcode'];
$form_state['redirect'] = array(
  $values,
  array(
    'external' => TRUE,
  ),
);


It's really hard to answer specifically, since it really depends on how you have set your vagrant up.

Long story short

You need to setup your drush alias so that it's using SSH settings to access your vagrant box. The issue is probably that your vagrant box doesn't expect connections on port 22 or that you haven't setup the correct IP/domain for SSH connection in your alias.

If you want to use Vagrant for Drupal development I can recommend parrot. It has all you want for Drupal developetment, uses puppet, which makes it pretty easy to change PHP versions etc, and has Varnish, Solr etc.

If you are using parrot you should be able to access the Vagrant box by doing.

ssh vagrant@site.dev

Assuming that your site is located on the site.dev url.


Git workflow for Composer-based projects

If your goal is to minimize the size of your repository, then you should use Composer, following the pattern described in the project drupal-composer/drupal-project.

One possible workflow would then be:

On dev:

git pull
composer install
drush config-export
git add / commit / push

On stage:

git pull
composer install
drush config-import

On live:

rsync from stage to live
drush config-import

The workflow you propose will not work. The command drush pm-update will not do anything if Drupal is already at the most recent version. drush pm-download is not a good alternative either, as it will overwrite portions of your code base. You could potentially repair this with a git reset --hard or some similar trick, but that would not be very clean.

If you do not wish to use Composer, your best option is to simply commit the core and vendor directories.


Why is cache_discovery not rebuilt on cache-rebuild?

If you truncate the table cache_discovery and then do a cache-rebuild the table is filled again with data, what would not be, if this was still a cache-clear. In D8 clearing the cache is more like rebuilding the cache, hence the new name. Some tables are still cleared, like the render cache or the twig cache, because these are filled with new data from the result of each request. But the structural data like discovery, router, config and some more are rebuilt, so that the first request after clearing the cache doesn't take too long.

If you set $settings['cache']['bins']['discovery'] = 'cache.backend.null';, then you freeze the table content. It is not touched, even not by a cache rebuild, until you remove this setting.


How dio I change things on module installation?

I think what you are thinking of is configuration and overriding configuration. You can load any config object and set its value.

See: https://drupal.stackexchange.com/a/187488/57

Menu links are entities and can be loaded and changed too. See: https://drupal.stackexchange.com/a/225605/57


Something like this:

foreach ($images as $image) {

  // New array for readability
  $options = array(
    'path' => $image->url,
    'alt' => $image->alt,
  );

  // Push the image tag onto the items array
  $block['content']['list']['#items'][] = theme('image', $options);
}


How do I rewrite attached file field output in Views to override the filename?

Certainly, you just have to use the correct formatter to start with.  I am guessing that you are using the "Generic Files" one.  If you instead select "Path to File" you can then use rewrite output the way you mention in your question.  Little gotcha:  make sure the title field you are using isn't "linked to its node" or things will get odd :)

(Note, I am suggesting you rewrite the file field instead of the title field)


Pages displaying blank ONLY when Theme Developer module turned on

This might be due to version compatibility with Simplehtmldom module.

Download this library and install in your sites/libraries files.

This is taken from modules page,

  NOTE: Currently, Theme Developer does not work with the latest version of simplehtmldom API. You must use simplehtml API version
  7.x-1.12 if you want Theme Developer to function properly.

OR if that is not the case you can try putting this snippet end of  the settings.php file, this snippet will show error message on the browser while loading page instead of WSOD. and you can put your error message here in question and elaborate it.

  error_reporting(E_ALL);
  ini_set('display_errors', TRUE);
  ini_set('display_startup_errors', TRUE);


Possible to use drush to list overrides for all features?

In the current version of Drush, you can show a list of all features and their override state with (both short and long versions of commands shown, with and without the "-y" flag to skip confirmation questions):
$ drush features-list
$ drush fl

If you want to show only the overridden features:
$ drush features-list | grep -E "Overridden|Needs"
$ drush fl | grep -E "Overridden|Needs"

To show everything that has been overridden for all features:
$ drush features-diff-all
$ drush fda -y

To update all features to their currently overridden state:
$ drush features-update-all
$ drush fua -y

To revert all features to their default state:
$ drush features-revert-all
$ drush fra -y


Drupal views custom filter, check if row exist

I guess you are looking for something like this, but you might need to tweak it a bit. You can group db_or and db_and, then combine them like this. Basically create two 'and' groups where all conditions need to match. Then combine those in an 'or' group, where one of the conditions needs to match.

function query() {
  $and1 = db_and();
    $and1->condition('field_name', 'test', 'LIKE');
    $and1->condition('field_id', 0);

  $and2 = db_and();
    $and2->condition('field_name', 'test', '<>');

  $combine = db_or();
    $combine->condition($and1);
    $combine->condition($and2);

  $this->query->add_where(
    $this->options['group'],
    $combine
  );
}


DRUPAL 7.33 - When i try to save a node with upload, i receive website encountered unexpected error...PDOException: SQLSTATE[25P02]

sorry for the delay, but finally found the solution to my problem ...
https://www.drupal.org/node/1003788

I would like to acknowledge the help of you gave me...