Where can I learn about how to create a custom exposed filter for Views 3 and D7?

I was lurking around the internet trying to find answer for the same question and this is what I've got in result:

Implement several hooks in your custom module. Replace modulename and filtername with your actual names.

/**
 * Implements hook_views_api().
 */
function modulename_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'modulename') . '/inc',
  );
}

/**
 * Implementation of hook_views_handlers() to register all of the basic handlers
 * views uses.
 */
function modulename_views_handlers() {
  return array(
    'info' => array(
      // path to handler files
      'path' => drupal_get_path('module', 'modulename') . '/inc',
    ),
    'handlers' => array(
      // register our custom filter, with the class/file name and parent class
      'modulename_handler_filter_filtername' => array(
        'parent' => 'views_handler_filter',
      ),
    ),
  );
}

function modulename_views_data() {
  $data = array();

  $data['node']['filtername'] = array(
    'group' => t('Custom'),
    'real field' => 'my_custom_filter_field',
    'title' => t('My custom filter'),
    'help' => t('Some more detailed description if you need it.'),
    'filter' => array(
      'handler' => 'modulename_handler_filter_filtername',
    ),
  );

  return $data;
}

Create folder named inc inside your module folder and create file named modulename_handler_filter_filtername.inc there (see code above for implicit reference to this file). Don't forget to use actual module and filter names.
Paste following code into that modulename_handler_filter_filtername.inc file. The code I used for this example creates a set of radio buttons that present years. So you can filter nodes by year created, using only years in which nodes were created.

class modulename_handler_filter_filtername extends views_handler_filter {

  /**
   * Options form subform for setting exposed filter options.
   */
  function value_form(&$form, &$form_state) {
    parent::value_form($form, $form_state);

    // get list of years from database
    $query = db_select('node', 'n');
    $query->addExpression("FROM_UNIXTIME(n.created, '%Y')", 'year');
    if (isset($this->view->filter['type'])) {
      $query->condition('n.type', $this->view->filter['type']->value, 'IN');
    }
    $result = $query->orderBy('year', 'ASC')
      ->execute()
      ->fetchAllAssoc('year');

    $years = array(
      '0' => t('All'),
    );
    foreach ($result as $k => $v) {
      $years[$k] = $k;
    }

    // create form element with options retrieved from database
    $form['value']['year'] = array(
      '#type' => 'radios',
      '#options' => $years,
      '#default_value' => end($years),
    );
  }

  /**
   * Alters Views query when filter is used.
   */
  function query() {
    // make sure base table is included in the query
    $this->ensure_my_table();

    // retrieve real filter name from view options
    // this requires 'real field' filter option to be set (see code above)
    $real_field_name = $this->real_field;
    // get the value of the submitted filter
    $value = $this->view->exposed_data[$real_field_name];

    // finally, alter Views query
    if (is_numeric($value) && $value != 0) {
      /*
        Having several custom exposed filters, make sure subsitution patterns
        (e.g. :filtername_value below) don't match across different filters.
        I spent some time figuring out why all my filters had the same value.
        It looks like the query skeleton is built first and then all replacements
        are made in bulk. Prefixing value with filter name looks good imo.
      */
      $this->query->add_where_expression($this->options['group'],
        "FROM_UNIXTIME(node.created, '%Y') = :filtername_value",
        array(':filtername_value' => $value));
    }
  }
}

That's all you need to get simplest custom exposed filter working!

Note that using FROM_UNIXTIME in condition of SELECT query may slow your database.


custom module js loaded before the module which it depends, Drupal.behaviors

Maybe you could try altering the weight of the script you add in your module?

drupal_add_js(drupal_get_path('module', 'MYMODULE') .'/myscript.js', array(
    'weight' => '999',
  )
);


How to Display a field only once in a view

In your view create two displays.

The first display (the display you'll be using in your site)
Add the title field only
Show 5 rows starting from 1

The second display (a block for the first item)
Add the title, image and excerpt from the body
Show only 1 row starting from 0

Save the view

Edit the second view
add a Global: View area, select the second display and (this is important!) add the field for this page only.


Is it possible to add CSS to the user edit page?

This depends on which theme you are using for your admin theme. If you are using a custom theme for the admin theme, you can add CSS in that custom theme. Otherwise, this is possible in a custom module via hook_css_alter().

Can you provide more information?

Are you using a contributed theme or sub-theme as the admin theme?
Which version of Drupal are you using?
Does the CSS only need to be loaded on the user edit page? What are you trying to change on the user edit page?

I highly recommend reviewing the Drupal documentation on theming: https://www.drupal.org/node/341246

Here are some similar questions:
How to Override CSS for a core module?
How to override some admin theme CSS rules?

Good example solution: http://purewebmedia.biz/article/2014/04/23/adding-your-own-css-admin-theme


After module installation, updating translations still at 0%

After a few time doing something else, I went back to the issue. In fact a lot of JavaScript was not working correctly.

Then I decided to go back to Configuration -> Performance and unchecked JavaScript aggregator and saved that configuration. See the image below :

Now everything works fine!!!

Now I can use admin toolbar's dropdown menu as well as coffee and all the other stuff is working well.

And thank you for reading me.


Why are the terms filled when they are actually empty?

Looks to be a PHP issue and not drupal. You're not clearing your $tid_1,$tid_2,$tid_3 values within your for loop

So when $data->StkGrupKodu1 isn't set for example the value of $tid_1 is still that of the last time $data->StkGrupKodu1 did exist.

You could declare your $tid_1,$tid_2,$tid_3 variables at the top of your foreach loop so they get set similar to what you're doing if the database results null


How to get View display label for field?

I recommend to take a look at this answer which provides lots of information on how to change the output produced by Views Datasource. This should give you a starter.


You don't store 3rd party passwords - nor should you get them.

The whole idea behind oAuth is that you will never get the email and password of the user that signed in with google. What you get instead is a token that is valid for a specific period of time for that user. It depends on the provider how long the token is valid, but it could be indefinitely. The smart thing about oAuth is that if you user has an active session on the site you are accessing and have granted your site access, he wont need to do anything. The browser will use his cookie for access and the site will allow you to do what you need since the user already has granted you the access.

So what you need to do is to store the token, typically something that looks like a md5 hash, the username and the site. This can be stored in the database, I would use a custom table unless you have a module that handles this for you.


Think your query needs to be:

$query = db_select('node', 'development');
$query->fields('property_type', array('field_property_type_tid'))
  ->condition('development.status', 1, '=')
  ->addJoin('LEFT', 'field_data_belongs2dev', 'property', 'development.nid = property.field_data_belongs2dev_target_id');
$query->addJoin('LEFT', 'field_data_field_property_type', 'property_type', 'property.field_data_belongs2dev_target_id = property_type.entity_id');
$query->addExpression('group_concat(property.entity_id)', 'houses_on_development');
$results = $query->execute();

Hope this should point you in the right direction.


Select on which page a view has to be display

It is easy, Edit your View and Click on Add (A popup near upper left) and choose Block

This newly created block will inherit all the settings from your existing view display.

You can Override any setting for your block display.

Choose appropriate template relevant to block following Theme: Information

Save your view and head on to block listing page to adjust your newly created block.


hook_field_formatter_view doesn't get called

In order for hook_field_formatter_view() to be called you also need to implement hook_field_formatter_info, to let the field system know about your custom formatter.

There's a good article called Creating new field formatters in Drupal 7 that has a step by step guide.


Unable to change theme that applies to view

To use a different theme for a specific page, try the ThemeKey module. It allows you to define rules for automatically selecting a theme. You can create a rule to switch theme for a particular path, which is probably the one you want. Another useful one is to select the theme based on the user's role. For example you can test theme modifications on a production site by showing one theme for anonymous users and your work-in-progress theme for the administrator role


I want to know the module through which any user can add his own tags for the content on the pages

Looks like you need to know how to use the Taxonomy module, which comes with Drupal core.

Good place to start would be its documentation.


How do I include composer.libraries.json in root composer.json without using the wikimedia/composer-merge-plugin plugin?

here is a specific way how to do it for webform module.

run composer require wikimedia/composer-merge-plugin
in composer add

  "merge-plugin": {
            "include": [
                "web/modules/contrib/webform/composer.libraries.json"
            ]
        },

run composer update --lock and verify the files

Reference https://www.drupal.org/docs/8/modules/webform/webform-frequently-asked-questions/how-to-use-composer-to-install-libraries
Reference 2 https://www.drupal.org/docs/8/modules/webform/webform-cookbook/using-the-composer-merge-plugin-to-download-libraries-with
Github issue https://github.com/wikimedia/composer-merge-plugin/issues/184


7 Ubercart - Notify Customer Shipping when Product Ships

There is a group box on each order detail page (e.g., admin/store/orders/123) which looks like the following:

Update order:
ADD AN ORDER COMMENT
[                     ]

After entering some text here (such as, "your order has been shipped"), clicking Update sends the notification to the customer via email.


How to show popup for save or view the file?

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

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

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

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

';


Purpose of the Tag field on Add View page?

To me, the tag field is handy for sites that have a lot of views.Different views have different purposes; for instance admin/editor tasks, front end pages and blocks, or as source for node reference fields. If you tag your views consistently, it's easier to find a view when you need to edit it.


A modified example from cron_example module. This doesn't concern the interval the cron tasks are set in cron.

This is important, as you will probably set another cron tasks sooner or latter with different interval requirements. Also, many system tasks require more frequent cron runs.

function cron_example_cron() {
  $interval = 30*24*60*60; // Approx a month of interval

  // We usually don't want to act every time cron runs (which could be every
  // minute) so keep a time for the next run in the site state.
  $next_execution = \Drupal::state()->get('cron_example.next_execution');
  $next_execution = !empty($next_execution) ? $next_execution : 0;
  if (REQUEST_TIME >= $next_execution) {
    // This is a silly example of a cron job.
    // It just makes it obvious that the job has run without
    // making any changes to your database.
    \Drupal::logger('cron_example')->notice('cron_example ran');
    if (\Drupal::state()->get('cron_example_show_status_message')) {
      drupal_set_message(t('cron_example executed at %time', ['%time' => date_iso8601(REQUEST_TIME)]));
      \Drupal::state()->set('cron_example_show_status_message', FALSE);
    }
    \Drupal::state()->set('cron_example.next_execution', REQUEST_TIME + $interval);
  }
}

Also, for more fine-tuned approach, you can use the Ultimate Cron module, which provides more fine-grained control for the cron jobs.


How can I rewrite the output of image field to become a div with this image as a background image?

Set all fields to "Exclude from display", add a "Global: Custom text" field and then build your html there using the "Replacement patterns" available.

I assume this still works in drupal 8.


Migrate Drupal 8 install from one server to another

I recommend using Drush as version 8.x-6.x is compatible with Drupal 8. You can then use drush archive-dump and drush archive-restore to move a .tar.gz file of your database and site files around as-needed.


How to flag an entity when it is created or updated?

You can use HOOK_entity_presave to trigger when node gets created. I updated code for you. Make sure that you change the capital letters to correct values.
function MODULENAME_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  // Check which content type would you like to flag.
  // You can use https://www.php.net/manual/en/function.in-array.php to check for
  // multiple content types
  if (in_array($entity->bundle(), ['mycontentype1', 'mycontentype2'])) {
    $flag_id = 'yourflagname';

    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);

    // Flag an entity with a specific flag.
    // https://www.drupal.org/docs/drupal-apis/entity-api/introduction-to-entity-api-in-drupal-8
    $flag_service->flag($flag, $entity);
  }
}


Allow users to access only terms that he created

There is a module that stores authoring information (author, published date and updated date) for the taxonomy term.

This module is views integrated. Exposes authoring information fields (author, published date and updated date) to views configuration (fields/filters/arguments/sorts/relation).

Taxonomy Term Authoring Information

After installing this module, create a view that filters terms and displays only terms created by the current user then change the field widget to use that view.


One module you can make use of in this situation is the honeypot module. The Honeypot method basically inserts a hidden form field to Drupal (or other). End users don't see the field, so they don't fill it out. But spam bots (usually using prewritten scripts) do see the field, and always fill it. The Honeypot module detects this and blocks the form submission if there's something in the field.

EXTRA OPTIONS YOU COULD ADD

Another Simple thing you can do according to this site is hooking into the Drupal user registration process and using a php snippet like this:

flood_register_event('reg');
if (!flood_is_allowed('reg', 4)) {
header ('HTTP/1.1 403 Forbidden');
die();
}

Using the flood_register_event() method to register a possible flood event. The method records every registration when used in this context. Next, using the flood_is_allowed() check if the current user has triggered the flood register event more than 4 or XX times. If the user has tried to access the form 4 times they get another lovely 403 and all output is killed. You could use this logic either when rendering the Drupal registration page or upon every new submission.


If you followed all the steps, I assume you have (or can get) a working copy of original 6.x page.

The question is - are your nodes OK?

If they work properly, it means you have data in good enough state. Delete views that include problematic fields and recreate them from the ground. Optionally export them, remove fields that cause problems from exported file, delete from server, import and add fields. That's the easy case
Sadly, if there was changes in the fields you were using in the very nodes, that renders nodes unusable, it will be worse. You will need to export data from 6.x site to some more or less universal format, like csv or xml, and import it anew to 7.x

Delete migrated data and it's content type
Create new content type with new-style fields, that maps 1:1 to old node structure. If possible, keep names
Export node data, using Node Export, Views data export or similar tool
Secure all the files referenced by nodes
If needed, manually upload secured files to new version; see next step
Import nodes using tool like Node Export or Feeds - it may be required for files to be already uploaded, read the manual of your importing tool


Where to change default translation language for drupal 7 while using entity translation module?

You have to first delete your translations then you will be able the select another language under the dropdown box for the original content.


Theming custom field directly in custom module folder?

When you define your module's theme info in theme_hook(), you can use drupal_get_path() to find the path to your module, and the path array key in your theme implementation array to point to the directory your tpl is in.

A working example would be:

function field_collection_theme($existing, $type, $theme, $path) {

  $path = drupal_get_path('module', 'field_collection');

  return array(
    'field_collection_op_links' => array(
      'path' => $path . '/includes/theme',
      'template' => 'field-collection-op-links',
      'render element' => 'op_links',
    ),
  );
}

Where the field_collection_op_links.tpl.php is in field_collection/includes/theme/, no matter where field collection is installed.


Why are anonymous visitors logged in when they visit /user/[uid] page?

This is no security hole, it's the custom code you shared.

// When you load the global user object ...
global $user;
// ... and then assign another user object to the global $user object ...
$user = user_load(<any_uid>);
// ... Drupal basically changes the context of the current user.
// It's kind of a hacky login by code.
// Hacky because, till this code executes
// there's no log about the user login, until drupal writes the current session into the database.

Typically $account is advised to prevent accidents like this.

$account = user_load(<any_uid>);


Drupal for Bloggers: How can I achive getting such a little FB, Twitter, etc. Box on the left of my homepage?

You want to try something like the ShareBar in Drupal 7.

  The Drupal Sharebar module lets you easily add a "floating" social
  media submission bar on your website (like that found on Mashable)
  that includes share buttons for the most popular social media websites
  online such as Facebook, Twitter, and Google +1 Buttons.


In your new machine you probably installed Apache and did not enable a2enmod rewrite

To enable it, copy and paste the following line to your command line:

sudo a2enmod rewrite && sudo service apache2 restart

Another way to enable it (in case you're on Windows), you could edit /apache/conf/httpd.conf and uncomment (remove the #) from #LoadModule rewrite_module modules/mod_rewrite.so line and restart Apache.


Why only first of two jquery files loaded is running?

They both have the same name, both "basic". Rename one of the 2 and you should be fine.
Change

Drupal.behaviors.basic = {

To for example

Drupal.behaviors.modifications = {

The name should be something descriptive about what the underlying functions do.


You can use the Content Access module to achieve this.

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


How to set custom user view mode for comments

The variables {{ author_picture }} and {{ author_name }} are prepared in preprocess in the hook template_preprocess_node(). You can modify these variables or add your own in a custom preprocess hook.

Or you can make the field uid configurable in UI by modifying the field definition in the node entity:

mymodule.module

function mymodule_entity_base_field_info_alter(&$fields, $entity_type) {
  if ($entity_type->id() == 'node') {
    if (isset($fields['uid'])) {
      $fields['uid']->setDisplayConfigurable('view', TRUE);
    }
  }
}

and you'll find the Authored by field in the Manage Display page, where you can configure how the referenced user entity is formatted (which view mode is used).

A third and IMHO perferable option is to use the module Display Suite.


hook_theme() in a custom file of my module

Just to clarify, you mean the actual hook_theme() implementation, correct? Not a theme hook you are defining in hook_theme(). If so, by default, all hooks must be in the .module file. Hooks are meant to be callable at any time, and only .module files are loaded by default on every page load. However you can tell Drupal that a hook is in a different file by implementing hook_hook_info():

function hook_hook_info()
{
   $hooks['theme'] = ['group' => 'theme'];

   return $hooks;
}

With this code, Drupal will look for the hook (the array key 'theme') in the file MODULENAME.GROUPNAME.inc. In this case your GROUPNAME is defined as 'theme' in hook_hook_info(), so Drupal will load MODULENAME.theme.inc, whenever hook_theme() is invoked.

Now, if you meant that you want to put a theme hook that you define inside hook_theme() in another file, then you need to declare the file for that theme hook:

function hook_theme()
{
  return array
  (
    'some_theme_key' => array
    (
      'variables' => array(),
      'file' => 'path/to/file.inc', // relative to module root
    ),
  );
}

In this case, when the system tries to load the theme some_theme_key, it will load the file [MODULEFOLDER]/path/to/file.inc.


Credit for most of this answer to this article: http://forumone.com/insights/styling-inline-images-with-drupals-wysiwyg-and-media-modules/
First I went and edited the relevant displays and added a caption field (which is what I was trying to do)

Then used hook_media_wysiwyg_token_to_markup_alter() to change the output, in my case I needed to catch the situation where the image got floated in the WYSIWYG, and float the parent element rather.

<?php
function MODULENAME_media_wysiwyg_token_to_markup_alter(&$element, $tag_info, $settings) {
    if (($element['content']['#bundle'] == 'image')) {
        // check if a caption has been set
        if(!empty($element['content']['field_caption'])){
            if(isset($element['content']['file']['#attributes']['style']) && strstr($element['content']['file']['#attributes']['style'], 'float')){
                // move floats to the wrapping element
                $element['content']['#attributes']['style'] = $element['content']['file']['#attributes']['style'];
                // remove inline style on image
                $element['content']['file']['#item']['attributes']['style'] = '';
                // add class to wrapping element so we can style it
                $element['content']['#attributes']['class'][] = 'media-with-caption';
            }
        }
    }
}


What happens when an email from webform fails to deliver?

It throws an error and drop it on floor like below:

Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in DefaultMailSystem->mail() (line 76 of \modules\system\system.mail.inc).
Unable to send e-mail. Contact the site administrator if the problem persists.
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in DefaultMailSystem->mail() (line 76 of \modules\system\system.mail.inc).
Unable to send e-mail. Contact the site administrator if the problem persists.


Drupal 7 CDN Module not altering URLs for themed Pages

The problem is that you are not using the Drupal API.

The CDN module needs to be able to alter the path from your Drupal site to your CDN.  It does this by catching the URL via hook_file_url_alter(), and changing it.

The proper way to to make a URL in this case is with file_create_url().  Something like this should work

function MYTHEME_preprocess_page(&$variables) {
  $path = drupal_get_path('theme', 'MYTHEME');
  $variables['mysrc'] = file_create_url($path . '/images/v1/image1.jpg');
}

And then in your theme you would use

<img src="<?php print $mysrc; ?>" width="380" height="197" />

However, as Mołot suggests, using a proper theme function to make a renderable image would probably be best.


Custom line items to be included in $order->getTotal()

I was able to achieve this by adding type as 'generic' for all my custom line items.
Sample code:

uc_order_line_item_add($order->id(), 'generic', 'Promotion', -100, 6, NULL);


Add .active class when certain view is executed using hook_menu

You can use the Context module for this. Context is capable of adding active classes to menu items based on conditions, e.g. path, content type, etc.


How/where to change the default size of inline images?

I would use the Image Resize Filter or Image Autosize Filter modules. These module add a filter to your input format that automatically resizes images added through the WYSIWYG editor. Image Autosize Filter allows you to set a maximum width, which seems like it would work for your case.

As a precautionary measure, you could add some CSS like this as well:

.node img {
    max-width: 450px !important;
    height: auto !important;
    border:0px;
    margin:0em;
}


How to override node clone to its parents node?

It looks that you are trying to implement elaborated workflow using node cloning approach.

I strongly suggest you to use Workflow module instead:

  This module allows you to create arbitrary Workflows, and assign them to Entities.

  Workflows are made up of workflow states. Transitions between states can be allowed per role. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state.
  You can set up the Workflow to alter states from form, page, comment and a special workflow tab.

  Transitions between workflow states can have actions assigned to them. In our example, we could assign an action so that when the story moves from the Draft state to the Review state an email is sent out. Another action could be assigned to the transition from Review to Published so that the node's status is set to Published (and becomes visible on your website).

It is there, it works, and it seems to cover all your needs in one, integrated solution. Even it's example use case is almost exactly like your use case here.

If you want to configure it at revision level more easily, there is also Revisioning, "a module for the configuration of workflows to create, moderate and publish content revisions".

  You use it in scenario's like this:

  Authors write content that prior to being made publicly visible must be reviewed (and possibly edited) by moderators. Once the moderators have published the content, authors should be prevented from modifying it while “live”, but they should be able to submit new revisions to their moderators.
  We shouldn't have to grant these roles “god-like” powers (e.g. D6's "administer nodes" permission) to implement this.


How to rearrange the sort buttons in a view

Sure there is a twig for the exposed sort form. But normally you rearrange form elements inside of a form by adjusting the weight property. If you want to move the button outside of the form in another place of the view you need some tricks, look here https://stackoverflow.com/questions/7020659/submit-form-using-a-button-outside-the-form-tag/23456905

If you want to rearrange the view in general, like moving the complete exposed section to another place, you can do this in views-view.html.twig:

{{ title_prefix }}
  {{ title }}
  {{ title_suffix }}

  {% if header %}
    <header>
      {{ header }}
    </header>
  {% endif %}

  {{ exposed }}
  {{ attachment_before }}

  {{ rows }}
  {{ empty }}
  {{ pager }}

  {{ attachment_after }}
  {{ more }}

  {% if footer %}
    <footer>
      {{ footer }}
    </footer>
  {% endif %}

  {{ feed_icons }}


Yes, that is the system table, which stores details about available modules, themes and theme engines.

For more information about the system table schema, refer to the technical documentation at:

system_schema

from:

 $schema['system'] = array(
    'description' => "A list of all modules, themes, and theme engines that are or have been installed in Drupal's file system.",

and also, it's usage by:

system_list

  Builds a list of bootstrap modules and enabled modules and themes.


Redirect to main view URL when no contextual filters are set

The problem lies in Drupal's menu system, which for the most part asserts itself as a safety mechanism, so if you or someone else mis-spells a URL it will give you the next best option.

Admin Menu Example

admin/structure/blocks = Manage Blocks Page

admin/structure/blockss = Structure Page

Drupal does this so it won't "disrupt" the user-experience, but it can also be a confusing if you don't know what just happened.

It's generally there to prevent human error and other problems that arise when managing a live website.

The Options

Keep the default set, so users are accommodated and instead focus on structuring the robots.txt (and perhaps .htaccess) file correctly, so you can let Search Engines know what's happening.
Look into the Rules and Context contributed modules to see if you can create a solution using those interfaces. You may or may not be able to find a solution there, but it might be a good start.
Create a module, which will handle non-existent URL's and correctly reroute them to 404 page.


Generating Ubercart orders programmatically

I was able to resolve this by adding these to my file:

//for order
use Drupal\Core\Form\FormBase;
use Drupal\uc_order\Entity\Order;
use Drupal\user\Entity\User;
//for products
use Drupal\uc_order\EditableOrderPanePluginBase;
use Drupal\uc_order\Entity\OrderProduct;
use Drupal\uc_order\OrderInterface;


For an email action, there are 2 different input modes for the fields in Send HTML email action.

Direct input mode: You're supplying most of the data (e.g. the HTML body) with different token (e.g. [site:slogan]) inserted in it.
Data selector mode: You're using a widget (see image) that lets you drill into data that the Rules action has available. This is useful for finding contextual data (e.g. retrieving the current user's email when a node is updated).


Clone the code
Import database
Configure your settings.php file
Get public files; copy them to sites/default/files
Compile CSS and JavaScript in the theme, if it is required
Clear the cache

Those step should works.

If Backup and Migrate module installed in Pantheon.io
you can get the database and public files from https://pantheon.io/admin/config/system/backup_migrate.


Is it possible to insert a value in field using Rules?

Before you will be able to create a Rules Action like "Set a data value" for your field, you have to make sure to add a Rules condition Entity has field (related to the field for which you want to set a value). And make sure to add that Entity has field condition BEFORE other Rules Conditions in which you might want to refer to this field (if you have any such conditions in your rule).

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

And to validate if your rule is working, just add a "Set a message" (within System) as your very first Rules Action, to display the actual value (using an appropriate token for your field), after your executed your rule (and re-execute it). If that doesn't work (or help), use Rules debugging, as detailed in "How to debug a rule that doesn't want to fire?".


hook_entity_field_access - trying to check if there's a value

In the documentation for EntityAccessControlHandler::fieldAccess(), the method that invokes the hook you are implementing, $items is defined as follows.

  \Drupal\Core\Field\FieldItemListInterface $items: (optional) The field values for which to check access, or NULL if access is checked for the field definition, without any specific value available. Defaults to NULL.

This could also happen if the entity containing the field is being created, and not modified. That is the reason why Drupal core implementations of that hook always check the value of $items before using it.

  // language_entity_field_access()
  // Only allow edit access on a langcode field if the entity it is attached to
  // is configured to have an alterable language. Also without items we can not
  // decide whether or not to allow access.
  if ($items && $operation == 'edit') {
    // Omissis.
  }

  // views_entity_test_entity_field_access()
  if ($field_definition->getName() == 'test_text_access') {
    if ($items) {
      if ($items->value == 'no access value') {
        return AccessResult::forbidden()->addCacheableDependency($items->getEntity());
      }
    }
  }


Is there a way to switch the Search form (used in the block) to do a Facet Search instead?

As stated below I originally understood your question.  Here is how you change the default search page to the one with faceted navigation:
In admin/config/search/settings you can turn off default node search and make faceted your default as shown in the below screen shot.

The Search API module allows you to choose other search methods, including using something like SOLR server for search, which also does faceted queries.


You might need MultiStep form using ajax enabled. Just implement #ajax on the buttons of form as in the given link.

    $form['buttons'] = array(
      '#type' => 'container',
    );
    if($form_state['step'] !== 1) {
      $form['buttons']['back'] = array(
        '#type' => 'submit',
        '#value' => t('Back'),
        '#limit_validation_errors' => array(),
        '#submit' => array('ajax_form_multistep_form_back_submit'),
        '#ajax' => array(
          // We pass in the wrapper we created at the start of the form
          'wrapper' => 'ajax_form_multistep_form',
          // We pass a callback function we will use later to render the form for the user
          'callback' => 'ajax_form_multistep_form_ajax_callback',
        ),
      );
    }
    if($form_state['step'] !== 3) {
      $form['buttons']['forward'] = array(
        '#type' => 'submit',
        '#value' => t('Next'),
        '#ajax' => array(
          'wrapper' => 'ajax_form_multistep_form',
          'callback' => 'ajax_form_multistep_form_ajax_callback',
        ),
      );
    }
    else {
      $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#ajax' => array(
          'wrapper' => 'ajax_form_multistep_form',
          'callback' => 'ajax_form_multistep_form_ajax_callback',
        ),
      );
    }


How to give user opportunity to select attribute by checkbox

Better Exposed Filters seems to be module you need:

  The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively. Description fields and Select All/None links can be added to exposed filters to make for a better user experience.


How can I remove "Show row weights" as well as the weight column in D7?

If you do not want to display those elements because it confuses users, you could simply hide them with CSS. Use Firebug or something alike to determine the correct classes in order to adapt the code underneath.

#YOUR-FORM-ID .tabledrag-toggle-weight-wrapper,
#YOUR-FORM-ID .field-multiple-drag {
  display: none;
}


Tiered HTML lists using Views and Taxonomy?

I'm going to assume your view is a taxonomy term view.

First thing you would want to do is add a relationship to your view. The relationship you want to add is the Taxonomy: Parent term relationship and set required this relationship.

Once you're done adding the relationship add another Taxonomy: Term field to your view but this time make sure to select the "Parent" relationship for that field.

Also select "Exclude from display" for this field if not this is going to show up twice.

Once you've done that you will need to group your fields by the Parent Term. This can be accomplish by going to the settings option for the format and selecting the Parent term you just added.

You will now get the display you want.

Hope this helps.


Programmatically add a taxonomy term as entity reference in a custom entity

Well thank you, the answer of 4k4 was very useful.
My problem was that for my field I wanted to reference to a taxonomy term, I had already created it and dropped it directly in the database.
It's seems no to be the right way to do this, so I was having such trouble recreating it.
So unisntalled my module (after removing all the data) , and reinstalled it , and then this piece of code worked perfectly to have a reference to a taxonomy term:

$fields['speciality'] = BaseFieldDefinition::create('entity_reference')
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default:taxonomy_term')
  ->setSetting('handler_settings',
      array(
    'target_bundles' => array(
     'specialite' => 'specialite'
    )))
  ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => 3,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '10',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

PS: specialite is my the name of my vocabulary


I found a solution to add the value to field_stock (Stock level).

$variation =  ProductVariation::create(['type' => 'default', 'sku' => $json['22107'], 'status' => TRUE, 'price' => $price]);
$variation->save();
//Stock
$stock = ['stock' => ['value' => 100]];
$var = \Drupal::entityManager()->getStorage('commerce_product_variation')->load($variation->id());
$var->set('field_stock', [$stock]);
$var->save();

My field_stock in database is empty but this code create a commerce_stock_transaction in database with my quantity.


Drupal 8 uses render arrays for the structure, and drupal_render() to render them (as can Drupal 7 for themeing, incidentally).

The examples from the change record are as good as any:

Drupal 7

// Theme a table with header and row data.
$markup = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));

// Render a pager.
$markup = theme('pager');

Drupal 8

// Theme is available as an element type (may have additional processing in rendering).
$table = array(
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#attributes' => array(
    'id' => 'my-module-table',
  ),
);
$markup = drupal_render($table);

// Pager is not an element type, use #theme directly.
$pager = array('#theme' => 'pager');
$markup .= drupal_render($pager);

There's a useful warning too:

  Also note that when preparing output for Twig templates (in preprocess functions) it is preferable to avoid calling drupal_render() whenever possible. The Twig environment in Drupal 8 will automatically render any render arrays printed in the template, allowing for manipulation by later preprocess functions and preventing unnecessary rendering if the variable is never printed in the template.


The only thing you should need to do is clear Drupal's cache; hook implementations are cached so once you've written the function you need to clear the cache to get the new data into the registry.

One other small thing, you probably shouldn't be returning an array like you currently are from your form builder function.

I'm pretty sure Drupal sets up the $form variable it passes into the function through drupal_get_form with some required details, so returning an array (and not the original $form element) will probably mean your return from the function is missing something. The usual way would be to do it like this:

function mymodule_form_one($form, &$form_state) {
  $form['#theme'] = 'mymodule_theme_one';

  return $form;
}


How to import nodes and their translations from a csv using Feeds?

While Feeds:entity translation should be awesome when finished you can try this Solution

  I created two feed imports.
      I forced the language field for each one.
      Two separated nodes were created for each content (one in each language) but it didn't links the translations.
      So I used a SQL query to finish the job, it's based on the feeds uuid :

I think he meant: based on guid not uuid


Add animation/fade to modal/dialogue box (without using the bootstrap)

What do you need the modal to do? I often use animated modals for my Drupal projects - http://joaopereirawd.github.io/animatedModal.js/

It seems to work pretty well for menus and forms in my experience.

It uses animate.css ( https://daneden.github.io/animate.css/ ) which you can use also to create some nice transitional effects.


To change the title of the block provided by the Facet API, go to admin/structure/block and choose the block of which you want to chage the title. Click on the Configure link and then change the title of block from Block Title textfield.


How can I assign an icon to users depending on their gender?

Create a vocab as gender and add two taxonomies to it as male and female. To the gender vocab add image field and while creating the male and female taxonomy term add the respective images.

Now add the term reference file to user entity and keep it as stele list.

In your custom module hook_user_presave and get the value for the taxonomy field.when you know the selected taxonomy you can load the taxonomy to get the image field fid associated with it assign the fid to $user->picture.

Now everywhere image will load as per the gender selected.


page.tpl.php base on a field criteria in views

Salam,
You can do this using hook_preprocess_views_view(&$vars). Your code should be like this:

function YOURTHEME_OR_MODULE_preprocess_views_view(&$vars) {
    $view = $vars['view'];
    // the values of the view, filter criteria and the value of fields are in $view
    if(CONDITION1 == true)
        $vars['theme_suggestion'] = 'views_view__custom_pages1'
    else if(CONDITION2 == true)
        $vars['theme_suggestion'] = 'views_view__custom_pages2'
}

Then create files views_view__custom_pages1.tpl.php and views_view__custom_pages2.tpl.php and theme the view. In this way different themes are defined for the same view.

You also said I need to know how to access field's value in my "function MYTHEME_preprocess_page(&$vars, $hook) ", what variables do you need to find it's value?


Where In or clause for when a variable might not exist

What you need to do is take that logic out of the SQL query, and instead use the query builder so to create your query; then you can add the IN statement conditionally, e.g.

// Set up your query
$query = db_select('actions')->fields('actions');

// See if you have data
if (!empty($types)) {
  // IN is the default operator for arrays so there's no need to specify,
  // but for the sake of an example...
  $query->condition('type', $types, 'IN');
}

// Get the results
$results = $query->execute()->fetchAll();


Change Bootstrap column classes based on the result of a view

One way to solve your problem is to implement an hook_preprocess() in your custom themes' .theme file, where you check whether your second block is empty or not and use this information to apply the appropriate (Bootstrap grid) class (to your block in the first column).

Although above suggestion is not using a custom module (it's in your sub-theme), however, I can imagine that this might not be the answer you're looking for.

As you suggest you can also put this logic in your Twig template, but checking whether your block is empty can be a bit troublesome (due to the fact that blocks can be lazy loaded using placeholders, see e.g. Drupal 8 regions with and empty blocks).


I'm struggling to understand what that code is trying to do; I'm assuming your end goal is to render either this:

Or this, if the condition passes:

But I don't see how the code sample would ever to get to even the result in your question. There's no mention of a
, and if $block contains the opening
 'html_tag',
  '#tag' => 'div',
  '#attributes' => ['class' => ['gcse-searchresults-only']],
  '#value' => '',
];

if (array_key_exists('search_broadness', $get_results) && $get_results['search_broadness'] == 'narrow') {
  $form['search']['results']['#attributes']['data-as_sitesearch'] = $gcse_narrow_search_query;
}


How to add variable using mytheme_preprocess_field and print using twig template?

Variables in a template are scoped - what you add in hook_preprocess_field will only be available in field.html.twig and its derivatives, not node.html.twig etc.

You can implement the same logic in the node preprocess:

function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->hasField('field_header') && $variables['node']->field_header->isEmpty()) {
    $variables['myVariable'] = TRUE;
  }
}


EntityMetadataWrapperException when accessing empty entity body. How can I test if body is empty first?

Just simply see the value is empty

if($node_wrapper->body->value() != ""){
 //Evaluates true
}

or use a try catch

try{
 echo $entity->body->value->value();
}catch(Exception $e){
  echo "Value does not exist continue";
}


How can we assign points to users in the site?

There is a module for that, userpoints

Also using Rules to assign them for certain actions is common with that module.


Setting up subdomains, confused on "Settings.php" / "web.config" setup

Instructions for multisite installations are in sites/default/settings.php. To quote from that file:

  For example, for a fictitious site installed at http://www.drupal.org/mysite/test/, the 'settings.php' is searched in the following directories:

  sites/www.drupal.org.mysite.test
  sites/drupal.org.mysite.test
  sites/org.mysite.test
  sites/www.drupal.org.mysite
  sites/drupal.org.mysite
  sites/org.mysite
  sites/www.drupal.org
  sites/drupal.org
  sites/org
  sites/default

  If you are installing on a non-standard port number, prefix the hostname with that number. For example, http://www.drupal.org:8080/mysite/test/ could be loaded from sites/8080.www.drupal.org.mysite.test/.

The lookup can be changed as described in sites/example.sites.php:

  This file allows you to define a set of aliases that map hostnames and pathnames to configuration directories. These aliases are loaded prior to scanning for directories, and they are exempt from the normal discovery rules. The aliases are defined in an associative array named $sites, which should look similar to the following:

$sites = array(
  'devexample.com' => 'example.com',
  'localhost.example' => 'example.com',
);

  The above array will cause Drupal to look for a directory named "example.com" in the sites directory whenever a request comes from "example.com", "devexample.com", or "localhost/example".

BTW: multisite installations are usually done to facilitate using different databases.


Ajust the position of autocomplete fields

This should be a CSS positioning issue, whether it is caused by padding, margining, position, top, left, right, or bottom.

You should be able to use firebug or another developer tool like it to find what CSS is causing this and remove that CSS if it's your own CSS. Otherwise if the CSS is provided by contrib then you can use a more specific CSS selector and override the values.


Migrate theme settings between multisite installations

So far what I've been able to figure out, the answer is -- it depends. It depends on what you're moving between installations.

Features module has worked best for me to move configuration settings or for modules (and their dependents). Sometimes, you'll have to include the strong arm values inside the Feature export.

For user content, it's best to use Migrate (or Backup and Migrate).


Added return ''; to the argument code if the if statement was false. Somehow that did the trick.


You can go directly in your View's settings, in "Page settings" bloc, configure the path manually. Just remove the game part of the path.

For your information:

I suggest you to take a look at Pathauto module that allows you to define URL patterns very precisely for all the default pages of your site (but not views apparently): https://www.drupal.org/project/pathauto

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.

Maybe it will be helpful for other cases.


Drush update: How to keep file permissions?

Write a script that correct permissions, you can find an example in this article:

Securing file permissions and ownership

Execute this script manually every time a drush update is made.

Or you can write a simple drush command that executes this script when a drush commands that cnahges files executes. Check the drush_hook_post_COMMAND:
http://drupalcontrib.org/api/drupal/contributions%21drush%21docs%21drush.api.php/function/drush_hook_post_COMMAND/7


Anything in content is a render array, you can't use functions like that on those directory.

You can loop over it and print out each item, that works as it is then automatically rendered.


How to add the input text field in node view page

You can use editablefields module.

  This module allows CCK fields to be edited on a node's display (e.g.
  at node/123), not just on the node edit pages (e.g. node/123/edit). It
  also works within views etc. Anywhere a 'formatter' can be selected,
  you can select editable (or click to edit).

You can  follow the below step for setting up editablefields for your content type.

Go to  Administration -> Structure -> Content type
Edit your content type and then click on "Manage Display"
Change the Format to editablefields for your field.
Once you set the formatter, you can click on the gear icon to further
change the settings - the settings vary per field type


How to make a MENU_LOCAL_TASK on a user's profile only appear on their profile?

Instead of user_access, define your own access callback function and then pass the user object to that.

So 'access callback' => 'yourmodule_analytics_access' and 'access arguments' => array(1).

In that function, compare the user id and check the permission.

function yourmodule_analytics_access($account) {
  global $user;
  return $user->uid == $account->uid && user_access('access ClientCompanyName services');
}


How to I tell a Views Block to only pull Snippets belonging to the same OG as the container page?

As fullerja said, you can use a Contextual Filter but you may also need to define a Relationship first so that the view pulls in the OG that goes with the snippets.

If this page is showing OG content, hopefully it has the OG's slug in the URL. If that's the case then you can use that path for the Contextual filter.

These answers might be helpful for the specific configuration:

Organic Groups Views Contextual Filters
How do I display all the nodes in an organic group?


Subtract one field from another (Quiz, Getting difference between revisions)

I could not find a module which does the same, but you can achieve this by custom codes.Not the exact codes but still covers the major things

  // get all revisions for a node
  // this function returns array of revision in order of revisions are created,with the latest revision at the top and last revision as the next array element
  $get_revisions = array_values(node_revision_list(node_load($node_id))));
  if(count($get_revisions) > 1) {
    $current_node_version = $get_revisions[0]->vid;
    $last_node_version = $get_revisions[1]->vid;
  } else {
    // No differnece,since there is only one version.
  }

  //Now load the nodes with the versions
  $current_node = node_load($node_id,$latest_node_version);
  $last_node = node_load($node_id,$last_node_version);

  // Once you have loaded nodes you can easily do the custom calculations,something like
  $field_1_diff = $current_node->field_1_diff... - $last_node->field_1_diff...


How do I add role permissions to custom module

Create a file my_module.permissions.yml and add

my permission:
  title: 'This is my custom permission'
  description: 'A custom permission for your.'

Then use your permission in your my_module.routing.yml:

example.name:
  path: '/example/{name}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'my permission'

Now you can configure your custom permission on admin/people/permissions


How to edit Media module`s display profiles?

They are to be edited on file-types page in Structure:
admin/structure/file-types


Different row tpl for every row in a view?

Out of the box with views? No. The row templates apply to all the rows in a given view.

You could do something like this with a custom module though...

You can use hook_views_pre_render to step through your view, like so:

function mymod_views_pre_render(&$view){
    if($view->name == "yourviewname"){
      $count = 0;
      foreach($view->result as &$row){
          $row->template = dostuffhere($row, $count);
          $count ++;
      }
    }
}

In this example, you would step through each of the result rows and and create printable content. The dostuffhere() function would be a routing function that would load in the appropriate template files, which you could define using hook_theme (example on how to call with a template file is in the comments). The custom .tpl.php files from hook_theme could be called like with the theme() function.

The routing function would then look something like this:

function dostuffhere($data, $row){
switch ($row) {
    case 0:
        return theme('mymodule_template1', array('$row'=>data));
        break;
    case 1:
        return theme('mymodule_template2', array('$row'=>data));
        break;
    //etc...
}

Because, in this example, we're using reference variables in hook_views_pre_render, the "template" variable will become available in the row output for the view. So all you really need to do in your row view is to just print out the $template var.


There is no support for wait lists at this time, however the API has a tagging system not exposed via UI, which is designed to support a list systems.

I encourage you to take a look at RNG Ecosystem, and give some feedback on your requirements for wait lists.


Migration from one domain to other domain

More than likely, you have a redirect base directive in your .htaccess. This is used when serving your Drupal site out of a subfolder of your webhosting provider's webroot. You should check your .htaccess file for the directive RewriteBase /abc and replace with RewriteBase /xyz
If that still doesn't work, check the vhost entry of your webserver for the same directive.
Otherwise, if the site still redirects to "/abc", then you may have a $base_url defined in settings.php causing the redirect.


Drupal 6 Content Types fields not saving

One final possible oops:  goto admin/content/node-type/TYPE/display and make sure the fields are being displayed in that content type.

If all looks well there, then from the comment discussion, this is sounding like your database might have become corrupted, lost some tables, or generally needs to be restored from a backup taken before all of this started to happen.  If you go into phpmyadmin (assuming you are using mysql) you can check on the following to confirm:

Basically, CCK uses database tables to define the content types it creates, so, you can look for a table called content_type_MYCONTENTTYPE, eg, MYCONTENTTYPE would equal story, page, album, product, etc.

So, if you find that table, it will have as fields/columns the field values of the fields of the content type: nid, vid, and then any custom fields UNIQUE to it in CCK.  By UNIQUE I mean that no other content type uses that field.  If, though, let's say you have a field_overview that you use in other content types also, well, that won't be listed here.

Where?  Once you start sharing a field between content types, it gets its own table, called  content_field_FIELDNAME and in there you will find your content values.

So, in your description above, let's assume the content type is product and that you don't share those fields with any other content type.  In your database, there should be a table called content_type_product and in it you should find fields/columns:

vid
nid
field_field_subtitle_value
field_overview_value
field_features_value
field_n_specifications_value

You should also see fields for FIELDNAME_format that tell drupal the text format.

If you DO share any of these fields, let's say you share the field_overview, look for a table called content_field_overview and in it, you'll find columns/fields for value and format.

So, in a nutshell, that's how CCK works with respect to saving fields and so forth.  If any of the above isn't there, you have to create it or put it back (and of course, try to figure out how/why it got deleted/corrupted in the first place).

If, though, all of the above is there, and there are values in there for your fields, then something else is going on.

Do the values show up when you edit the node, eg, look at a piece of content with those fields, and if you edit it, do those fields have values, or are they blank?  If they have values when you are editing it, then something is causing them to not display.

Did you change or add a text filter that is stripping all your content out?

Did you change your node.tpl.php file and now not printing/displaying these fields for some reason?

Or did you change the display parameters mentioned above at the beginning and they are being hidden or excluded from display?

Anyways, lots to track down but let me know what happened and maybe something else will spring to mind to help track it down to a conclusion.


Drupal 8, Commerce 2 custom products, variations and order items

When setting the unit price, you must set the override parameter to true as so:

$unit_price = new \Drupal\commerce_price\Price('9.99', 'USD');
$order_item->setUnitPrice($unit_price, TRUE);
$order_item->save();


your question is not clear.I don't understand what you want.
But I think it can help you.
Node relationship


Allow users to register using username in drupal commons throw Integrity constraint violation error

I removed the default value

Sort of but not really - what you've actually done is set a static value of NULL for that field, which will be carried through to the submission regardless of any user input.

Your best bet to avoid these sort of problems would be to implement the field again from scratch:

$form['account']['name'] = array(
  '#type' => 'textfield',
  '#title' => t('Username'),
  // ...
);

Note that this won't remove any extra validation that Commons might add, so YMMV and there may be some additional steps to complete your feature.

Just for future reference, to set an initial value for an element that doesn't nuke user input, use #default_value in place of #value.


I suspect that you have some very large menus in your site.  Rebuilding menus is a an expensive operation, and menu trees can vary page-to-page, user-to-user, etc.  As a result, that data gets cached in {cache_menu}.

My suggestion is to query in your favorite SQL tool, and print_r() the data column for the large entries to see if anything looks out of the ordinary.  In general, the data will be your menu tree with everything from the various hook_menu() entries added in.  Modules that add extra data onto menu entries (like Menu Attributes) will have there data here, too.

You need to profile to see where the problem is actually happening.

It could be the result of a less-than-ideally configured MySQL instance.  If you do have 1M cache entries, then you may want to bump up the query cache result set limit (I think this defaults to 128K).

You may also want to investigate using memcache or redis as your cache backend.

However, if you really do have huge menus, then the slowdown could be from unserializing all of that data.  If this is the case, then you need to figure out a strategy to cache the menu output when your pages are being built up.  Enabling block level caching may help, or you may need to make your own menu blocks, and cache that output yourself.  Panels caching may be worth investigating.

It may sound odd, but you may also want try to disabling caching for {cache_menu}.  The easiest way to do this is to install one of the dummy cache modules, and configure it to just use that cache backend for {cache_menu}.


Safely enter PHP code in block to prevent site crash?

The usual way to avoid problems with your production site is to try out everything first on a dev or staging site, and then push it to production after it is tested.  There are two main problems with php in blocks: one is that block data is stored in the database.  If you push the database from dev to production, you will lose new content on your live site -- no good.  The solution to this problem is to use the features module to export your database configuration to your code files, which allows you to push your config-in-code from dev to live & then re-import on the live site.

The other problem with putting php in blocks, though, is that it opens up a security hole in your site, as anyone who has the right to configure blocks can now run code on your server.  This means that your site is one guessed password away from compromise at all times.  It is therefore better to write your blocks in code using a custom Drupal module rather than put php in the database.

If you do have a site with malformed code in a block, you can disable the block using the drush block-disable command from the drush_extras project.


how to add multiple style values in attribute in drupal form

You can nest the style attributes as follows :

$form['precio'] = array(
  '#type' => 'textfield',
  '#title' => t('Price'),
  '#default_value' => $precio,
  '#size' => 20,
  '#attributes' => array(
    'style'=>'background: none repeat scroll 0 0 #EAEAEA;
              margin: 0 3 4;
              color:red;'
  ),
  '#description' => t('Change the price'),
);


How to delete a node with same specific field content and by same user when a more recent one is created in drupal 7?

Here is how I achieved it in the end:

First, create a component rule 'Listreviews'. This component rule will filter nodes created by the current user and then

Component plug-in is set to 'rule'.
The variable is of type 'node' of type 'parameter'. Give it a machine name 'nodefromlist' and save.
Add a condition: data comparison. This comparison will be have the data selector nodefromlist:author:uid, and it needs to equal site:current-user:uid.
Add an action: 'delete entity', which will have the data selector value of 'nodefromlist'.
Save!

Then, create a rule 'Delete duplicate review'.

the event chosen is 'before saving content type review'
no conditions
Actions: 'fetch entity by property'

entity type 'node'
property: the field 'location' (in my example)
data selector: go down the arborescence up to: node:field-location
I put a limit of 10, but may need to be adjusted based on previous content available.
Add a label to the provided variables section
Add a variable name like: item_same_location

Then

Create a loop below the action above with the parameter item_same_location

call the current list item: list_item.

In that loop, create an action 'component' with the name of the rule component created above.

the data selector will be: list_item.

Save your rule!

This should now work. As a bonus, I added a 'display message' action in the component rule in order to let the user know that their previous review was deleted. I hope this helps someone in the future!


Where is $form_state stored between form build, and form submit functions?

The cache_form table stores $form_state, so except for the values passed on by the client, which should be validated anyway, it is safe to trust the content in $form_state.


Late but might be useful for someone, you can use views_summarize module.
Note: If you want to take export of your views using views_data_export module than views_summarize will create issues.


How to Move the Nodes Displaying in the Front Page to Another Page? (e.g. domain.com/articles)

You need to use the Views module to create a list of recent articles. In fact views come with a predefined view that emulates the core Drupal frontpage. You just need to enable it and just define another path to use (such as site.com/articles). Here is a good series on learning views http://nodeone.se/blogg/learn-views-screencast-series-summed-up (Not affiliated in any way)


Superfish menus getting clipped in blocks

If you can't remove it with z-index: 4; then it might mean that your menu does not have a background; thus, it's transparent.

So add a background to your menu ex: background: white;


I needed to allow users to give either a datetime or just a date, so I needed to override the default date_popup behaviour. NOTE: I am not using the date fields provided with the date uri, just the date_popup form element.

You can override the default date_popup validation. The data_popup module applies the validation function during the date_popup_element_process function.

I used a hook_element_info_alter function to append a custom process function AFTER the date_popup_element_process and applied my own validation function. Like so:

function hook_element_info_alter(&$type) {
    $type['date_popup']['#process'][] = 'my_popup_date_process';
}

function my_popup_date_process($element, &$form_state, $form) {
    $element['#element_validate'] = array('my_popup_date_validate');
    return $element;
}

function my_popup_date_validate() {
    if (isset($form_state['values'][$element['#field_name']])) {
        if (trim($form_state['values'][$element['#field_name']][$element['#language']][0]['time']) == '') {
            list($date_format, $time_format) = explode(" ", $element['#date_format']);
            $element['#date_format'] = trim($date_format);
        }
    }
    date_popup_validate($element, $form_state);
}

Removed unneeded code for brevity. Updated validation funciton with an example showing how this could be achieved. This example assumes that there is a space between the data and time formats (ie "d/m/Y H:i:s") and that the date format is first.


That error means that $menu_item['page_arguments'][0] isn't an object in the context in which that code is run. It's probably happening during a redirect where the page isn't node/123, and so there's no node object available.

You can fix it by adding a bit of error checking (I've taken the liberty of using menu_get_object() instead of menu_get_item(), it's a more standard way of getting the current node object):

function _MO_events_is_event_page() {
  $is_event = &drupal_static(__FUNCTION__);

  if ($is_event === NULL && $node = menu_get_object()) {
    $is_event = $node->type == 'event' || $node->type == 'virtual_conference';
  }

  return (bool) $is_event;
}


I had this same problem few days back. Try to Inspect that broken Images, your Image might have source like this: src="https://ci4.googleusercontent.com/proxy/a0ulmqxF3B*******************************************gMzBa5MRdHDhrBXYc8KaMYIvFZ2HAf3P_lOwFrg=s0-d-e1-ft#http://yoursite/logo.png"

So if you are trying to send email from your local then probably they did not get cached by some google service because probably google can't access your local, try access.log for any issues.
Some other are also facing the same problem:
https://productforums.google.com/forum/#!topic/gmail/q47KoUYQXPw

this problem still persists on my local it has nothing to do with mime mail, or any other module, in fact I was able to send emails with images using only print-email- module try this https://www.drupal.org/project/print

Hope this helps you.
al
PS: If nothing helps try to send mail form live or your development site, you won't face this problem there, because there problem here is google not given access to your images at local machine.


How to migrate multiple columns to single field in CSV Migrate

It took a while for me to solve the issue. However, I was able to manage the same without having to write additional plugin or module. I solved the issues in two steps:

First used the plugin concat to concatinate all 3 required fields to one.
Then used the plugin explode to pass the value to the same field.

Yaml Below:

id: sections_tfr
migration_tags:
  - CSV
migration_group: tfr
label: 'Import sections'
source:
  plugin: csv
  path: /var/www/html/php/tfr/prepared/final/sections.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - s_id
  column_names:
    -
      s_id: Id
    -
      part_no: Part
    -
      sections: Section
    -
      summary_1: Summary
    -
      summary_2: Summary
    -
      summary_3: Summary

process:
  name: sections
  description: heading
  field_summary:
    -
      plugin: concat
      source:
        - summary_1
        - summary_2
        - summary_3
      delimiter: ','
    -
      plugin: explode
      limit: 100
      delimiter: ','
  weight: s_id
destination:
  plugin: 'entity:taxonomy_term'
  default_bundle: sections
  migration_dependencies: null
migration_dependencies: null


How to filter a view when day, month and year are separate fields

You can do that with views php.

Construct your view to take two contextual filters. Do not append any placeholder (%) to the path.

First filter: Add the month field as a contextual filter. Select from the section that reads: When the filter value is not in the url, Provide a default value. A select list Type opens up and from it you select PHP Code and in the PHP contextual filter code you enter:

date('F');

This will match it against today's month in the format of a full string ie. January. Adjust it if your month format is different (if for 3 letter abbrev, use date('M');)

Test this by typing in the month for a node that exists in the Preview with contextual filters text box at the bottom and update preview. It should show you your nodes filtered by month.

Second Filter: Add the day field as a contextual filter, and as above select PHP Code for default value. Add this code:

date('j');

This will filter on the day in the format of 1-31. If you want 01-31 then use date('d');

Test this by typing in the month/day for a node that exists in the Preview with contextual filters text box at the bottom and update preview. It should show you your nodes filtered by month and day.

You can also access the view as such: VIEWPATH/MONTH/DAY and it will show you a result for the values you provided. If you just access the view by VIEWPATH it will give you the result for the date of today.


User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children()

You should return a render array $build. if you want to add a title to the page add title in render array $build.
You can use $build['title'] = [ '#markup' => 'Yours title goes here ];
and return the $build
and in table element use #header instead of $header


Define module parent item to contain other module items

What you are trying to achieve is really simple. You need not use any additional code. You just need to follow the correct menu structure. I've posted a sample code below

     function mymodule_menu() {
      $items['admin/config/development/mymodule'] = array(
      //Your code here
      );
     $items['admin/config/development/mymodule/sub-module-1'] = array(
      //Your code here
      );
     $items['admin/config/development/mymodule/sub-module-2'] = array(
      //Your code here
      );
      return $items;

}

You need to clear the cache. Sometimes you might need to disable and re-enable your modules to register the menu. Now when you click mymodule menu item, a list of all your sub modules will be displayed.


Custom Field Type is missing in Feeds Importer

You might need to create a target for your custom field type with the help of hook_feeds_processor_targets_alter and here is a code sample for doing so:

<?php
function MYMODULE_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name)
{
    foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance)
    {
        $info = field_info_field($name);
        unset($callback);
        if ($info['type']=='MYFIELDTYPE1')
        {
            //The callback for this field type goes here.
            $callback = 'TARGET_SETTER_FOR_MYFIELDTYPE1';
        }

        if ($info['type']=='MYFIELDTYPE2')
        {
            //The callback for this field type goes here.
            $callback = 'TARGET_SETTER_FOR_MYFIELDTYPE2';
        }
        //Add cases for each field type here
        //...

        if (isset($callback))
        {
            $targets[$name] =array(
                'name'=>check_plain($instance['label']),
                'callback' => $callback,
                'description' => t('The @label field of the node.', array('@label' => $instance['label'])),
            );
        }
    }
}
?>


What might cause the unexpected workflow state changes after executing a rule?

Option 1

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are typically 2 ways of debugging, as further detailed below.

Rules Evaluation Log

Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

More info

For way more details about these 2 variations, move on to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".

Option 2

Try to consolidate your 2 rules in a single rule, by using the Conditional Rules module. This module allows you to use Rules Conditions within Rules Actions. So in your case if you can think of an appropriate Rules Event that fits both cases, you simply use the Rules Conditions and Rules Actions within such consolidated single rule, whereas you use Conditional Rules to trigger either (not both!) of your Rules Actions.


Loading bootstrap.inc in external PHP file in a subdirectory

The bare minimum required is:

define('DRUPAL_ROOT', '/var/www/vhosts/mysite.com/httpdocs/');
$_SERVER['HTTP_HOST'] = 'mysite.com';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

If you don't want to fully bootstrap and only get the session, see the technique defined in Getting the current user without bootstrapping to DRUPAL_BOOTSTRAP_SESSION


How to pass formatter settings to field theme function?

Your formatter_view implementation looks ok, very similar to image_field_formatter_view().

However, you're info hook seems to be missing default values for your settings, I'm not sure if they are required or not, but try to add them, again see image_field_formatter_info()

Does the field_formatter_settings form work correctly? Does it show correctly in the summary and keeps the values when you edit it again?

Without more information, the only advice I can give you is install devel.module if you haven't already and make extensive use of dpm() to see where you get which information. For example, contains $display the necessary information in your formatter_view() function?

If yes, it could simply be a outdated theme registry that does not yet know about your additional theme argument (if you added later on for example).


You can use No results behavior on the field. Include the path field and use the field path token.

If there are no results, it picks the node URL.


How can we associate an image & textfield with a specific Domain in Drupal 7?

Domain Fields module works for me as it restricts fields to specific content type on specific domains.


CCK stores values against the vid, so you should be able to see the history of your fields (you can look in tables like content_% to check that the raw data's there). Otherwise a revert would be fairly useless for most situations involving fields. Can you confirm the results of the following?

Create new content type with revisions turned on.
Add text field.
Create a node of this new type (add some text to the field).
Edit the node and update the title, body and field.
Revert the node to its first state.


For Drupal 7

The div with view-content class comes from views-view.tpl.php template file.

You can always override your view theme and adjust the class names, HTML etc..

Under Advanced section of view click on information at the bottom of the section next theme, you will see a list of template files including the top level template which is views-view.tpl.php.

You can find a lot of tutorials how to override views templates file but in general, it's all about copying the right file to your theme and rename it with the right template file.

You can take look at this tutorial how to do that

For Drupal 8

Views UI no longer provide suggestions, In order to get the same information you need to enable Twig debugging.

You can enable Twig Debugging in sites/default/services.yml.

Set the debug variable to true. And clear cache.

parameters:
  twig.config:
    debug: true

(If services.yml does not yet exist; copy default.services.yml and copy it to services.yml.)

Using your browser debugger, you will see the templates suggestion as HTML comments, just be sure your browser debugger is set to show HTML comments.


What operator is equivalent to "Is not greater than or equal to"?

You must use "Is less than" with an offset - just like the screenshot.


How to programmatically submit the file system settings form?

I would not re-create what the form does by hand as @Ayesh does. There is a small chance this form will do more things in a future minor drupal release date (maybe that should never happen, i'm not 100% sure).

What you want to do is look at drupal_form_submit() to programmatically submit a form -- its like visiting the form in a webpage and submitting it without ever opening a browser window. Whatever logic that form does upon submission -- will still happen, eg. create an .htaccess file for you.

You would put the following code into your module install() hook, or you could drush ev this code or make a small php script and run drush php-script myscript.php

Code:

$form_state = array();
$form_state['values']['file_private_path'] = 'sites/default/files/private';
$form_state['values']['op'] = t('Save configuration');
drupal_form_submit('system_file_system_settings', $form_state);

You can then re-submit the form and set the default file serve mode from public to private. Or I would use drush vset or just variable_set somewhere in PHP to set the default file serving mode in drpual. My point is that this is the correct way to programmatically submit a form.


Make sure that cron is running, that should clean that out the watchdog table regularly.

http://api.drupal.org/api/drupal/modules--dblog--dblog.module/function/dblog_cron/6

Drupal has a setting that controls how many rows should be kept, which you can configure at:

Drupal 6: /admin/settings/logging/dblog

Drupal 7: /admin/config/development/logging

Additionally, you should check what kind of logs you have in that table. Maybe a module or something is causing a lot of notices which are all logged there (And considerable slow down your site!)

You can of course simply truncate the table, but you should first figure out why it's not getting cleaned and what is filling it up like that. How many rows are there?


I suppose there are a few ways, but this is how I do it:

You need to have your images managed by Drupal. I use Media module (7.x-2.0) and its sub-modules to first upload my images to the Media library. I make sure that my images have unique file names and I do not change it during the upload (Media allows you to rename after upload, just leave at default).

I then map my images via:

Image -> Images: Ref in the feed settings and use Feeds Tamper to
Explode in case I need multiple images
Images: Alt and Images: Title, again using Feeds Tamper.

In my uploader file I then use the exact same image names as the file names for Image. Feeds will then map to the Drupal Managed File entity ids which it looks up by name via the URI stream wrapper (I think). I also include fields for Image Alt and Title.

If you don't want to use Media then you may use FileField Sources, but getting the images in the very first time is then a hassle.


how to get user name in a view instead of uid

it's in the advanced configuration (click on add relationship):

search and select the uid field (this applies also for entity references for instance)

add a new field to the output, select User: name

select the relationship you created earlier (you can have multiple relationships, e.g. if you have multiple entity references)


The link generated by a View's header (Global: Text area) is only visible for the admin role and I need it to show for other roles

As per your code , you need to make sure two things...

Logged in User should have create page content access in permissions since your code checks for that permission
Logged in User should also have access to create articulo content "node/add/articulo" since l function checks for user access of the  path he is trying to access.

Make sure logged in user role have both permissions in your permissions list. Clear cache and rebuild permissions before verifying.

In your case , Make sure the different role you are mentioning has "create page content" permission.


Core provides several examples of this.  The basic pattern is to create a test module, and have that module provide the form.  In your test ::setUp(), you add the test module to $modules, and then your form should be available for use.

Look through 'core/*/tests/modules' for the test modules, and if you have an IDE that class completes, a lot of the test form are (wait for it) TestForm.

However, in your case, I would look at existing Element classes and see what their integration tests look like.   I suspect you can just emulate what they are doing w/o needing your own test module.


How do I diagnose a unstable installation on ubuntu 16 server?

Unless you are using Drupal 6, I suggest you start again from scratch and use/install PHP 7.

Drupal 8 and 7 (since 7.50) support PHP 7, which is twice as fast as PHP 5.

sudo apt-get update
sudo apt-get install apache2
sudo apt-get install curl
sudo apt-get install mysql-server
sudo mysql_secure_installation

Would you like to setup VALIDATE PASSWORD plugin? n

Change the password for root ? n

Now, for the rest of the questions put y

sudo apt-get install php php-cli php-curl php-gd php-mbstring php-mcript
a2enmod rewrite
sudo service apache2 restart

Now, Install and Secure phpMyAdmin and create a database with and a user with privileges. Do a fresh Drupal install and make sure you get no errors in the install screens.

Once all ok, dump all your DB tables and import your site. Make sure your Drupal directory contains all your modules and the files folder contains all your images and files of your importing site.


Installing demo content via module.install file with Migrate module

Ok, I now understand that registering a migration is only registering it, not importing it, you still have to process the import.  I now call the _panopoly_core_import_demo_content function which executes $migration->processImport();

<?php

/**
 * @file
 * Installation file for Parcel Event Demo
 */

/**
 * Implements hook_enable().
 */
function parcel_event_demo_enable() {
  Migration::registerMigration('ParcelEventMigrateEvent');
  _panopoly_core_import_demo_content(array('ParcelEventMigrateEvent'));
}

/**
 * Implements hook_disable().
 */
function parcel_event_demo_disable() {
  _panopoly_core_rollback_demo_content(array('ParcelEventMigrateEvent'));
  Migration::deregisterMigration('ParcelEventMigrateEvent');
}


Have you tried this code ?
I have taken it from here

// Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'two-sidebars';
  }
  elseif (!empty($variables['page']['sidebar_first'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-first';
  }
  elseif (!empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-second';
  }
  else {
    $variables['classes_array'][] = 'no-sidebars';
  }


Unable to render title field on node template

I was able to print the title using

print $title;


Regions not showing in block region demonstration

It's pretty hard to troubleshoot, but I would really recommend looking at the .theme file again. It sounds like the region is not configured/configured incorrectly there. Maybe post that here?


Drush disable module updates email notifications

You can turn off just the email notify feature like this:

drush vdel update_notify_emails

(See in update.fetch.inc: $notify_list = variable_get('update_notify_emails', '');)

You might also want to consider the following alternative:

drush pm-disable update

This will completely disable the update module on your live server, which will also disable email notifications about Module updates.  At first blush, you might be sad that you won't be able to see the module updates page on your live server any more; however, you should really be doing your updating on a development machine anyway, so you can just re-enable update on the dev server.

To automatically re-enable the update module every time you sql-sync from live to dev, see symc_enable.drush.inc.

Finally, to insure that your dev machine does not send out unwanted email notifications, enable the devel module, and then add to your settings.php file:

$conf['mail_system'] = array(
  'default-system' => 'DevelMailLog',
);
$conf['devel_debug_mail_directory'] = '/path/to/dir/to/save/email';

Then, devel will intercept all email that is sent and write it into the target directory instead of emailing it.


How to handle refunds / returning goods with drupal commerce

There hasn't been created any module that handles this. How to approach this also depends a lot on the custom logic in your store like

How are payments created
How should payments be refunded
What happens if returned goods has damage
...

Anyways, what you could do for starters, is to create a custom order status to mark that the goods have been returned. Most of the rest is most likely custom store logic anyways.


Drupal 7 open image in colorbox when a “button” on the image is clicked, otherwise go to content

In Drupal 7 you can achieve it by the following steps

Steps

Create a new VIEW and add the following fields
Background image : Add the image which you want to show as background image using imagestyle. Also add the link to the node using Link image to. And check Exclude from display.

Colorbox image : Add the image which you want to show inside COLORBOX using imagestyle. Dont add the link to this image and check Exclude from display

Image icon : Add the image which is used to render on the top of the background image  using imagestyle. And check Exclude from display.This image we will use in COLORBOX TRIGGER field.
Colorbox Trigger : Add this field and make Image icon field as the TRIGGER FIELD and Colorbox image as its CONTENT by use "Replacement patterns".

Custom text : Add Global: Custom text field and add the below html inside it and make sure you should replace [Background image] and [Colorbox Trigger field] using "Replacement patterns". It act like a container.

[Background image]

[Colorbox Trigger field]

OUTPUT

Note : Arrange the image icon above the background image using CSS


You can convert your PDF to a series of images and show them as slideshow, using the PDF To ImageField module.

  The PDF To ImageField module provides automatic conversion of uploaded PDF files to images.
  It can be used either to create a snapshot of the front page to use as a preview thumbnail, or to generate a gallery of images from each page in the document.

  The module is implemented as CCK widget for FileField where PDFs are uploaded to. It places generated images into a CCK ImageField on the same content type.


Views Slideshow with jCycle - Making it 100% flexible repsonsive

An easy way of making the slideshow responsive is by overriding the css something like below:

.views_slideshow_cycle_main {
  width: 100%;
  float: left;
}
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame {
  width: 100% !important;
  height: auto;
}
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame-row {
  width: 100% !important;
  height: auto;
}
.views_slideshow_cycle_main .field-content {
  max-width: 100%;
  width: 100%;
}
.views_slideshow_cycle_main .field-content img {
  max-width: 100%;
  width: 100%;
  height: auto;
  margin: 0;
  padding: 0;
}

The changes you where doing might be getting overriden by default styles as those were taking the precedence.

Reference: views Slideshow for Responsive design

Alternate solution:
Give a try to Flexislider module: Flex Slider module integrates the Flex Slider library with Drupal and several contributed modules which allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

Some features of FlexSlider slideshows include:

Touch enabled nagivation
Keyboard navigation
Configurable slide animations
Multiple sliders per page


How to restrict a page to a group of people?

You can add the secondary database to Drupal by following this tutorial: https://www.drupal.org/node/18429

I would probably run a hook_node_view so that it's called before rendering the node and adding your custom logic there.


What is the correct workflow for updating a high traffic site?

Drush and command line are for rescue here:

1) To clear cache selectivelly, just run drush cc and drush will provide you with different options to select from, so you can clear everything or just theme registry, js/css, views, pages, etc.

2) To regenerate script use this bash script: http://dropbucket.org/node/241. It reads your sitemap.xml and revisits all pages, warming up cache.

3) Additionally, consider using Drush Entity Cache Loader http://drupal.org/project/drush_ecl, it doesn't generate page cache for you, but warms up content cache, so when authorized user loads the page, nodes and other entities are loaded from cache instead of being generated on the fly.


How can I throw a form error if a submission field has a certain value in webform?

Create your own validation function of your webform and do it there:

function modulename_form_webform_client_form_FORMID_alter(&$form, &$form_state, $form_id) {
     //FORMID - your webform id
    $form['actions']['submit']['#validate'][] = 'modulename_form_webform_client_form_FORMID_validate';

}

function modulename_form_webform_client_form_FORMID_validate($form, &$form_state) {
    //validate it here
    if ($form_state['values']['yourvalue'] == 'somevalue') {
        form_set_error('you can\t do that');
    }
}

also you can use hook_form_alter to provide your own validate function.
Further reading form_set_error, hook_form_alter,


I found the issue. The taxonomy terms where stored without the taxonomy_term_hierarchy information. This info is needed for the list of terms in the admin list to determ the relations between the terms.

This was caused by me, I've removed the hierarchy field from the form. This caused Drupal to not save this information at all. There are no default values or something like that here.

https://www.drupal.org/files/drupal7-db-schema.png


How can get the current region inside the 'hook_preprocess_block'?

As described in the documentation for template_preprocess_block(),
$variables['elements']['#block'] is available, and it contains the Block object. With that, you can get the region to which the block is assigned with Block::getRegion().

function ThemeName_preprocess_block(&$variables) {
  if (isset($variables['elements']['#block']) && $variables['elements']['#block']->getRegion() == 'nav') {
    $variables['attributes']['class'][] = 'SomeStyle';
  }
}

That is slightly different from Drupal 7, where hook_preprocess_block() would get the region assigned to the block from $variables['block']->region, or from $variables['elements']['#block']->region. See template_preprocess_block() (Drupal 7).

  $block_counter = &drupal_static(__FUNCTION__, array());
  $variables['block'] = $variables['elements']['#block'];
  // All blocks get an independent counter for each region.
  if (!isset($block_counter[$variables['block']->region])) {
    $block_counter[$variables['block']->region] = 1;
  }


It means the global scope, ie anything outside a function and namespace. It's the PHP 'global', not anything specific to drupal.

People tend to use module_load_include at the top of .module files to bring in includes, much like in a traditional standalone PHP project.

This is potentially bad because the required elements might not have been bootstrapped at that point, which can lead to errors; hence the warning not to use it in a global context.


save the value of a custom form in the database

hook_schema is called at install and unistall, so make sure your actually installing the module and not just turning it on.

If you've already had your module running on your site, switched it off at /admin/modules and then switched it back on, drupal doesn't recognize this as an uninstall/install event. Rather, you need to fully remove it from the DB by going to admin/modules/uninstall after switching the module off.


what benefit is it to clearing the Drupal cache now that I have Varnish in front of Drupal?

Whenever Varnish Cache expires it asks Drupal to give it the rendered page. Drupal in turn sees if it can server the page from the Cache. If yes it will server from the cache, else it will regenerate the page.

In short, when you clear the Drupal Cache,

No changes are visible to end users for whom the content is served from Varnish.
When the Varnish Cache expires, it will fetch the content form Drupal. Now that you had cleared the Drupal cache, instead of serving from the cache the page will be rebuilt.


URL with "en" for english language does not work

I found the solution. Default language "English" requires the code to be enabled like the way when we add/change the code for new languages.

Go to configuration click languages.
Click "edit" for default language "English".
Now put code language code "en" in "path prefix language code" text field."
Save changes and access Url with/without "en" code. It will work in both cases for default language.

Thanks.


One thing you can do is create a second block display view that's simply an html list of events (rather than a calendar display) and put that block on the same page as your current mini calendar.

The trick is that that event list can be set up to take a contextual filter that only displays it when you click on a day from your first calendar.

Here's how you can make it work

Customize your calendar-datebox.tpl.php file (except make sure you name it such that you're only customizing it for your specific calendar block, rather than globally) and place in your custom theme's templates folder.  It should have something like this, rather than the typical one line it comes with:

// Notice how I'm placing the current day's selection into a URL variable called selected_day.  You may need to customize this a little to fit your needs.
<?php
  if ($selected) {
       $output = '' . $day . '';
} else {
  $output = $day;
}
?>
<div class="<?php print $granularity ?> <?php print $class; ?>"> <?php print $output; ?>

Once you've done that, the links that are printed for your days that have events, will just add a parameter to your existing URL that is called 'selected_day', rather than replacing your calendar block.
Now just create a new block, which is an html list that prints out the event's name, time and description, like you have in your screenshot.  Place that block on the same page as your current calendar either via a context or your block's admin screen.
Create a contextual filter for your new block listing, which should be the event's start date.  Set the default value to be a php snippet, which just gets the url's 'selected_day' variable

  return $_GET['selected_day'] ;

If both of your blocks are present on the page, the second one -- the listing -- shouldn't display anything until you click on an event date, at which point the url's variable will be created and the second block should appear.  I just did a small test, and it works for me.

:-)