Views caching not working for Taxonomy listing pages I was able to turn on Views caching (both time-based for a few, and content-based for others) successfully.  However, for my "taxonomy/term/%" pages (and their respective "/feed? pages as well) if I turn on any kind of caching, I get an empty page. Not the WSOD, but just the title and no listings.  Further, the pager is all screwy - the page numbers point to pages for OTHER taxonomy terms.  I can't seem to find a pattern.

I did find this discussion on d.o but it's not much help: http://drupal.org/node/1430650

What's killing me is that these pages are seriously about 98% of my site's traffic - literally tens of thousands of page views per day.  If I can get these cached it would give me a huge performance increase.

Any ideas?

Have you tried doing a print_r(), dpm(), etc. on the cache_get() and cache_set() functions to see what's going on? The output of this tends to be somewhat verbose, so I generally like to do an error_log(), then go to the PHP error log and see all the calls to cache_get and cache_set to see if I detect a pattern. This would give you a concrete idea of what and what is not getting cached.


How to add custom theme to module block on Drupal 7? I saw lot of questions and answers on this but I can't find solution.
I need to show last posts trough tpl file and I can't figure how to do it.
Also I don't know what to put in my tpl file.

Edit!:
This is my hook_block_view () function and if I send data at the end of it like theme('item_list', ... it works perfectly. But I need to send it to my custom tpl file and when I do that it won't properly display list. I think that there is problem in .tpl file.

<?php
function last_5_user_posts_block_view($delta = '') {
$block = array();

switch ($delta) {
case 'last_5_user_posts':

  // Capture the image file path and form into HTML with attributes
$image_file = file_load(variable_get('last_5_user_post_image', ''));
$image_path = '';

if (isset($image_file->uri)) {
$image_path = $image_file->uri;
}

$image = theme_image(array(
    'path' => ($image_path),
    'alt' => t('Image description here.'),
    'attributes' => array('class' => 'class_name'),
    'width' => '12',
    'height' => '12',
    ));

  $block['subject'] = t('My last posts');
  if (user_access('access content')) {
    // Use our custom function to retrieve data.
    $result = last_5_user_posts_contents();
    // Array to contain items for the block to render.
    $items = array();
    // Iterate over the resultset and format as links.
    foreach ($result as $node) {
      $items[] = array(
        'data' => $image.l($node->title, 'node/' . $node->nid),
      );
    }
   // If there is no nodes
    if (empty($items)) {
      $block['content'] = t('No posts available.');
    }
    else {
      // Pass data through theme function.
   //   $block['content'] = theme('last_5_user_posts_output', array(
   //       'items' => $items));
        $govno = 'Govno!';
        $listitems = array('items' => $items);
      $block['content'] = theme('last_5_user_posts_output', array(
          'items' => $items));
    }
  }

  return $block;

}

}

And my .tpl file for now contain just:

 <div class="field-items"<?php print $content_attributes; ?>>

 <?php foreach ($items as $delta => $item): ?>

<?php print render($item); ?>

 <?php endforeach; ?>

If I create array:

$test[1] = 'Test!';
$test[2] = 'Test2!';
$test[3] = 'Test3!';

And send it trough $block['content'] like this

$block['content'] = theme('last_5_user_posts_output', array(
          'test' => $test));

It works pefectly!
But for $items it won't work. How to optimize $items to get it in .tlp??

Was too long for a comment...

If all you want is the last 5 posts of the current user - create a view:

choose content type
Create a limit under Pager (presumably of 5)
advanced - relationship author
filter by currently logged in user
sort by post date descending

This will create a view (be it a page or block) that shows the last 5 posts of whatever content you want for the currently logged in user. If you want to include it as a block, create as a block, and in the block configuration for that view (under structure/blocks), you can decide where on the page and for which pages you want the block to appear.

You can decide which content types are included via the filter, and decide the layout.


Display error message daily Is there a way to display error message daily to the user saying that "Your subscription Expiry in x days". And this message needs to popup each and everyday.

I can use hook_init()(this will run each and every page load), is there any other hook/option available?

hook_init is used, when you want to do something while the request is initialized,
you could use hook_preprocess_page and there set the message, checking on a custom field you added to your user, storing the date of the last information. If this is not today, then show it and update the field value.


How can I create a customised add/node form in D7? How can I create a customised add/node form in D7?

I am not talking about a form for gathering information that is not content for the site, like an event registration form. I'm talking about the node/add form where you create content for your site.

What I want to replicate is just some simple html tables, arranged together, and some css to make it look good. Lots of boxes in which to insert numbers, mainly, a few drop-downs and text fields too. Imagine you navigate to node/add/scorecard and something like this appears:

Thanks.

SOLUTION

This is the solution I have arrived at:

(1) Create a module (.INFO and .MODULE files).

(2) Implement hook_menu (in your new module) to create a url and page where the form is to reside.

(3) Add a function to render the HTML of the form using drupal_get_form.

(4) Add a form builder function and construct your form using an array called $form (see form API for details).

(5) Add a submit button at the end of your form.

(6) To make the form look the way you want it to there are several methods: (i) create a theme function to add to the elements of $form; (ii) use #prefix and #suffix properties to add additional HTML and CSS ids/classes to the rendered form; (iii) manipulate the many ids/classes, rendered by drupal_get_form, with CSS; (iv) use the #markup properties to add additional HTML and CSS ids/classes to the rendered form (not recommended). I used a combination of (ii) and (iii). I could not work out how to do (i) but it is probably the 'most correct' method.

(7) Add a validation function.

(8) Add a submit function using node_save (for nodes) and drupal_write_record (for fields) to insert your form values into the relevant database tables: node, field_data_field_my_field etc.

you may try using Webform module.

Webform is a module that aids in making various one-off forms such as contact forms, surveys, order forms, reservations, CRM requests, and more.
To install the module, download the module and add it to your sites/all/modules directory. Enable it under /admin/build/modules.
You will now have a new node type called "Webform". From there you simply give the webform a title, description, confirmation message, set up email settings and the like.
Finally, you can add several components (think fields). There are several component types available: fieldset, pagebreaks, grid, textarea, textfield, select (checkboxes, pulldown lists), email addresses and more.

Here's the documentation.
Let me know if you need more information.
-------------------- UPDATE ----------------------
To customize the HTML of the form you can copy the file webform-form.tpl.php and copy it into you template.
Inside there is the array $form['submit'] that contains the compontents of the form.
write dsm($form['submit']) and it will print the compontents.
Then you may do something like
<div class="my_class" id="my_id">
<?php print render($form['submit']['YOUR_FIELD']); ?>
</div>

Then you may want to assign this template to that node, so it will be
webform-form-NID.tpl.php


How to force a running migration to stop I created a migration with a query that seems to have broken my migration. I added two groupBy on a query, instead of two orderBys. As a result, running drush mi MyMigration got stuck in what appeared to be an endless loop.

I CTRL-C'd the process and then ran a drush mst --all, but now the status is reporting as "Stopping" in the UI, and the drush ms command does not return.

I tried stoping and restarting MAMP, but to no effect.

Is there someway to force my migration to get unstuck?

Did you try migrate-reset-status, and possibly with --force:
https://www.drupal.org/node/1561820

Otherwise I typically restart PHP manually once (restart your webserver) and then use Drush to rollback all the migrations to try again fresh.

EDIT

I rarely use the UI as everything is usable and scriptable via drush when using Migrate. And trying to use a webserver to check the status of long-running tasks can be error-prone.


How to add and delete a user to another group using the Group module? I am using Drupal 7 and the Group module. I would like to create  reaction rule or some code which automatically signs the user up to group 'blue', when they sign up to group 'red'.

I wouldn't mind using Rules or hard coding it. The only thing is that if the user leaves the first group, I want to be able to cancel their membership in the second group too.

What would be the easiest way? I have of course tried Rules without success and I cannot find a simple way to hard code it.

Found the solution. When using the group module, there are methods which work well. I used a hook_group_membership_insert($group_membership):

function [my_module]_group_membership_insert($group_membership) {

   $grouptest = group_load($group_membership->gid);
   $grouptest->addMember($group_membership->uid);
}

The same exists for deleting a member, just use the following function:

$grouptest->removeMember($uid);


How can I add a theme template to site? Bootstrap has templates like new age, creative, clean blog, etc. How do I add these templates to my site?

My workflow didn't work out well.

I copied the starter kit less to themes/custom
I renamed it to testtheme
I renamed all THEMENAME.yml files to testtheme.yml
I executed git clone https://github.com/BlackrockDigital/startbootstrap-new-age.git

Edit:
- Installed and set as Default (backend)

Unformatted bootstrap

edit 2:
global-styling:
 ` css:
    theme:
      css/style.css: {}
      css/new-age css: {}
      css/new-age.min css: {}

bootstrap-scripts:
  js:
    js/new-age.js: {}
    js/new-age.min.js: {}

Follow the following steps to add the bootstrap:

1. Put the bootstrap theme in the theme folder.
2. If you want to create a sub theme then copy the cdn folder from starterkits and rename. (themename)
3. Rename .info.yml , .libraries.yml and .theme files with your themename.

Include the CSS in theme.libraries.yml file. Like below

global-styling:
 css:
  theme:
    css/style.css: {}

global-scripting:
 css:
  theme:
   js/script.js: {}


Is there a node hook that runs AFTER a node is fully inserted into the database? I want to run some code after a node is inserted into the database.  hook_node_insert() is close, of course, but as the doc says, "when this hook is invoked, the changes have not yet been written to the database, because a database transaction is still in progress".  Is there a hook that I can implement that give me access to the newly-inserted node after it's completely in the database?  hook_path_insert() does this, and is related to what I want to do, but it's not optimal for all sorts of reasons.  Thoughts?

There isn't a hook that is called after the transaction is completed, as the code node_save() executes is executed during the transaction.

function node_save($node) {
  $transaction = db_transaction();

  try {

    // ...

  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('node', $e);
    throw $e;
  }
}

If node_save() is called from node_form_submit() (the form submission handler for the node form), you can add a form submission handler that is called after that. It would be executed after the node is saved in the database.

What the documentation for hook_node_insert() means is that, since the data are not still saved in the database table, you cannot query a table making a join with the "node" table, as that table still contains the old data; in the same way, you should not call a function that queries the "node" table.


How to add extra eventlistener to menu object in attached library This is my first Drupal 8 project and I'm running into a problem figuring out how to attach an extra event handler to an object.
I am working on a custom theme using Radix as base theme. I am using Superfish as menu module.
One of the issues is that Superfish creates an extra 'root' menu called 'Menu' that is shown when the Bootstrap hamburger menu is clicked. You subsequently need to click on 'Menu' to show the actual (accordion) menu.
I found a snippet of code in an issue: https://www.drupal.org/project/superfish/issues/2891228 that hides the 'Menu' toggle, but I cannot get it to work.

I have setup a library definition and created a 'script.js':

import "popper.js";
import "bootstrap";

(function($, Drupal) {
  Drupal.behaviors.helloWorld = {
    attach(context) {
      console.log("Hello World");
    }
  };

  Drupal.behaviors.myMainMenu = {
    attach(context) {
      console.log("myMainMenu: " + context.toString());
      $(".navbar-collapse", context).once('myMainMenu').on(
        "show shown shown.bs.collapse show.bs.collapse",
        () => {
        console.log("navbar-collapse");
        if (!$("#superfish-main-accordion").hasClass("sf-expanded")) {
          console.log('no expand');
          $(".superfish-main-toggle")
            .click()
            .hide();
        }
      });
    }
  };
})(jQuery, Drupal);

I know the script runs, because I see 'Hello World' and 'myMainMenu' + some glob several times in the console. But I never manage to get the other console messages.

I also know the code in the if statement is correct, because, if I run it manually in the console, it works as intended.

What should be the correct code?

Couple of problems. But the main two are:

In Drupal 8, you need to call $.each() on $.once()
In Drupal you don't need to call $.on() on elements. The combination of Drupal.behaviors and $.once() achieves the same goal.

So your code should be something like:

$(".navbar-collapse", context).once('myMainMenu').each(function () {
  // Do stuff here
});


How to add one entity reference field that can reference either a node or a user? I'm looking to create an entity reference field that can reference either nodes from a specific bundle, or users. Is their a way to do this either with a module , or programmatical,y?

I do not think you can do this with the Entity reference module.  Look at its code:

/**
 * Implements hook_field_info().
 */
function entityreference_field_info() {
  $field_info['entityreference'] = array(
    'label' => t('Entity Reference'),
    'description' => t('This field reference another entity.'),
    'settings' => array(
      // Default to the core target entity type node.
      'target_type' => 'node',
      // The handler for this field.
      'handler' => 'base',
      // The handler settings.
      'handler_settings' => array(),
    ),
    'instance_settings' => array(),
    'default_widget' => 'entityreference_autocomplete',
    'default_formatter' => 'entityreference_label',
    'property_callbacks' => array('entityreference_field_property_callback'),
  );
  return $field_info;
}

I suggest you try a work-around.  For example, you could create a content type that includes two entity-reference fields, one of type Node and one of type User.  Maybe, for convenience, include a boolean or integer field indicating which of the two to use.  Then use references to your new content type where you want to use node-or-user entity references.

Alternatively, you could use the Field collection module, which works the same way, creating node types to handle collections of fields:  https://drupal.org/project/field_collection.


How to use inline_entity_form in Drupal 8? I am building 2 custom Content entity types: one is a Node type representing a type of food, called "food". This food may have multiple varieties, which will differ with regards to specific details, so I wish to store information about the varieties in a separate database table, and to accomplish this I have defined a second entity type called "food_type" which serves to provide additional information related to the "food" node.

Within the Food form, I want to also fill out all the fields for the related food_type. I am trying to accomplish this using inline_entity_form.

Following the documentation, I have done the following things for food_type:

Added a dependency of inline_entity_form in food_type.info.yml (there are no other dependencies)
Created food_type/src/Controller/FoodTypeInlineEntityFormController.php, which contains the following code:

namespace Drupal\food_type\Controller;

/**
 * Controller routines for Food Type pages.
 */
class FoodTypeInlineEntityFormController extends EntityInlineEntityFormController {

 /**
   * Overrides EntityInlineEntityFormController::entityForm().
   */
  public function entityForm($entity_form, &$form_state) {

    return parent::entityForm($entity_form, $form_state);
  }
}

Added the following code to food_type_install() in food_type.install:

$entity_info['food_type']['inline entity form'] = array(
    'controller' => 'FoodTypeInlineEntityFormController',
);

Defined '\Drupal\food_type\Controller\FoodTypeInlineEntityFormController::entityForm' as the _controller default under entity.food_type.form in food_type.routing.yml

I cannot enable the food_type module. Attempting to do so yields the following error:

  Fatal error: Class 'Drupal\food_type\Controller\EntityInlineEntityFormController' not found in {directory}\sites\all\modules\custom\food_type\src\Controller\FoodTypeInlineEntityFormController.php on line 9

I assume this is caused because I do not include a use statement in FoodTypeInlineEntityFormController.php for EntityInlineEntityFormController. From Googling, it seems that such a statement is not used in example code that uses this module at all, and it's supposed to simply work when the inline_entity_form module is enabled. However, I for sure have inline_entity_form enabled and am still getting this error.

I would like to try a use statement, but the EntityInlineEntityFormController class does not seem to exist at all in the module code, as far as I can tell from searching. I am using 8.x-1.0-alpha6.

I am very new to drupal development and believe I am probably doing something else wrong, but I am completely at a loss here as to how to proceed or troubleshoot. Can anyone please help me or point me in the right direction?

Thank you in advance.

In order to implement Inline Entity form in D8, all you need to do is set your entity reference field to use the IEF widget - simple or complex. That is all. No additional work.

Here is how we set it up in Drupal Commerce for products, programmatically.

$form_display = commerce_get_entity_display('commerce_product', $product_type->id(), 'form');
$form_display->setComponent('variations', [
  'type' => 'inline_entity_form_complex',
  'weight' => 10,
  'settings' => [
    'override_labels' => TRUE,
    'label_singular' => 'variation',
    'label_plural' => 'variations',
  ],
]);
$form_display->save();

This tells the variations field, which is a Product Variation entity reference, to use IEF as the way to manage field values.


Redirecting Views dynamically generated URL's via .htaccess RewriteRule - CSS stylehseets arent loading after change I have many dynamically generated pages via views and it seems the easiest way to redirect them is using the .htaccess file via a RewriteRule. I put in the following right above the index.php rewriterule and none of the css files are loading anymore. obviously i have something wrong here, but what?

Doesn't the first rewrite fire only if it detects the buy string in the first part of the url? I dont see how that would interfere with anything.

RewriteRule ^buy(/?.*) http://www.EXAMPLE.com/buy$1 [R=301,L]

RewriteRule ^ index.php [L]

actually i put the RewriteRule above the RewriteCond and it seems to be working good now. so it seems that RewriteCond corresponds to the RewriteRule that's right below it only like an inline if statement


Create a log when user join/abandoned in a og group in Drupal 7 I'm creating a log with several actions in drupal.

I need register in a custom log when a user requests to join a group. Then I need register that the user has joined in the group or has abandoned this.

Appreciate any guidance to investigate. Thanks :)

Heartbeat module is the one to try.

I didn't tested it myself, but I read in its description that it's "an API to log activity".

It seems to support OG activity.


How do I pre-configure a block's settings in my module in Drupal 7? I'm building up a custom module which contains a few blocks. These blocks will always only appear either on the front page or on every other page, mutually exclusive.

I'd like to be able to pre-configure these blocks on install, but I'm not sure how to go about it.  The documentation for hook_block_configure mentions an '#options' key, but has no details on the format of that info.

Can anyone get me pointed in the right direction here?

If you want to set the standard block options, you can do that in hook_block_info

e.g:

/**
 * Implements hook_block_info
 */
function MODULE_block_info() {

  $blocks = array();

  // Assign block to front page, sidebar_first region by default
  $blocks['my_front_page_block'] = array(
    'info' => t('Front page block'),
    'status' => 1,
    'region' => 'sidebar_first',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => '<front>'
  );

  return $blocks;

}


How to force forms only through your own submit functions? If I want a custom submit handler, the usual answer is to add the function call to $form['#submit'], and if need be, $form['actions']['submit']['#submit']. The standard warning is do something like

$form['#submit'][]='my_handler';

instead of

$form['#submit']='my_handler';

because you generally want the form submission to still go through the core form submission handlers.

I have a case where I need to completely manage the form submission process and don't ever want the form to be passed to the core submission handlers. To test that I could do this, I have:

global $user;
module_load_include('inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'my_content_type';
$node_form->uid = $user->uid;
$node_form->name = (isset($user->name) ? $user->name : '');
$form = drupal_get_form('my_content_type_node_form', $node_form);
$form['#submit']='';
$form['actions']['submit']['#submit']='';
$render($form);

I would have thought that since there are no submission handlers, the form shouldn't submit, or even if the page reloaded due to the action attribute in the html form element, that the content wouldn't be added to the database.

But it is.

So how can I keep Drupal from processing a submission through the normal core submission handlers, but still process through custom handlers? (I already know how to write custom form submission handlers, so that's not part of this question.)

Since I suggested this in my comment (the first in the thread) I'll rephrase as an answer so that you can mark it as correct.

Rather than using drupal_get_form() to build the node edit form (which just doesn't work the way you tried to do it, as there is no such callback my_content_type_node_form as far as I know) and then modifying the $form array, my suggestion is to:

Let Drupal build your node edit form (you can do this by calling the appropriate URL /node/8/edit or /node/add/[type])
Then use the widely documented way of altering a form by implementing
hook_form_alter.

EDIT: Digging a bit more I did find a hook_form function callback for nodes, but it's standard for all nodes - it's implemented in the node.module as node_content_form(). The hook is invoked in node_form() but as far as I can tell (I did some trials) it's the same for all Content Types regardless of their machine name. I think this may be where the confusion started.


Change date format for the example dates given below date field I'm using Drupal 7, with the latest date module release. I've added a date field to an event node type I created.  However, when I go to create a new event, the example date given (the date format description) underneath the date field uses the American date format of m/d/y. I want to change it so that the example date uses the English date format of d/m/y.  Can someone tell me how to do this.  I did change all the date formats in the date format section to UK date formats, but this hasn't made any difference.  I also changed the timezone to Europe, also with no effect.

I'm sure there is something simple I'm missing?

You can change the format in field settings. Follow below steps to change.

Go to admin/structure/types
Click on manage fields next to your content type
Click on edit link next to the field


Login to drupal with just a number Is it possible to login to Drupal with just a number?

Use case is a kiosk where users have a nfc tag.
So my idea was to hide the input field an use the number retrieved from the nfc tag to identify the users.

The kiosk is only used internally and there would be no keyboard just a touchscreen.

Thanks

You should definitely have a look at the Identification module. Some details (from its project page):

... allows users to login with a custom identification number (or string). To configure this module, the site builder creates a (or specifies a pre-existing) field on the user entity. The value stored in this field for a particular user can then be used as the identification login credential.
Use Case
An organization that wants users to be able to login using a custom identification number and password. This means each user account will have three unique identifiers:

core user name
core user e-mail address
custom user identification number (or string)

Credits (and kudos) to tyler frankenstein!
Note: This answer applies to both D7 and D8.


Drupal database innodb or MyISAM? I have a Drupal site, and I am suffering performance issues. I found How do I convert a database from MyISAM to InnoDB? indicating that performance may improve by switching.

How can I tell if my MySQL database is InnoDB, or MyISAM?

You can run a custom query:

SELECT TABLE_NAME, ENGINE
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'database_name'

to list all the tables in your database and the engine that's in use for each.

Alternatively you could log into your database using phpMyAdmin and select your database...you'll see the engine in the Type column in the list of tables.

Personally I'd recommend Navicat for MySQL, it's a very nice MySQL GUI and makes finding out things like this very easy.

Source: http://www.electrictoolbox.com/mysql-table-storage-engine/


What does -1 signify in system.schema_version? The Drupal 7 {system} table has a schema_version column. Its default value is -1 as indicated by the DESCRIBE system; MySQL command.

Sometimes an update function won't run if the module's schema_version is -1.  For instance, I have site that migrated from Drupal 6 to Drupal 7 quite some time ago.  Recently I found that a database column that should have been introduced by honeypot_update_7100() never ran.  I'm not sure whether or not the version of honeypot at the time of the migration contained that function.  After changing the schema_version to 0, update.php ran that update and the missing column was introduced.  See PDOException Column not found: 1054 Unknown column 'hostname' for similar stories.

Is -1 treated specially?  Do all -1's potentially need to change to 0 for their update functions to run?

-1 means the module is not installed. Updates are only run on installed modules, which is why any update in a module with a status of -1 will not run. If the module is coded properly, when the module is installed, it will be installed in the same level as if all updates had been applied, as updates are used to bring the database in line with the current definition of it in hook_schema().


How can I prevent some configuration settings getting overwritten? I tell drush this:
drush @live cim --skip-modules=system,swiftmailer

and Drush replies with this:
  Collection  Config                 Operation
              swiftmailer.transport  update
              system.performance     update
  Import the listed configuration changes? (y/n)

and, if I reply "y", the settings in the live Drupal site are overwritten from settings previously exported from the dev system.
What do I have to do to avoid importing selected parts of an exported configuration?

I believe that Config Ignore could help you out here.

Spoiler: I am the maintainer of that module.

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

In this case:

swiftmailer.transport
system.performance

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


Search button text not showing in a Bootstrap sub-theme I'm using a sub-theme of the Bootstrap v8.x-3.1 theme.

By default the search button shows the search icon.

In the theme settings you can un-check 'Iconize Buttons' which I expect would show the 'Search' text instead of the icon, however it shows an empty button... no text or icon.

How do I get the button to show 'Search' text instead of an icon?

The solution I found for this was to copy this file from the Bootstrap theme directory

src/Plugin/Form/SearchBlockForm.php

to the same location in your sub-theme.

Then you can set the icon_only property to FALSE.

e.g.

<?php
/**
 * @file
 * Contains \Drupal\subtheme\Plugin\Form\SearchBlockForm.
 */

namespace Drupal\subtheme\Plugin\Form;

use Drupal\bootstrap\Annotation\BootstrapForm;
use Drupal\bootstrap\Plugin\Form\FormBase;
use Drupal\bootstrap\Utility\Element;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @ingroup plugins_form
 *
 * @BootstrapForm("search_block_form")
 */
class SearchBlockForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function alterFormElement(Element $form, FormStateInterface $form_state, $form_id = NULL) {
    $form->actions->submit->setProperty('icon_only', FALSE);
    $form->keys->setProperty('input_group_button', FALSE);
  }

}

I still think there must be an easier way... but until then.


add name field with email to invite block I want to capture the name of the user who is invited by an existing user, along with the conventional email field. This is because I want to use this name in the email that is sent to invited user so that he finds his own name on top of the mail bosy as "Dear 'name'" .

How can this be done?

I'm not exactly positive if this is what you're asking, so if I misunderstood the question, just let me know.

You can add any field you want to the user registration forms if you go right here on your site: /admin/config/people/accounts/fields

So even though there are not any 'First name' or 'Last name' fields by default, you can add anything you want and then get to those fields through views...

Does that help?


View my local site on smartphone and tablet I want to view my website on my iPad and iPhone to take a look how my responsive design looks like. I'm running on a macbook air and I was wondering if there is any type of way to run my local drupal site on the ipad or iphone. I heard you could connect through the ip or somehow. Any ideas?

Anyone done this before?

Go to the terminal and type

  ifconfig

Check for you IP address.

Suppose your drupal url is

  www.localhost/drupal

then go to your iPad and iPhone browser and type

  IP Address/drupal

Using this you could see your local drupal site on iPad and iPhone.


Cash on delivery extra fee I use cash on delivery payment method. When the user select this payment method an extra fee should be added to the order total. NOT to the product line items. Any ideas? I read i a post that a workaround for that is to add a custom line item and charge it the extra fee. Anyway I didn't understand how i should that

I put this code to my custom rule action in order to add a price component via a line item. The problem is it throws an error when i finally save the order in the last line. The error is:

Warning: Invalid argument supplied for foreach() in commerce_price_components_combine() (line 972 of /Users/Sakis/Sites/Under_Construction/e-wireless/profiles/commerce_kickstart/modules/commerce/modules/price/commerce_price.module).

$default_currency_code = commerce_default_currency();
if ($balance = commerce_payment_order_balance($order)) {
   $default_currency_code = $balance['currency_code'];
}
$line_item = commerce_line_item_new('cod_fee', $order->order_id);
dsm($line_item,'line_item');
// Wrap the line item and order to simplify manipulating their field data.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
$line_item_wrapper->line_item_label = 'Αντικαταβολή';
$line_item_wrapper->quantity = 1;
$line_item_wrapper->commerce_unit_price->amount = '200';
$line_item_wrapper->commerce_unit_price->currency_code = $default_currency_code;
$line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
    $line_item_wrapper->commerce_unit_price->value(),
    'cod_fee',
    $line_item_wrapper->commerce_unit_price->value(),
    TRUE,
    FALSE
);
commerce_line_item_save($line_item);
// Add it to the order's line item reference value.
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order.
$order_wrapper->save();

If you create the COD payment method yourself you can in the code that would normally process payments ect. add the fee to the order by adding a line item to the order. You could use a custom price formatter instead of showing the line item.

I have answered how add a line item in code here.


How to display a View Block based on number of characters in Body? I currently have a view that creates an "About the Author" box that pulls information from the user's profile and displays the appropriate author box based on the author of the node (content). I only want to display it on nodes that have a minimum amount of characters in the body of the node. (It currently displays for all nodes the block is enabled for.)

The desired result is that long pieces of content have an "About the Author" box, while short pieces of content do not.

The problem I am having is that when I select the filter criteria for the view, the body field for the node is not listed, so I cannot filter off of it. And I do not see any other way to test how long the content is, in order to determine whether the "About the Author" block should display or not.

How can I make it so the Author Box only appears on long content (i.e. content body > 1000 characters)?

You can use the Views Conditional module. Configure your field to Exclude from display and Apply

Then add the Views: Views Conditional field and configure like this (but with your condition) and Apply

EDIT (after No Sssweat comment):You can combine in your view the Views Field View module to embed a view (your block if you want) as a field in the view.


remove theme tab on blocks for certain roles I'd like to hide/remove theme block tabs for certain roles in drupal.
For example Administrator can edit both theme blocks, but other roles can edit only blocks that are available in their current theme.

Picture:

As you can see on picture, I'd like to hide SEVEN from other roles that are not Administrator ? Any ideas.

Thanks!

function HOOK_menu_alter(&$items) {
  global $user;
  if(in_array('administrator', $user->roles) == FALSE && in_array('admin/structure/block/list/seven', array_keys($items)) == TRUE) {
    // This allows the path to still be registered but not displayed
    $items['admin/structure/block/list/seven']['type'] = MENU_CALLBACK;
  }
}


How to include block using machine name? I created a custom block that I want to include in my template file. But I don't want to include using block id. Is there any way to do it?

I enabled the box module so a machine name is added with each block. I want to add using machine name.

I dont think there are any machine names associated with a block. At least didnt saw it in the database. And by the way, why will you want to use the machine name when you already have an unique identifier like the "bid"/"delta" ??


Entity reference field with custom class I created two content type Writer & Book. Writer has entity reference field that link to Book nodes. When display Writer node, I like the book nodes that attached to it display as list and the first list item has CSS class of "first".

Output the list is simple but I couldn't figure out how to add that CSS class.

If possible, I prefer do it with template.php or node--content_type.tpl.php flies, not using JQuery, Views or another modules.

Appreciate any suggestions, Thanks!

Inside your tempalate.php file, add the following for that field. This is the standard implementation of theme_field. I added the line if ($delta == 1) $classes .= ' first'; to add the class.

function yourthemename_field__yourfieldname ($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables ['label_hidden']) {
    $output .= '
' . $variables ['label'] . ':&nbsp;
';
  }

  // Render the items.
  $output .= '
';
  foreach ($variables ['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    //add your class here
    if ($delta == 1) $classes .= ' first';
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

Furthermore, you can change this for different view modes and different bundles. The rest is in documentation.


How can I reorder meta tags? According to my client's requirement, I need to change the order of meta tags. The requirements are also to hide some of the meta tags.

The order requested is similar to the following one.

<Title>
<Description>
<keywords>

Is there a module to achieve this easily, do I need to edit the files of the Metatag module?

To alter the order of specific meta tags, a hook_html_head_alter() implementation in your theme's template.php file would be your best bet:

function MYTHEME_html_head_alter(&$head_elements) {
  // Combined with the devel module this line will tell you what elements you have to work with
  dpm($head_elements);

  // Any you can just alter the weight like this
  $head_elements['module:key']['#weight'] = -1000;
  $head_elements['another_module:another_key']['#weight'] = -999;
}


how to hide Body Label from webform? I have created a webform, but the Body label shows on the page. How do I remove that label from the form?

Go to "Manage Display" tab in content type page. Hide label there


How to properly add inline js? function prospectpicker_unfollow_init() {
drupal_add_js($prospectpicker_unfollow_path . '/js/stickyMojo.js');
drupal_add_js('jQuery(document).ready(function () {
    jQuery("#unfollow-sidebar").stickyMojo({footerID: "#unfollow-footer", contentID:  "#unfollow-content"});
    });', 'inline');
}

I have included a js file named as "stickyMojo.js", and I want to use that js file's function named as stickyMojo, in order to add the sticky sidebar to my form elements.

Just a suggestion.

As hook_init is only called on non-cached page, and you require this JS to be called on every page; why don't you go ahead and add it to your theme's .info file?

scripts[] = js/stickyMojo.js


Making a username/password syncronization scheme - D7 I need to register my users to a 3rd party service upon registration in Drupal. I have toyed around a bit with hooks, and tried to catch the password upon registration so I can insert it into another database, but to no avail. The 3rd party DB encrypts the password in a different way, so I need to get the users password in clear text, crypt it and then save it to the database.

Can anyone give me some pointers to where I should look? hook_user_insert (&$edit, $account, $category), both $edit and $account contains the users encrypted drupal passwords.

When a form is submitted, its values are validated by the functions listed in $form['#validate'] then processed by the functions in $form['#submit']. If there is no $form['#validate'], then the function FORM_NAME_validate will run (if any). Same for submit.

See user_register_submit. The plain text password is in $form_state['values']['pass']. Write a hook_form_alter and add a new submit function to $form['#submit']. Declare that function and put the logic you need in it.


can I call my entity checkCreateAccess function from custom code? I have several custom entities in my projects.

To check access for certain links, I would like to utilize the checkAccess() and checkCreateAccess() functions in the MyEntityAccessControlHandler classes.

How do I call these from the Controller class or from the module file?

Something like this should do the trick.

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

$entity_type_mgr = \Drupal::getContainer()->get('entity_type.manager');
if (!$entity_type_mgr->getAccessControlHandler($type)->createAccess($bundle)) {
  $permission = "create $bundle $type entities";
  throw new AccessDeniedHttpException("You don't have permission to " . $permission);
}


Difference between creating a Rest endpoint and a route&controller with jsonResponse What is the difference between creating a Rest plugin with the Rest API and creating a route/controller that returns a jsonResponse ?

In which case i have to create a custom route/controller with a jsonResponse ?

The main difference is the authentication and authorization,  is Rest Solution  you should provide different way to authentication and authorization to access to the endpoint. but in Controller,route solution is MVC base solution that drupal and it's ACL  ( role and permissions) hanle the access to the results not REST authorization methods like basic_auth, oauth2  etc.


show amount of results for exposed filter I have a couple of exposed filters to filter the content in my view.
Most of them are taxonomy terms, now i would like to show how many nodes are tagged with that term behind the taxonomy term.

example:

London (5)
Paris (3)
Madrid (2)
...

Any idea how i can do this?

Here is some sample code to do this:

function hook_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id) {
        case 'views_exposed_form':

            $allowed_categories = db_query("SELECT 1 as tid, "Term Name (2)" as `name`")->fetchAllKeyed();
            $allowed_categories = array_reverse($allowed_categories, TRUE);
            $allowed_categories['All'] = '- Any -';
            $allowed_categories = array_reverse($allowed_categories, TRUE);

            $form['field_category_tid']['#options'] = $allowed_categories;

            break;
    }
}

Just change the query to return 2 columns - the tid and the name with a count.


Why nodes are stdClass? My question is a little bit vague. Why do we use stdClass(es) to represent objects in Drupal 7? is there a practical use to it ? Why not just using arrays ?

Generally speaking, objects are used for storing structured data and arrays for lists or collections.
It even logically makes more sense. Node is an object with properties; it's not an array of properties.

See this answer posted on SO as an example.


menu item required to edit content I need to add a menu item in my User menu which provides the facility for users to amend the content of a Content Type ( Sectors) i.e. so they can amend a sector. The User Menu only appears of course for logged in users.

I have tried setting up a menu option in the User menu which links to a View which displays all the Sectors so the logged in user can select one and amend it, this works fine, but the menu option is still displayed for anonymous users as well.

I have 'node/add' for other menu options to create content for content types, they behave properly in the User menu i.e. only appear when a user is logged in, how do I have an edit option for Sectors which only appears for logged-in user in the User Menu?

This is achieved by setting the Permission of the View to Role and selecting the role required.


What is the alternative to file_unmanaged_save_data()? In a custom module, I use this code.
file_unmanaged_save_data($data, 'private://' . $path, FILE_EXISTS_REPLACE);

The documentation for that function has the following warning.

Deprecated
In drupal:8.7.0 and is removed from drupal:9.0.0. Use \Drupal\Core\File\FileSystemInterface::saveData().

So I tried using \Drupal\Core\File\FileSystemInterface::saveData($data, 'private://' . $path, FileSystemInterface::EXISTS_REPLACE),
which gives the Non-static method cannot be called statically.
Adding use Drupal\Core\File\FileSystemInterface; at the beginning of the module doesn't change anything.
In the same page, I found also a link to Unmanaged file functions replaced with a service which explains that file_unmanaged_save_data($data, $destination, $replace)
has been replaced by \Drupal::service('file_system')->saveData($data, $destination, $replace). It seems to work, but I'm still wandering:
Is there another way to do it?

Drupal always documents all the methods using ::, so you need to look closer as to whether the method is static or not.
So if you look at FileSystem::saveData

Its public and not a static. Therefore using ::saveData() is incorrect, needs to be called with the arrow ->saveData()
Also, as pointed out, you need to call it with a class that implements the FileSystemInterface.


Setting Fields Using Rules I couldn't find the answer at How to change a field value with a Rules Action?, so instead of necroing that I figured it would be better to ask here.

I have a Rule that, when a Taxonomy Term of a certain type is created, it creates a node of a specific type. I need the Rule to also have actions that edit a few fields of the node - there's a term reference field I need set to the Taxonomy term that triggered the event, and I would also like to set the body to some generic text (either the term name or "Lorem ipsum...").

I see no "Populate a Field" in the Populating a node reference field using PHP in Rules. I don't need the PHP filter, thankfully.

Is this possible?

The action you are looking for is "set a data value". You will find that some values are easy to set with this and some are not. Install devel (if you havent already) and use the page array functionality to get the exact details about fields you want to fill in. Also make sure to have tokens/entity tokens available as that will make your life a lot easier for setting values in rules. If the field is multi value then you will need to start using variables, lists and loops to fill the field with data.


colorbox not loading images in lightbox I have dloaded libraries 7.x-2.0 in my modules folder and installed colorbox 7.x-2.2 in modules and installed  1.3.26 plugin to sites/all/libraries folder and enabled colorbox in manage display for fields. ALL OF THIS WAS WORKING BEFORE UPGRADE. So started from scratch but when I click on an image it opens lightbox and the image never loads.

The latest version of the colorbox plugin uses a different version string in its js file ( sites/all/libraries/colorbox/colorbox/jquery.colorbox-min.js ) so it doesnt get recognised by the colorbox module requirements check.

If possible look at the version string from the previous file, it's the first line, and copy that over, incrementing the number in the new file.


Drupal Views : Cumulative filtering from an exposed tag cloud Sorry for this newbie question...
I hope you can help.

I need to set up a search result page, with a tag cloud as a filter.
If user select one tag (termX), the matching rows are being displayed.
He could refine his search by clicking on a second tag, to refine it even more (displaying results matching termX AND termY).

Ideally, the selected tags in the cloud, should be visually seen as "selected".

Any idea which module should I rely on ?
Do I need to go through a custom development instead ? Any hints ?

You could use views with exposed filters. You can set filter criteria to "exposed" so the user can choose which filter he would like to have. With the module "Better exposed filters" you have the possibility to format for example a select list as links.


At user creation set different default timezone When a new user applies for an account, how does one set the timezone default from 'America/Denver' to 'UTC' timzeone?  It's ok to allow the user to change the timezone to a preferred timezone.  However, most of my users will be signing up from the UK.  Is there a way to set the default to UTC rather than America/Denver?

Try visiting admin/config/regional/settings to set default timezones.

I've also created a module called Timezone Detect that will detect and set user timezones automatically using javascript.


How do I limit validation errors to submission buttons? Using hook_form_alter I have tried to add limit validation errors to workflow submission button.

In form alter I'm getting two form_id's one is normal node add form_id and
another is workflow state form_id.

$form['actions']['workflow_course_status_save_as_draft']['#limit_validation_errors'] > = array(array('field_sample_course'));

I did exactly the same but we were wrong in the usage of #limit_validation_errors.

The reason why this is failing is that we're not using properly #limit_validation_errors. This issue has nothing to do with Workflow.

During the form validation, if this property is set (validation errors are limited), Drupal core will remove any non validated form values from the form state, so only values that passed validation will be left for submit callbacks.

For Drupal 8:
http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/Form/FormValidator.php#n147

For Drupal 7:
http://cgit.drupalcode.org/drupal/tree/includes/form.inc?h=7.x#n1193

My solution was to add a custom validation that will be executed at end of all validations, and in there remove all form-related errors:

/**
 * Removes all validation errors that could happen when saving a draft
 *
 * @param $form
 * @param $form_state
 */
function my_custom_draft_validation($form, &$form_state) {
  $errors = form_get_errors();

  if (!empty($errors)) {
    $messages = drupal_get_messages('error', TRUE);

    // Remove error messages originated during the form validation
    foreach ($messages['error'] as $error) {
      if (!in_array($error, $errors)) {
        drupal_set_message('error', $error);
      }
    }

    // Remove all form errors
    form_clear_error();
  }
}


Nivo Slider jQuery plugin Not installed I´m trying to install Nivo Slider to my website. I was following this tutorial from the official plugin website.

I have the folder "all" an inside it I have "libraries", "modules", and "themes". I extracted the FlexSlider-master.zip in my libraries folder, and rename it to "nivo-slider".

The second step was install the extension from the url drupal/project/nivo_slide without drush, download the folder an upload to my server in modules/.

I have clear the cache but the problem persist.

Can someone help me? I can´t upload pictures or links with less than 10 reputation.

If it's drupal 8, which sounds like it, your libraries folder needs to be outside of the sites folder. Where you main Drupal stuff is, like the modules folder.

ex: Needs to be drupal/libraries and not drupal/sites/libraries

The drupal/sites/libraries is only for Drupal 7.


Views: link to an admin page I want to print a link in place of a field in case of No Results Behaviour.

The link is to admin/commerce/products/add/, but drupal always add /content/ before my relative address.

I've try different attempts, but so far the only solution I've found is to write the absolute path.

If you want a proper relative path your url must start with a / at the beginin of your url like this : /admin/commerce/products/add/


How to search on date ranges using apachesolr module? I have a drupal site which have some events.

I am using apachesolr module for searching the site. Currently two fields are used for searching "keywords" and "location". Now I want to add the date field and when I click the search button it also query the search based on the date selected in the date field.

Suppose If I selected a 10/01/2011(m/d/Y) in the date field It should display the events with date 10/01/2011 or greater.

Any Idea?

Take a look at the Lucene search syntax, for dates use a filter query like
created:[2011-10-01T23:59:59Z TO 2011-10-31T14:11:00Z]


Why does drupal_add_css and drupal_add_html not always work? I have a drupal_add_css in my template.php, following a series of drupal_add_html calls.

The drupal_add_html calls, adding meta tags, work except for the first one (regardless of the order I put them in) which is for a meta generator tag, which the jquery form library I'm using requires. I've also tried getting it in by doing the call for markup rather than a tag...same...it doesn't appear.

The drupal_add_css call does not add the css file (I'm not aggregating), even if I specify the full url. If I add the css file to the list in the .info file, it appears, but I only want the file for a specific page, so I'm doing in the pre-render. When the file is not added, there is no reference to it in the page resources or network list as 404. It does get referenced in the js behaviors object that Drupal inserts.

It turns out that it's a known problem that core provides a generator metatag without an option of replacing or disabling it. The metatag module will do this, or removing it in a custom module via hooking html_head_alter.

I'm not quite certain why drupal_add_css would not work, but adding it with drupal_add_html_head worked.


Hierarchical taxonomy structures I am wondering about how to set up hierarchical taxonomies.  For example say I have a vocabulary called Vehicle Make which consists of terms Audi and Honda, then I have a further vocabulary called Vehicle Model which consists of A4, Civic and Accord.  So now say I wanted to create a vehicle registration content type with term reference fields corresponding to the two vocabularies listed above.  Is there a way to define an is-a relationship between these vocabularies, I.E. an Accord is a Honda and an A4 is an Audi and therefore the selection in the Vehicle Model term reference would be dependent upon the selection in the Vehicle Make term reference.  So if I select honda for the make I should be able to select Accord or Civic for the model and if I select Audi I should be able to only select A4.  Is this something that can be done with Drupal taxonomy system?

You can construct your hierarchy using the core module taxonomy.  Go to admin/structure/taxonomy, create your vocabulary and add your terms. The form that lists your terms precedes the name with a graphic arrow widget (points in four directions.  Selecting that widget and dragging can reposition the terms in parent child relationships, and your done!  The Taxonomy Manager module can help you add large quantities of terms to a vocabulary very quickly as well.


How to create a node based on views results I'm looking for a way to accomplish the following:

Use views to select users that match a certain criteria.
Create a "campaign" targeted at only those users. The campaign should ideally have all users' names/ids attached to it.

Many thanks.

I think you need 2 relationships in Views. One that targets your field that points from user to the campaing. Second, with the author, based on the first relationship.
After, add as fields user names.
Not really sure about your structure so that was just a supposition.


Assign User Points in existing website which already contains content Question specific to "User Points" module, backcopy of question from here due to no response: https://www.drupal.org/node/2492933

Drupal 7 -

I have a website which is already running for more than 2 years. Many users have been adding content to it and now I have a requirement where I need to assign points to the user. I came across this great module but this does not let me assign values to the user based on the content they have already contributed, revisions already worked on and also the comments provided already.

I have tried to google and also checked the module thoroughly but there is no way to do what I want to achieve. Is there a way to achieve this?

I think User Points Contributed modules is your best alternative available today. I. e. submodule userpoints_retroactive. Excerpt from that project page:

  Award users points for their nodes, comments and votes that they have created so far, before userpoints was enabled on the site.

However, the port of this module to D7 still needs work. Maybe you can/want to somehow contriute to the finishing touch of that issue?

PS: there is also Berdir's Api documentation about this submodule ... (maybe that helps somehow).


How to send dynamic content as an attachment file in email? Normally we send files as attachments in the email if they are stored in the file system.
$file->uri = 'sites/default/files/file_name.pdf'; // File path
$file->filename = 'file_name.pdf'; //File name
$file->filemime = 'application/pdf'; //File mime type
$params['attachments'][] = $file;
$mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

But I have dynamically generated content.
$content = <?xml version="1.0"?>
<root><element>element value</element></root>

I want to send it as an XML file attachment in the email. How can I do this?

I have found the answer.
Here is my code.
$content = '<?xml version="1.0"?><root><element>element value</element</root>';
$params['attachments'][] = [
  'filecontent' => $content,
  'filename' => 'data.xml',
  'filemime' => 'application/xml',
];

and then in hook_mail
function mymodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'my_email_key':
      $message['body'][] = $params['body'];
      $message['subject'] = $params['subject'];
      $message['params']['attachments'] = $params['attachments'];
      break;
  }
}

BTW I am using the swift mailer module.
Hope this helps someone.


Display message to authenticated users I have a Drupal site and my problem is that it doesn't display error messages when authenticated users are filling in, but they display with the administrator users.

An example of the messages I am referring to is "image size too exceed […]."

How can I make the error messages appear for every users?

Use Disable Message Module. and set permission for user roles you want.

  Gives a site owner options to disable specific messages shown to end
  users. The core drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all drupal site owners are keen to show all the messages
  sent out by drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.


Change display order of a content type fields in the view tab How can i change the order of displaying fields details of a node of a content type in D8 ? Its neither specified in the Manage form display or in the Manage display of the content type management menu .

PS : I have added existing fields from another content type to this content type . Will that's display order taken in to this ? How can i change this ?

The fields are sorted by weight, which is hidden by default, because you can reorder the rows by dragging. You can switch off dragging and input the weights by hand with Show row weights.

Doesn't matter if the fields are used in multiple content types, you can arrange them in each content type individually.


How to prevent installation to run from UI? I have an installation profile that will be installed purely via Drush/CLI. So I need to prevent anyone to run the installation from web interface.

What would be the best approach?

Just specify hidden: true in the info yml file


Managing Abusive/Report User I have setup flags so a user can report another user as abusive/offensive. I need a way to manage to flags. I would like to be able the view all the users that have been flagged and and remove the flags. I have tried to do this with views but I could not find a way to remove the flag.

Look at the answer in this question: Flag module views integration

It seems to be possible with relationships, though I would guess that this depends a little on your flag configuration.


How can I embed a view in an email sent by Rules without resorting to the PHP filter? I want to embed a view in an email sent by the Rules module using the standard "Send mail" action.  I have the Mime Mail and Mail System modules installed, and I can send HTML email when it is included in the body of a rule.

Based on this question, I tried the Insert View module, but that only allows views to be inserted into node content, not rules (which are entities, but Insert View does not support generic entities).  I tried adding [view:view_name=display_name] to the message body of my rule, but the view did not appear.  To make sure it wasn't working, I added another rule with the "show a message" action and tried to embed the view there, which also didn't work.  However, I can place the exact same code inside a node body and the view DOES appear, so it appears that Insert View does not work with Rules.

Entity Views Attachment does support generic entities, but this "attaches" the view, whereas what I am trying to do is embed the view in a rule's email message body like this:

  MY TEXT - HEADER

  EMBEDDED VIEW

  MY TEXT - FOOTER

I also only need to do this for one email, so if possible, I would like to add something like a custom token for Rules to embed the view, but I'm not sure how to go about that.

Using Insert View, Mime Mail and Mail System module, you can send views in emails.
After installing and enabling the above modules, you will need to configure Mail System settings and Text Format settings.

In the Mail System settings,
Change all settings to use MimeMailSystem class to send mails.
Note: Site-wide default MailSystemInterface class should be MimeMailSystem.
In the text formats settings,
Enable Insert View Filter in each text format you require.

The problem for you isn't with the rules. It should be the Mail System settings.
I hope this would work.


Hooks called after installation profile is installed? I'm stuck writing an installation profile.
There are certain things that I want to do only after the installation is completed.

I analyzed top ten installation profiles and checked the documentation, but I couldn't find it. I might be missing something small though.

Is there such hook? If not, how can I execute something at the end of the installation?

Thanks!

UPDATE

I know for hook_install and hook_install_tasks, and they are not exactly what am I looking for.

They both are called during the installation. I want to execute code after the installation has been completed.

For example, setup Backup & Migrate schedules. If I do this using hook_install_tasks(), the cron run at the end of installation does not seem to work properly/in full, and I get errors when backup_migrate tries to write to private directory. Private directory is set up properly and if I just re-run the cron afterwards, it works as it should.

Move your post-installation hooks to a module/part-of-your-profile (that can implement any hook and move things around even after the system modules is installed).

That way you can overcome problems like custom block's BLOCK_VISIBILITY_LISTED not working on profile installation hook_install()?, and have a solid last installation step, that makes all your final configs.

bonus * why not even choose or make configs in that installation step's form_alter() ;)


Expand region to fill screen size I have a splash page where the user will choose a language before entering the site.
This page only needs the header region and a background image (for the #main-wrapper div) that should occupy the rest of the screen size.

I'm using

#main-wrapper {
    background: url('img.jpg') center no-repeat;
    height: 100%;
    width: 100%;
    background-size: cover;
}

But it doesn't fill the available space, only the #main-wrapper div, so I end up with a grey area below the background image, where the footer should be.

Is there a way to make this region expand all the way to the bottom (I don't need the footer in this particular page) without declaring it's height in px?
I want to avoid scrollbars when not necessary, and have the image fill the space when resizing the window or viewed on mobile.

Is it possible to do this with Bartik theme?

EDIT:

I've already hidden the footer, but that doesn't make the #main-wrapper div reach all the way to the bottom. I still get a blank space below it.

You could style that special page with css to not display the footer (display:none). Drupal delivers a css class in the body tag that identifies the current node, like so .page-node-x, where x is the node id of the page. So you could go like page-node-x .footer.

You could also use a page.tpl override for the specific page where you remove the footer region. Create a copy of page.tpl.php in your themes template folder and name it page--node--x.tpl.php. Remove footer in this file completely.

And as for fullsize background image, maybe this module could be interesting: https://www.drupal.org/project/supersized


show field of entity for editing according to path I have an entity with many field (about 200) collecting information about buildings (area, height, conditioning system, ...)
my client has asked me to show specific fields in groups for editing, where user can choose from menu "group 1" and see only those fields
it is also possible that users will only visit some groups they want, and leave some of groups un-edited for later
how do i show specific fields of one entity, according to path? /node/1/edit/g1 for fields 1 to 20, node/1/edit/g2 for fields 21 to 30 and ....

extra info: i'ts not about permissions at all, the same user, will fill group 1 today, will comeback tomorrow and fill group2 if wanted to
field collections looks promising, can it do that? instead of deciding by user permission, deciding by path?

One way to do it is by using field gropups and custom permissions.
Start by installing field groups module to make it possible to group your fields at all.
Move your fields into different control groups and use for example tab groups and tab items in a way to make the editing page pleasing.

If you want detailed asccess rights for different user groups, add some code to do this.

Add your own permissions by using hook_permissions()
For example

function my_module_permissions() {
  return array(
     'edit group1' => array(
      'title' => t('Edit group1 section'),
      'description' => t('Edit field group group1 in Building.'),
     ),
   );
}

In a hook_form_alter() function, you can hide/show field groups like this:

// Check if the current user has rights to see this group and its fields
if(!user_access('edit group1', $user)) {
 // Loop through all group fields and hide them
 foreach($form['#groups']['group1']->children as $index => $groupField){
   $form[$groupField]['#access'] = FALSE;
 }
}

You don't have to hide the group itself, hideing all it's fields will render it invisible.

Then it's just a matter of settings the right permissions to the right user groups.

Pros:

Detailed permissions just for the things you need
Field groups are pleasing to use :-)

Cons: You need to do some coding

Second way

An other way is to use field collections module where a collection itself will be treated as fields in a sense. I guess by adding field permissions you will be able to control each fild collection's permissions.

Pros: no coding :-)

Cons:

By adding field collection you adding a new layer of abstraction wich might complicate things for you later on.
field collections isn't supported by all modules you might use - check it before starting this path.
It will get a bit messy in the permissions hanlding page


How do I change the default configurations for the node options? I want to change some default configurations for the node options; for example, the authoring information has 'Authored by' field which is defaulting to auto-complete authors. I want to change this to a drop down instead.

Is there a module that can do this? I learned that editing a module is not advisable, and I cannot find modules that can override default configurations anywhere.

Unfortunately in that case, I guess that you should do your own module and use hook_form_alter()


How to apply multiple sort criteria on views? I have created a view where I used

  Display a specified number of items | 5 items

And I have 2 sort criterias.

  SORT CRITERIA

  Add sort criteria

  List additional actions Content:

  Authored on (desc)

  Content: Page Views (desc)

What I want is sort criteria 1 should be applicable on first 3 rendered items, and sort criteria 2 should be applied on next 2 items. So here right now, total 5 items are displaying. From them, I want first 3 items to pass from sort criteria 1 and other 2 items from sort criteria 2.

How this can be achieved?

One of the solutions can be using 2 views and use one view as footer attachment to the other view

View 1 with sort criteria 1 (no of items 3)
View 2 with sort criteria 2 (no of items 3)

For View 1 footer, use View 2


Split node edit tab in several tabs with panels (or programmatically) I have a content type with many fields, so that loading node/%node/edit is a pain ! In order to split node edit form in smaller forms (menu tabs), I used Page Manager.

What I did so far

Enable the Node add/edit form coming with Page Manager, with selection rule node being edited is from foo_type
Add three new custom panels pages in admin/structure/pages, with paths /node/%node/photos, /node/%node/prices, /node/%node/fd ; with selection rule node being edited is from foo_type
Define its menu as local menu tab.
Share foo_type fields between these forms, and add a submit node form to each.

This renders correctly three node edit forms accessible in new local task menu tabs :

The buggy part

If I edit the node from any of these forms :

the fields present in it are saved
the data from other fields saved before is still in the database, and also readable in the form fields if I show up the other forms (except for pictures), but it is not displayed anymore in the node.

As per @Letharion comments : " [...] while Panels happens to let you output only half the form as well, that is not supported by form api. One way or another, every field must be present. If not, form api will interpret it as "the user deleted the content of those fields" [...]

The question

I'm searching a way to patch the current solution, or a fully programmatic way to split node edit into tabs. Thanks for your contribution!

Edit:

Most of the issue is solved thanks to flexiform, except for inline entity commerce products. So I'm trying with MrD answer for this specific field, as exposed below.

The commerce product is saved (corresponding DB tables commerce_product, field_data_commerce_price and so on have a new record), but not attached to its product display (and no record in field_data_field_product). No error is returned.

How to correctly save that commerce product so that it is attached to its node display ?

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

  $items['node/%node/prices'] = array(
    'title' => 'Prix et dates',
    'page callback' => 'node_page_prices',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('update', 1),
    'weight' => 4,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  );

  return $items;
}

function node_page_prices($node) {
  $form = drupal_get_form('vts_nodedit_form', $node, 'field_product');
  return $form;
}

function vts_nodedit_form($form, &$form_state, $node, $field_name) {
  $form = array();
  field_attach_form('node', $node, $form, $form_state, NULL, array('field_name' => $field_name));
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );
  return $form;
}

function vts_nodedit_form_submit($form, &$form_state) {
  $node = $form_state['build_info']['args'][0];

  //retrieve commerce product to be saved... NON DRUPAL way... :(
  $item = key($form_state['inline_entity_form']);
  $entities = end($form_state['inline_entity_form'][$item]['entities']);
  $product =$entities['entity'];//this is the correct product entity
  //SAVE THE COMMERCE PRODUCT
  commerce_product_save($product);
  //MrD solution
  field_attach_submit('node', $node, $form, $form_state);
}

It sounds like you have done a lot of work already, and this continues to be a learning experience.  Since the form is now managed how you want it and it is only the data management in the save process that is causing you trouble, I would suggest a few code additions.  Using hook_form_ID_alter there are two methods you can try.

Method 1 Add a custom validation callback to the form.

$form['#validate'][] = 'MYMODULE_node_data_validate';

Then in your new validation function I suggest loading the node ($node = node_load(nid);) and propagating the data into the form_state.  I am not sure this will work, but I have it listed as method 1 because it is the less disruptive path of the two that I have in mind at the moment.

Method 2 Replace the submit handler with your own.  Similar to the validate function mentioned above, the idea here is to load the node to get the data that was not present on the form that you edited.  However, this time you are going to invoke node_save yourself.  Also you will need to end with a drupal_goto or some other method of sending the user someplace.  Yes you could add an additional handler to the #submit array in the form variable, but either it will be too late to prevent the change the form is doing or it would just be a different name for method 1.

function hook_form_ID_alter(&$form, &$form_state, $form_id) {
    $form['#submit'] = array( 'hook_something_submit');
}
/**
 * Implements hook_form_FORM_ID_alter();
 */
function vts_nodedit_form_accompagn__node_form_alter(&$form, &$form_state, $form_id) {
    $form['#submit'] = array( 'vts_nodedit_data_submit');
}

function vts_nodedit_data_submit($form, &$form_state) {
  // possible cause of missing data is that the form build populates
  $original = node_load( $form_state['node']->nid );

  // this drupal core function does the work of a full node edit save
  // but we have to have the node to hand it
  // and I do not trust all of $form['node'] in your instance
  field_attach_submit('node', $original, $form, $form_state);

  drupal_set_message(t('The changes have been saved.'));

  if( isset( $form_state['redirect']) ){
    drupal_goto( $form_state['redirect'] );
  } else {
    drupal_goto( '/home' );
  }
}

EDIT
The difference between form_state['input'] and form_state['values'] is that input is the raw $_POST from the user.  I think it would be a security concern to use that directly.  The other validators that are running (why we use $form['#validate'][] and append instead of replace) are taking the new data from input, cleaning it, and putting it in values.  Then if there are blank spots, they fill values with #default_value of the node.  Default is typically the existing value.  Therefore, a submit handler can ignore form_state[input] and have the benefits of drupal in just the form_state[values] array.
Input vs Values


Parent-child node relationship without using taxonomy? I'd like to be able to offer sub-site maintainer's the ability to create their own sections of content. I can use a hierarchical taxonomy tree to force multiple levels of content to be classified at different depths of the site. However, I'd rather not be on the hook for revising custom nested term lists for each maintainer.

Is there an easy way to allow publishers to create parent node <-> child node relationships without relying on taxonomy revisions?

I'm using Drupal 7 and Node Hierarchy is unfortunately not yet out of development for D7.

You can use Entity Reference module.

You create two content types: Parent and Child.

in Child content type, add an mandatory "Entity Reference" field that reference to a Parent node.


Filter nodes by entity reference I have an article content type linked to an event content type via entity reference.

In the Articles view, I would like to offer a filter allowing to filter articles by linked event title.

With Drupal 7, we used to manage it with better_exposed_filters module but I can't find a way to do it in Drupal 8.

Here is the my solution inspired from:

http://www.webomelette.com/creating-custom-views-filter-drupal-8
http://www.sitepoint.com/drupal-8-version-entityfieldquery/

Thanks to Danny Sipos

I already had a dedicated custom module for this project where I added the following:

mymodule.views.inc

<?php
/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(array &$data)
{
    $data['node_field_data']['related_content_titles'] = array(
        'title' => t('Related content titles'),
        'filter' => array(
            'title' => t('Related content titles'),
            'help' => t('Specify a list of titles an content node can have.'),
            'field' => 'nid',
            'id' => 'mymodule_related_content_titles'
        ),
    );
}

src/Plugin/views/filter/RelatedContentTitles.php

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\ManyToOne;
use Drupal\views\ViewExecutable;

/**
 * Filters by given list of event title options.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("mymodule_related_content_titles")
 */
class RelatedContentTitles extends ManyToOne
{
    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL)
    {
        parent::init($view, $display, $options);
        $this->valueTitle = t('Allowed event titles');
        $this->definition['options callback'] = array($this, 'generateOptions');
    }

    /**
     * Helper function that generates the options.
     * @return array
     */
    public function generateOptions()
    {
        $storage = \Drupal::entityManager()->getStorage('node');

        $relatedContentQuery = \Drupal::entityQuery('node')
            ->condition('type', array('event', 'story'), 'IN')
            ->condition('status', 1);

        $relatedContentIds = $relatedContentQuery->execute();

        $res = array();
        foreach ($relatedContentIds as $contentId) {
            $res[$contentId] = $storage->load($contentId)->getTitle();
        }

        return $res;
    }
}

When ceating the view listing my articles where I want to expose the related event filter I had to :

add a relationship field_article_associated_event: Content
add a filter criteria of my type Related content titles, select the perviously cerated relationship for the field Relationshi, check Expose this filter to visitors, to allow them to change it


Drupal File upload only allowing one upload at a time I'm having a problem with the File widget. I have created a content type with a file field that allows unlimited values. When I upload a file I am expecting to be able to immediately upload another file.

but what actually happens is the upload box disappears, meaning I have to save the node and re-edit it in order to upload another file

both these example have exactly the same content type settings, both running the same version of Drupal. I'm not getting any JS errors or anything. Any ideas on why this is happening? I've even updated all my modules and drupal core and tried disabled all my theme's JS files, still have this issue.

Probably same issue as here
https://drupal.stackexchange.com/a/112999

As suggested in the post above,
you should consider Plupload and file field sources, you'll never look back,
imagine dragging 10 files from your explorer/finder to your form field and uploaden them all at once ... ;)


Use of pattern in hook_theme() I'm trying to implement pattern but It doesn't work.
Here is the implementation of hook_theme() with my pattern:

Call theme('publication__' . 'news', array('bean' => $bean));

in file atom_publications.module

function atom_publications_theme() {
  return array(
    'publication' => array(
      'variables' => array('bean' => NULL),
      'pattern' => 'publication__',
      'file' => 'atom_publications.theme.inc',
      'preprocess functions' => array('atom_publication_custom_preprocess'),
      'template' => 'publication',
    ),
  );
}

In file atom_publications.theme.inc write this code:

function atom_publication_custom_preprocess(&$variables) {
}

Files in module dir:

publication.tpl.php
publication--news.tpl.php

But render only publication.tpl.php template. Why?

Looking at theme(), I notice that the "pattern" property is never used. What the function does is using the following code.

  // If there's no implementation, check for more generic fallbacks. If there's
  // still no implementation, log an error and return an empty string.
  if (!isset($hooks[$hook])) {
    // Iteratively strip everything after the last '__' delimiter, until an
    // implementation is found.
    while ($pos = strrpos($hook, '__')) {
      $hook = substr($hook, 0, $pos);
      if (isset($hooks[$hook])) {
        break;
      }
    }

In your case, theme() first looks for publication__news key in theme functions array, and then it looks for the publication key. As in your case there isn't any match for publication__news, it uses publication, and the template file associated with that theme function.

This is documented in theme().

  If the name contains a double-underscore (__) and there isn't an implementation for the full name, the part before the __ is checked. This allows a fallback to a more generic implementation. For example, if theme('links__node', ...) is called, but there is no implementation of that theme hook, then the 'links' implementation is used. This process is iterative, so if theme('links__contextual__node', ...) is called, theme() checks for the following implementations, and uses the first one that exists:

  links__contextual__node
  links__contextual
  links

  This allows themes to create specific theme implementations for named objects and contexts of otherwise generic theme hooks.


Cannot seem to get hook_preprocess_page to work in 8.4.2 Why do I get to the breakpoint in MYMODULE_preprocess_page_title but not in MYMODULE_preprocess_page?

What I am tying to achieve is to update page title both on the top of the page and in the browser title bar/tab name.

The following code only affects the title on the top of the page.

function MYMODULE_preprocess_page_title(&$variables) {
  $variables['title] = 'Something Different!';
}

I've read some people are saying hook hook_preprocess_page instead to update both.

I tried to find what are the available hooks like hook_preprocess_blabla starting here, but couldn't find my way in the documents to the list of available hooks.

both should work on custom MODULE or THEME

function MODULENAME_preprocess_page(&$vars) {
  //do stuff
}

function MODULENAME_preprocess(&$vars, $hook) {
  if($hook == 'page') {
    //do stuff
  }
}

You need to rebuild cache and at least when using netbeans be careful not all lines will trigger the breakpoint ... for example I have noticed that multiline array definitions will not trigger it.  Post your code for more details


How to remove tags from display in form? I have this form tempate

    {{ form.card.a }}

    {{ form.card.b }}

and I want to to frame it with  tag like this.

        {{ form.card.a }}

        {{ form.card.b }}

so I made

$form['card']['card_link'] = [
  '#type' => 'item',
  '#markup' => $this->getCardLink(), //returns integer
];

But it still doesn't show what it supposed to.
It inserts
needed integer
 inside href="<here>"

How should I fix this?

The item element type is a form element, Drupal\Core\Render\Element\Item.

This means that it gets a form element wrapper by default.

Rather than rendering the  wrapper in the Twig template, you could include it in the render array, and add form.card.a and form.card.b as its children:

// In your form handler class

function buildForm($form, $form_state) {
  // ...

  $form['card_link'] = [
    '#type' => 'html_tag',
    '#tag' => 'a',
    '#attributes' => [
      'href' => '/card?id=' . $this->getCardLink()
    ],
  ];

  $form['card_link']['a'] = array_merge($form['card']['a'], [
    '#prefix' => '
',
    '#suffix' => '
',
  ]);

  $form['card_link']['a'] = array_merge($form['card']['b'], [
    '#prefix' => '
',
    '#suffix' => '
',
  ]);

  // ...
}

The template then simplifies to this:

{{ form.card_link }}


Getting the URL for every language I have a route of a page, and I want get the link for it on every language of my site.

On my site the contact page is: en/contact for English, and es/contactenos for Spanish.

I am trying using the following code, but I am getting just the URL for the current language set for the site.

$route = 'contact.site_page';
$url = new Url($route);
$uri = $url->toString();

How do I get it for every language available for the site?

I found the solution myself, with the following code.

// Get all languages of the site
$languages = \Drupal::languageManager()->getLanguages();

// Route of contact for example:
$route = 'contact.site_page';
foreach ($languages as $language) {
  $url = new Url($route, [], ['language' => $language]);
  $uri = $url->toString();
}


Modules and namespaces I have strange problem or maybe I'm doing something wrong. I've create my own module. My .info file looks like this:

...
files[] = DdFactory.inc
files[] = ArticleManager.inc
...

In ArticleManager.inc I have class ArticleManager (no namespace). Than I would like to use DFactory (namespace Dd) class in ArticleManager.

Here is the beginning of DFactory.inc:

<?php

namespace Dd;

class Factory
{
...

In ArticleManger I have:

$ob = new \Dd\Factory();

And error:

Fatal error:  Class 'Dd\Factory' not found

I can make it work in two ways. Or I have to remove namespaces than $ob = new Factory(); or I have to add include 'DFactory.inc' at top of ArticleManager.inc

Could somebody tells me how to run it with namespaces and without the include? I'm using drupal 7.

Try the xautoload (http://drupal.org/project/xautoload) module to help with autoloading. It's faster and less fragile then the D7 core code registry.

XAutoload implements the PSR-0 standard, which is how Drupal 8 will handle namespaces, so it's the most future proof way.


How to use hook_views_query_alter to catch last DELTA of a multivalue date field? I need a View that should list only past events.

Events have multivalue date fields, so an event can have multiple "start" and "end" dates.

Date's API assign a DELTA value to every group of "start" and "end" dates.

In my configuration, an event is consideret "past" if its very last (= last delta) end date is < of "now" (= today)

With default Views UI it seems impossible to catch LAST delta of group of dates for a record.

(see some answers by Merlinofchaos here: https://www.drupal.org/user/26979)

My UI views provides the following query:

SELECT field_data_field_period.delta AS field_data_field_period_delta, field_data_field_period.entity_id AS date_id_field_period2, field_data_field_period.delta AS date_delta_field_period2, node.created AS node_created, node.nid AS nid
FROM
{node} node
LEFT JOIN {field_data_field_period} field_data_field_period ON node.nid = field_data_field_period.entity_id AND (field_data_field_period.entity_type = 'node' AND field_data_field_period.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('exhibition')) AND (DATE_FORMAT(ADDTIME(field_data_field_period.field_period_value2, SEC_TO_TIME(7200)), '%Y-%m-%d') < '2014-07-16') ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0

With some tests with pure SQL directly on DB, I noticed that I can obtain the results I want with the following changes to the query:

SELECT MAX(field_data_field_period.delta) AS field_data_field_period_delta, field_data_field_period.entity_id AS date_id_field_period2, field_data_field_period.delta AS date_delta_field_period2, field_data_field_period.field_period_value2 AS field_data_field_period_field_period_value2, node.created AS node_created, node.nid AS nid
FROM node
LEFT JOIN field_data_field_period ON node.nid = field_data_field_period.entity_id AND (field_data_field_period.entity_type = 'node' AND field_data_field_period.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('exhibition')) ))
GROUP BY nid
HAVING MAX(DATE_FORMAT(ADDTIME(field_data_field_period.field_period_value2, SEC_TO_TIME(7200)), '%Y-%m-%d')) < '2014-07-15'

In the above please notice:

field_data_field_period.delta becomes MAX(field_data_field_period.delta)
Added clause "GROUP BY nid" and "HAVING MAX(DATE_FORMAT(ADDTIME(field_data_field_period.field_period_value2, SEC_TO_TIME(7200)), '%Y-%m-%d')) < '2014-07-15' "

After hours of research I understood I have to use hook_views_query_alter to alter my views query, but the modification I need are very complex and I don't know where to start...

Please help me.

This can be done with HOOK_views_query_alter(). Add all the fields as normal within the views UI, including filtering on the date field value. Make sure the entity ID is in there (in your case, nid is in the query) and the date's delta field.

Next, add a WHERE clause on the delta in hook_views_query_alter() using add_where_expression():

function MODULE_views_query_alter(&$view, &$query) {
  // Check for correct view
  if ($view->name == 'view_name' && $view->current_display == 'display_name') {
    $query->add_where_expression(0, 'field_data_field_period.delta = (SELECT MAX(field_data_field_period.delta) from field_data_field_period WHERE entity_id = nid)');
  }
}

This assumes the filter should be in the first filter group (0).

References:

https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7.x-3.x

https://api.drupal.org/api/views/plugins!views_plugin_query_default.inc/function/views_plugin_query_default%3A%3Aadd_where_expression/7.x-3.x


Lightbox gallery is not working in mobile website I am using D7 and lightbox2 for image gallery.

I'm using same in the mobile version too. But the lightbox popup is not opening and showing in mobile browsers. It will work sometimes and will never work on another occasion. What is the reason of this issue?

Using Lightbox2: lightshow:thumbnail->original  in content filed display, I used other options, but showed the same issue.

After that is used colorbox, it's working ok but when we close the popup window the parent window is blank and showing the same error undefined

  undefined

Also the page url is changed to the image url. E.g.,
www.site.com/sites/default/files/DSC_0164.jpg

Mobile jQuery 7.x-2.0-beta1 (default mobile theme by Mobile Switch)

How can I overcome this issue? How can I open image in modal window. It was working perfectly before, now it's showing the problem.

At last I found an alternative solution for image gallery:

Photoswipe,it is working for me...(Compatible with lots of mobile devices and all popular JavaScript libraries and development frameworks. )

http://www.photoswipe.com/

sample:

http://www.photoswipe.com/latest/examples/04-jquery-mobile.html


How to display different sets of images per page in sidebar? I'm trying to show different sets of four images in sidebar depending on which page a visitor is viewing. Aside some trouble I'm wondering whether a proper workflow should be as follows:

Create "Four Images" content type set up as a single multiupload image field.
Create "These Four Images", "Those Four Images", etc. content.
Create as many views as content units in step two set up as a grid block.
Add every block to sidebar in Block Design and restrict each block to be displayed using "Visibility->Pages".

So I'm getting a Sidebar in Block Design rapidly filled with four images views. Is there any other cleaner way of doing this?

Create as many views as content units.

  Is there any other cleaner way of doing this?

Yes, you do not need to create a View for each of your nodes/pages/content. You can create a dynamic view which automatically passes the Content ID to Views.

Create "Four Images" content type set up as a single multiupload image field.
Add these "Four Images" to you node.
Create a View Block

In View, for Fields, add your image
Click on Advanced (far right), for Contextual Filter add ID .Provide default value, Content ID from URL. (Note: The view preview will go blank, which is normal, since the View edit page does not have a Content ID.)

Go to blocks (/admin/structure/block), and add the View block to a region. For Visibility settings select the content type that you want this to appear in.


Commerce 2.x attribute translations cause product duplicates in views If I add a translation for an attribute entity my views display duplicates products. I've tried to find an attributes delta filter, but  there is none. If I add a relationship for the attributes there is still no delta available in filters. Even if there was, I would need to add a relationship and filter for each attribute entity which would result in a rather massive view. I have also tried distinct views query and it does not work. How can I filter my product views on attributes language delta or another way to eliminate the duplicates?

I found a way to solve this. You must:

1) ensure you have a variations delta filter set.

2) add the field variations and ensure that the Display all values in the same row is NOT CHECKED under Multiple Field Settings. you can then hide this field if you do not want to display the output.

3) in the view display's Query settings tick the check box Distinct.

This configuration will remove product duplicates when the Product Variation relationship is used. This is the resulting query, i am not sure how efficient this configuration is but at least it works.

SELECT DISTINCT commerce_product__variations.delta AS commerce_product__variations_delta, commerce_product__variations.langcode AS commerce_product__variations_langcode, commerce_product__variations.bundle AS commerce_product__variations_bundle, commerce_product__variations.variations_target_id AS commerce_product__variations_variations_target_id, commerce_product_field_data.product_id AS product_id, commerce_product_variation_field_data_commerce_product__variations.variation_id AS commerce_product_variation_field_data_commerce_product__vari
FROM
{commerce_product_field_data} commerce_product_field_data
LEFT JOIN {commerce_product__variations} commerce_product__variations ON commerce_product_field_data.product_id = commerce_product__variations.entity_id AND (commerce_product__variations.deleted = '0' AND commerce_product__variations.langcode = commerce_product_field_data.langcode)
LEFT JOIN {commerce_product_variation_field_data} commerce_product_variation_field_data_commerce_product__variations ON commerce_product__variations.variations_target_id = commerce_product_variation_field_data_commerce_product__variations.variation_id
WHERE commerce_product__variations.delta = '0'


Why does max_allowed_packet need to be increased? Strange problem on the production server. After restarting the container assembly (which had the unintended side-effect of re-initialising the MySQL server with default settings), some memory-intensive pages (specifically the Views-enabled All Content page) wouldn't load. I couldn't import an SQL snapshot into a dev server for testing because MySQL kept on complaining about max_allowed_packet. After increasing max_allowed_packet, the import was successful and the troublesome pages loaded fine. I increased the setting on the production server and the problem went away as well. Why did max_allowed_packet need increasing unexpectedly? Is increasing it by a factor of 10 likely to avoid further problems, or will it cause more problems further down the line?

Why does max_allowed_packet need to be increased?

When your server is processing big queries, then you have to increase the value of the max_allowed_packet (or to shorten your queries if possible ?).

Big queries makes me think of Views. One way to find those queries is, to enable the "Show the SQL query" under admin/structure/views/settings edit a view and see how big its query is.

It is possible that if your content has been increased, your queries will have been increased as well (will return a large result row).

You can increase the max_allowed_packet, if needed, as MySQL says:

  It is safe to increase the value of this variable because the extra memory is allocated only when needed.


HSBC Payment method for Ubercart I am unable to develop this but was wondering if there is any modules out there or at least some guide to work on HSBC Payment method for Ubercart 3.x ?

If you are looking for generalized payment options Ubercart CCavenue can help. On their official website they provide some economy plans as well, which is good for setting up basic payment modules in place.


set #empty_option of billing address select list I'm using Drupal 7 with Commerce (7.1) Commerce Address Book 7.x-2.0

I'm simply trying to change the #empty_option value of the "Addresses on file" select boxes that appear on the checkout page from "-- Choose --" to "Add new address"  I'm using hook form alter and then:

if ($form['#id'] == 'commerce-checkout-form-checkout'){
    $form['customer_profile_shipping']['addressbook']['#empty_option'] = (t -'- Add a new billing address -');
}

But when the page loads, it still shows "--Choose --"

I'm pretty sure this should be easy !

The problem is that your t() function looks like this:

(t -'- Add a new billing address -');

And it is supposed to look like this:

t('- Add a new billing address -');