Moving a number of fields into a table on D7 node form

There is an API that will allow you to alter the output of the field group or write your own field group handler. https://www.drupal.org/node/1017962

Using this you could write a custom field group handler that loops through the fields and outputs the data using theme_table(). This would allow for you to grab the field label and add it to the header array, and then add the fields to the the data array.

After creating your custom field group you can nest the field group under the horizontal tab and nest your fields under the custom group.


Alternative to .htaccess compression with Boost

Core should support .gz for CSS & JS. This requires .htaccess rules though. For core they should already be included.

Looks like I never got around to gzip for Boost for 7.x. You can follow the issue here
http://drupal.org/node/1416214


Check if there is already a valid one-time-password -reset link

In D7 one-time reset pw links are generated using the normal hashing techniques (plus a timestamp) but they are not saved in the DB (see  user_pass_reset_url). This means that there is no way to resend a link (without doing some major work to store this on your own). I don't see why you would care about resending the identical link, but I'm sure you have your reasons.

If they do click a reset password link, I would recommend that you style the password reset page using a completely different page template that does not include your navigation links (etc...) rather than trying to disable them. Just be sure to add a message with a link to the homepage (or where ever) once they successfully edit their password, or even better, do a redirect upon success.


Taken from the API page:

views_handler::ensure_my_table

  Ensure the main table for this handler is in the query. This is used a
  lot.

It's just to make sure that the base table (node or user for example) that your handler needs is referenced in the query/actually exists.


How to migrate Drupal nodes from one installation to another, preserving revision history?

You can also try UUID and UUID Features, can export both Nodes and Nodes revisions.


Search for product displays based on info from products in Commerce

Use Commerce Search API module. Basically you are gonna have to set up Facets to achieve what you want.

This screen cast here walks you through on which modules you have to enable and how to tweak your configurations.


After trying quite a few things, we ended up putting together a shell script to do the provisioning. Most of it is specific to our application, but here are the relevant excerpts for anyone who might want to try this:

(there is probably some configuration necessary that this script omits)

#!/bin/sh

cd ~

echo "Beginning fresh install..."
sudo apt-get update

echo "Installing base utilities..."
sudo apt-get -qq -y install zip unzip

# Install LAMP stack
echo "Installing LAMP stack..."
sudo apt-get -qq -y install tasksel && sudo tasksel install lamp-server
sudo apt-get -qq -y install php5-gd php-pear php5-xdebug php5-dev php5-curl
sudo a2enmod rewrite # Enable apache rewrite module

# Install pressflow if necessary
echo "Downloading and installing pressflow..."
wget -qNO /tmp/pressflow.tar.gz https://github.com/pressflow/6/archive/pressflow-6.26.109.tar.gz
sudo rm -rf /tmp/pressflow && mkdir /tmp/pressflow
tar -xzf /tmp/pressflow.tar.gz -C /tmp/pressflow
sudo rm -rf /tmp/pressflow/6-pressflow-6.26.109/sites/all
rsync -a /tmp/pressflow/6-pressflow-6.26.109/* ~/yoursitepath # !! Your Drupal directory here.
sudo rm -rf /tmp/pressflow /tmp/pressflow.tar.gz

# Update php.ini
echo "Updating PHP config options..."
PHPINILOC="/etc/php5/apache2/php.ini"
sudo sed -i 's/memory_limit = 128M/memory_limit = 1024M/g' $PHPINILOC
sudo sed -i '/error_reporting = E_ALL.*/c\error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT' $PHPINILOC

# Create database schemas
echo "Creating databases..."
mysql -uroot -e"CREATE DATABASE IF NOT EXISTS ourfa5_drupal; CREATE DATABASE IF NOT EXISTS stats;"

# Here, you'll probably need to download any default tables needed by your
#   application, update /etc/hosts, etc.. This portion of the script is
#   specific to our application so I've left it out.

# Restart apache for good measure
sudo service apache2 restart

sudo apt-get upgrade


How to theme a menu in drupal 7 with this html

Use theme_menu_tree() theme function overrides

https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_tree/7

Copy the contents of 'Code' on these pages to your theme's template.php and change the 'theme' in the function names to the name of your theme, for example:

function yourcustomtheme_menu_tree($variables) {
  return '
' . $variables['tree'] . '
';
}

Make the changes to the HTML tags, save the template.php and clear caches.

Also if you just want to customize HTML for a specific menu, you can name your functions like this: THEMENAME_menu_tree__MENU_NAME()


Prevent WYSIWYG inline images from showing in Teaser Display

Perhaps you could try https://drupal.org/project/advanced_text or https://drupal.org/project/smart_trim?

I think they both have the ability to strip html from teasers.


Open Webform in a modal, but deny access to the form url

Not sure if its the best way but I had something similar to do to allow viewing an entity only on a specified route and if some other conditions were met.
I created an EventSubscriber which basically decides if the user is allowed to access the page or not.
<?php

namespace Drupal\MY_CUSTOM_MODULE\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Custom class RedirectSubscriber.
 */
class RedirectSubscriber implements EventSubscriberInterface {

  /**
   * Custom function to check if we should redirect.
   */
  public function checkForRedirection(GetResponseEvent $event) {

    $route = \Drupal::routeMatch()->getRouteName();

    // If route is group add form.
    if (isset($route) && $route == "entity.group.add_form") {
      if ("MY CONDITION IS NOT MET") {
        //REDIRECT OR DO SOMETHING ELSE
        $event->setResponse(new RedirectResponse('/random-page url'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => 'checkForRedirection',
    ];
  }

}

Also, if you decide to do this, don't forget to register your event subscriber in the services.yml file.
services:
  MY_CUSTOM_MODULE_redirect_event_subscriber:
    class: Drupal\MY_CUSTOM_MODULE\EventSubscriber\RedirectSubscriber
    tags:
      - {name: event_subscriber}


change an exposed filter from a select box to a text field search

This might help you,

http://drupal.org/node/506654#comment-6412784

Views autocomplete filters


How to use entity reference field titles in Views exposed and combined filters

You just need use Views Reference Filter module


How do I add a variable to $node from a module?

Try hook_node_load(). With this hook you can add info to a node.


How to load a view with ajax so that additional js/css files needed by the view are also loaded?

Hmm, I feel like this question deserves a bigger bounty :-p but none the less here's my attempt at answering this.

Drupal already loads any extra css/js now I can't really find much documentation on it and sadly the JS files aren't easily documented without actually reading through the code but is there.

You really should try to avoid making $.ajax request yourself and instead wrapping everything with Drupal.ajax also if you use the Ajax System you don't even need to write the ajax request your self.

By implementing a proper Drupal ajax request using ajax commands most of the css/js handling will be done for you automatically.

By looking at your above code it looks like you you're making the same request views would normally do it self. So you should probably let views handled the ajax request and overwrite the ajax commands thats going to be fired to be your command. You can do this by either implementing a hook_ajax_comamnd_alter but it kinda sucks with views because you loose all contextual information so I would recommend using hook_views_ajax_data_alter instead.

I know there's not much code in my answer, but it's hard to answer with code, being that the code currently there is not correct to being with.

For more information see Drupal.ajax in the misc/ajax.js file. For an example of implementing an ajax request with Drupal.ajax see the views ajax file. And if you want to see and example of views normal behavior being overwritten by changing the ajax commands see the views_load_more module where I do this behavior.

Also please feel free to comment on this answer, if anything here is unclear.

On and for more info on the Ajax Framework see Ajax Framework for example see the example module, even thought most of what you want to do is not cover in the examples module.


Is there a way for Forena to restrict the debugging messages to selected roles?

1. About the debug option

The debug option for a Forena data source is one of the options you enter when defining a data source. If enabled (value = TRUE), it'll actually trigger logic as shown in this logic:

  public static function debug($short_message='', $log='') {
    if ($log) {
      watchdog('forena debug', $log, NULL);
    }
    if ($short_message) {
      drupal_set_message(check_markup($short_message));
    }
  }

2. Restrict debugging messages to selected roles.

Defining the options for a data source (such as the debug option) can be done as described in the tutorial that comes with Forena (i.e. within the Data Sources Settings):

Defined using Forena's configuration data tab (within the admin UI).
Defined within settings.php files which allows for including PHP logic.
Defined by a module using a forena_alter_repos hook.

So the actual answer to your question depends on how you define the data source, as further detailed below.

a) Using Forena's configuration data tab (within the admin UI).

Using this option there is no way to answer your question, except if you would want to hack the logic shown above (which I do not recommend).

However by using the Disable Messages module you should be able to  restrict the debug messages to select roles only (though it'd still write the watchdog messages). Refer to "Option 1" in my answer to "How to show messages starting with "Debug : " to an administrator only?" for more details on that (not sure if "Option 2" of that answer would make sense in this case also).

b) Using a settings.php file

Include the desired PHP logic to assign a value (TRUE or FALSE) to $conf['debug']. Have a look at the repos/sample/settings.php file that comes with Forena for an example to start from.

c) Using a custom module

Using hook forena_alter_repos (documented within Available Hooks in the Development Guide).

3. Alternative solution

From your question, it seems that your developer is designing new queries (during normal business hours) in your production environment ... There must be good reasons to do (allow) that.

However, as an alternative, you could also define an additional data source that points to the same database, and for which you enable the debug option. If you combine this with "Access [data source] Data" (as described in Forena's Permissions) you could easily limit access to this data source to developers only. And after the data blocks (SQL queries) that they created are finish (approved), just MOVE the file containing that SQL query to the regular data source.

Disclosure: I'm a co-maintainer of Forena.


The custom node template file is not working

Try node--product_display.tpl.php.

If your file is empty, it will show the default template file; make sure you have write something in your custom file.

Be sure to clear the cache.


List all nodes related to a term which is related to another one

If you don't have Views installed, install the Views module.

Create a taxonomy view
Add filter to filter your taxonomy.
Add a relationship to other taxonomy you want.
Add the relationship to nodes.


Are you trying to print full display mode + teaser mode under full display mode? You can always render any display mode directly using node_view as

  node_view($node, $view_mode = 'full', $langcode = NULL)

or with your example:

switch ($view_mode) {
case 'full' :

//content for full view mode here

$rendered_teaser = render(node_view(node_load($nid), 'teaser'));
print $rendered_teaser;

...

I would also recommend breaking your display mode templates out into separate files to simplify management. If your full mode should be the same as your teaser then using this method you can always just symbolically link the files on your server.


Try the Quickbar module.

This is a simple administration toolbar. It allows you to take any menu and assign it to a role. This menu will be displayed at the top of your page as an administration toolbar.

Most of this module is taken from [the] Admin [m]odule version 1.x. It also uses some features from the Toolbar module.


Is there a real-time inline field validation module?

Use Rich Form Module.

This module gives you a framework to easily make client side and server side validation in the same time. It increases the validation features of the Drupal Form API (FAPI). If you want to have a powerful tool for creating custom validation logic to any text field, without writing a tons of codes, this module is for you!


How can I increase the number of excerpts shown per result?

[Update] Figured it out.Here's the solution I found. Somebody much more experienced than I will probably come along and offer better ideas but this works for now.

Leave "Retrieve result data from Solr" and "Retrieve highlighted snippets" unchecked, and just edit solrconfig.xml to define your snippets parameters like so:

<str name="hl">on</str>
<str name="hl.fl">fieldname</str>
<str name="hl.snippets">20</str>

Now solr will return the specified snippets in the results even if Drupal doesn't do anything with them. I cobbled together a simple module that implements hook_search_api_solr_search_results_alter (found in search_api_solr.api.php) to grab the results and store them in the $_SESSION variable:

excerpted from the solr_snippets.module I Frankensteined together:

function solr_snippets_search_api_solr_search_results_alter(\Drupal\search_api\Query\ResultSetInterface $result_set, \Drupal\search_api\Query\QueryInterface $query, \Solarium\QueryType\Select\Result\Result $result) {

    if(!isset($_SESSION['solr_snippets'])) {
        $_SESSION['solr_snippets'] = array();
        }
    $myResults = & $_SESSION['solr_snippets'];
    $myResults = '';
    // Grab the result items
    $result_items = $result_set->getResultItems();
    // Grab the highlighted snippets
    $extra_data = $result_set->getExtraData('search_api_solr_response');
    $highlights = $extra_data['highlighting'];
    [ process the results here and load them back into $myResults ]
    }

Then they are picked up by a view field:

  public function render(ResultRow $values) {

    return [
        $build['search_results'] = [
           '#theme' => 'solr_snippets',
           '#results' => $_SESSION['solr_snippets'],
          ],
        ];
  }

I also had to find a way to get the row count to the field template since it doesn't appear to be passed automatically. I didn't find the right way, but the method that worked for me was to implement hook_preprocess_views_view_field() and add it to the session variable:

function solr_snippets_preprocess_views_view_field(&$variables) {
    $_SESSION['solr_snippets']['rowNum'] = $variables['row']->index;

}

That's it, works great and I can use the twig template to customize the SERP results. Credit to https://drupalium.com/articles/creating-custom-view-fields-programmatically for the basic module that I hacked apart to make this. Also Drupalize.me was a Godsend.

Just to reiterate to anyone looking to do the same - what I did here was definitely not "best practice." Be careful and good luck!


limit_validation_errors resetting form values in submit handler

#limit_validation_errors prevents values from being passed to the submit handler, since they have not been validated. You can whitelist values by passing the form element key to #limit_validation_errors:

'#limit_validation_errors' => [
  // format follows the same as in the form state values. Elements
  // that are not #tree will be a string. Nested elements will be
  // an array.
  'element1',
  ['wrapper','element2'],
];

If you want to limit validation, but need all the values in the submit handler, then it's better to not use #limit_validation_errors. Instead, you can wrap any validation in a conditional to check if the 'next' button was clicked:

if ($form_state->getTriggeringElement() == $form['actions']['next']) {
  // Do form validation here. If the 'back' button was clicked, this
  // validation code will not be clicked. It will only be validated if
  // next has been clicked.
}

Note that if you use #required, validation will still happen even with the above code, since #required is handled separately. In this case, I don't use #required, instead I'll add custom validation to the above code:

if ($form_state->getTriggeringElement() == $form['actions']['next']) {
  // Do form validation here. If the 'back' button was clicked, this
  // validation code will not be clicked. It will only be validated if
  // next has been clicked.
  if (!strlen($form_state->getValue('some_element')) {
    $form_state->setError('some_element', $this->t('Please fill in a value for some field'));
  }
}


How to add java script in a content type: article or blog or basic page

You can add javascript in template file using hook_preprocess_page() function.

<?php
function mythemename_preprocess_page(&$vars, $hook) {
  if(arg(0) === 'node' && arg(1) === 'add' && arg(2) === 'article') {
    drupal_add_js(path_to_theme().'/js/events.js');
  }
}
?>

Other solution is that you can use theme function.

function theme_content_type_node_form($form) {
  drupal_add_js(...);
  return theme('node_form', $form);
}

This just calls the default theme function for the node add form after adding the js. As the theme function is called even the form is cached, this works nicely. You also need to implement hook_theme to make this work.


Set image as permanent in custom block plugin, temporary URI

To set the correct file scheme is necessary to define the upload location in the form array.

I've amended the form as follows:

public function blockForm($form, FormStateInterface $form_state) {
  $form['upload_image'] = [
    '#type' => 'managed_file',
    '#title' => $this->t('Upload Image'),
    '#default_value' => $this->configuration['upload_image'],
    '#upload_location => 'public://blocks',
    ];

  return $form;
}

The URI and URL are now as expected and the file is permanently saved.


This is the listing page for the taxonomy items, correct? the node page would be after you click on one of these to see the full content of that particular piece of content? And, if I understand correctly, you want a two column layout of this list? Here is a site I did recently that does that very thing.

http://noboribetsu-spa.jp/en/stay

This is very easy to accomplish. Just float left the class that wraps the item and all of them will fall into place. Let me know if I am not understanding what you are asking.


Menu Block: Expand all children of this tree - ignored?

I had the same problem... Bug was dependant of my theme which have a theme_menu_link preprocess function. If I delete this function and clear cache, menu block works as designed.
To be quickly sure, enabled bartik and look the behavior of your menu block.

@see http://drupal.org/node/1425342#comment-5679426


Create a view to display the list of content created by user and any published content

You anyway want to display all content from all the authors and current user so no need to add contextual filter, then it's going display all the content from your site with logged in user's content too.

Also you can try this link


What is the right way to count filled multi value field values in drupal?

$wrapper = entity_metadata_wrapper('entity_type', $entity);
dpm($wrapper->{FIELD_NAME}->count());

Dealing with entity reference field you can get the identifires like this:

dpm($wrapper->{FIELD_NAME}->value(array('identifier' => TRUE)));


How can I check if an image style for an image has been created already?

I couldn't find one in the core files but fortunately it's pretty straightforward to implement:

function image_style_path_exists($style_name, $path) {
  $uri = image_style_path($style_name, $path);
  return file_exists($uri);
}

Assuming you have a file object you would call it like this:

$image_exists = image_style_path_exists('thumbnail', $file->uri);

If you only need to use it once in the site you could boil it down to:

$image_exists = file_exists(image_style_path('thumbnail', $file->uri));

but it's usually better to separate this sort of thing out into a function


How to have a Conditional Field in node form?

You have the Conditional Fields module that works very well in Drupal 7, unfortunately there is not a Drupal 8 version, you can check this issue to find out its progress. If you want you can test the dev version, but I don't know if it works.

Other module in dev is the Field States UI

  Field States UI allows sites builders with minimal PHP/Dev skills to
  configure the Field States API. This lets you configure a field to for
  example hide if another field has a certain value or hasn't been
  filled. While doing it via PHP can be be more powerful the UI can be
  very handy and in some cases quicker.

In the other hand you can make use of the #states property.

EDIT:
As the OP says in the comments there is another module named Field Formatter Condition that can be used for accomplish this task.


Set permission for a specific column in view for table format in drupal 8

you need to do something like this in global php field :

$uid = 1;
$user = \Drupal\user\Entity\User::load($uid);
$roles = $user->getRoles();
$v=$roles[1];
if($v == "administrator")
{
echo "your-content";
 }

Global php field will be available as Replacement pattern add that variable in your custom text field.


How do I call the menu_rebuild function in Drupal 7?

Drupal 7

If you're using drush, you may run:

drush eval 'menu_rebuild();'

If won't work, see: How to do menu rebuild when having PHP Fatal error?

Drupal 6

drush php-eval 'drupal_rebuild_theme_registry()'

memcached

If you're using memcached, you've to restart it.

On Linux: /etc/init.d/memcached restart

On OS X (if using Homebrew): brew services restart memcached


How do i rewrite path field in views-view-fields.html.twig inside a href tag?

Probably because {{ fields.path.content }} actually is
/your/path
 and not just /your/path

So try with

If the above does not work

Try

Another possibility is that if you have Twig Debug turned on, this will screw up your template. Turning the twig debug off will fix it.


Execute some steps before REST POST request

There is a hook called entity_presave.

This is always called when you persist a new or updated entity through Drupal API.
You can always check for the current request's method to see if it was a POST method (you can also check for the route itself).
So these presave changes (or can be save or post save) will be only taken place if that criteria is met.


How to change value of a node field after a webform is submitted?

If typo:

if($reservableItem ->type == 'items'){

change into:

if($reservableItem->type == 'items'){

In my implementation I get the submission values like:

$submission->data[3][0]

So try to change it accordingly


A question about views and how to let sub menus link to the view like the main menu

By default a link will be created to the full node view, as you described. When you want an item to link to another url, you need to rewrite the url.

To do so go to the view settings page and click on the field you want the link to be different of. Next go to the 'rewrite results' part of the settings schreen. check 'display field as link' and enter the correct url in the 'path' field.

Hope this helps


Simple row saving through link with Drupal 7

take a look at the Favourites module:

  Favorites provides a tiny block that allows users to easily bookmark
  any content of the site.

or the Flag module:

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, users, and any other
  type of entity. Some possibilities include bookmarks, marking
  important, friends, or flag as offensive. With extensive views
  integration, you can create custom lists of popular content or keep
  tabs on important content.


Auto Complete displaying wrong for non-admin users

I think anonymous user doesn't have a permission of autocomplete. Can you please visit permission tab of your site. May be you get some luck!

Hold on, you are using taxonomy right, then please check this module permission. I think that time you get some luck.


I would create a content type for the link and then there are two options I can think of:

Linkit, but I'm not sure it has a create option
Nodereference with a module like Node Reference Create or References Dialog


Unable save/update any content after migrating from local to production

Check mod_rewrite (server module) and .htaccess (configuration files in Drupal installation, which easily can be left behind when copying) which take care of lot of the URL and path functionality.

Read more from https://drupal.org/getting-started/clean-urls

Credits to this question:
Can't save settings after copying site to new server


Where do I put image style definition in a module?

I think its better to use features and export it, then in your .info file add dependency to it.

other solution is what you say, put it inside MYMODULE_image_default_styles in your .module and re-install your module to make it locked in admin


Thanks Clive for get clue me about this prblem.
according  https://drupalcommerce.org/user-guide/configuring-creating-customer-profiles
`EDIT CUSTOMER PROFILE
Here we are editing the customer profile. Normally this might need to be updated to account for a customer who needs to change their shipping address or other kinds of updates. Note that the original customer profile does not get lost, we simply clone a copy of the original and make the changes. We are doing this action to show you how this process works. Note that this means, by default, if you edit a customer profile it does not change the original order.'


Upgrade Commerce Kickstart 1 site with drush

According to this page http://www.drupalcommerce.org/commerce-kickstart-2/install you should use Drush 8.x-6.x for an upgrade.


What is the variable/method to address the content type in a template file?

call the getType method of the node object, like:
 node.getType() == 'article'


Why bootstrap sub-theme with sass starterkit is not working?

Thanks to @JeffBurnz @MarkCornoy and @FreeRadical for their inputs.

The following setting needs to be disable in mysubtheme.info(sass.starterkit A original file). And may be @FreeRadical want to point out same thing by asking "Have you removed the CDN?" in the his comment.

  ; Disable the CDN provider so compiled source files can be used.

  settings[bootstrap_cdn] = ''

After commenting out settings[bootstrap_cdn] = '' it does take the base theme setting.

Any more suggestion appreciated. For now, this solution works.


Field Group Conditional State does not work after upgrade

Searched for some time. Tried different options. Finally reverted to older version 1.3 and it worked just fine :)

This was the bug which has not been addressed in the dev version as of now: https://www.drupal.org/node/2283245

Thanks.


The class implementing the block showing the theme logo, in SystemBrandingBlock::build() contains the following code.

  $build['site_logo'] = array(
    '#theme' => 'image',
    '#uri' => theme_get_setting('logo.url'),
    '#alt' => $this->t('Home'),
    '#access' => $this->configuration['use_site_logo'],
  );

So, for the path of the logo, you can simply use theme_get_setting('logo.url'), which returns "/core/themes/bartik/logo.svg", in my test site.

If you want a relative URL for the logo file, for example because you want to use it for the src attribute of the <img> tag, you can do as template_preprocess_image() does.

$relative_url = file_url_transform_relative(file_create_url(theme_get_setting('logo.url')));

For an absolute URL, you can use the following code.

$absolute_url = file_create_url(theme_get_setting('logo.url'));

That code needs to go in a preprocess function, where it initializes a variable. For example, if I wanted the relative URL of the logo file in html.html.twig, I would use the following code.

function mytheme_preprocess_html(&$variables) {
  $variables['relative_logo_url'] = file_url_transform_relative(file_create_url(theme_get_setting('logo.url')));
}

And in the template, you would just use {{ relative_logo_url }} to get it.


How do you customise the Group subscription format

You can make use of the string override module

  Provides a quick and easy way to replace any text on the site.


There is undefined value in fieldCondition. there are some examples listed below. try one of these format.

->fieldCondition('field_foo', 'tid', array('12','13'), 'IN')
->fieldCondition('field_foo', 'value', 'spotlight', '=')
->fieldCondition('field_foo', 'fid', 'NULL', '!=')
->fieldCondition('field_foo', 'tid', $value)
->fieldCondition('field_foo', 'value', $year. '%', 'like')
->fieldCondition('field_foo', 'value', NULL);


How to alter view query after exposed filter is changed?

Using d70rr3s suggestion and this patch (required), I came across this solution that worked.

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implements hook_views_query_alter().
 */
function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
   if ($view->id() == 'myview'  && !empty($view->exposed_raw_input['field_country']) && $view->exposed_raw_input['field_country'] !== 'all') {
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'your_entity.field_country') {
          $field = 'node__field_country.field_country_target_id';
          $value = 'somevalue';
          $operator = '=';
          $query->addWhere(2, $field, $value, $operator);
        }
      }
    }
  }
}

Results:

WHERE (((node__field_country.field_country_target_id = '10')) OR (node__field_country.field_country_target_id = 'someValue')) AND (node_field_data.status=1) AND (node_field_data.type='article')

Filter Criteria where #1 and #2 from screenshot had to be applied:


The wrong site title is coming up for home page

Normally the <title> element is set in template_preprocess_html

  // Construct page title.
  if (drupal_get_title()) {
    $head_title = array(
      'title' => strip_tags(drupal_get_title()),
      'name' => check_plain(variable_get('site_name', 'Drupal')),
    );
  }
  else {
    $head_title = array('name' => check_plain(variable_get('site_name', 'Drupal')));
    if (variable_get('site_slogan', '')) {
      $head_title['slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
    }
  }
  $variables['head_title_array'] = $head_title;
  $variables['head_title'] = implode(' | ', $head_title);

That is then output in your theme html.tpl.php

You may have some code or configuration overriding the default title there in a module or theme.

I'd suggest searching through the codebase for the title text, or perhaps in a db dump file.

After that, you can either update it, or add some code for your own HTML <title> logic.


hook_node_presave() fires twice when adding a new node

Just in case anybody else experiences the same strange problem. In my case the reason was module CER (Corresponding Entity References) 7.x-3.0-alpha7. For any reason after a complete uninstall and clean reinstall hook_node_presave() now works fine with entity referenced fields.


Yes, you can use the Libraries API for this.  The docs explain all of this fairly well.   This is best for things that change infrequently.

For my custom Javascript libraries (which I work on continuously), I make module with an instance of hook_library

function mymodule_util_library ()
{
    $path = drupal_get_path("module", "mymodule_util");

    $libraries = array();

    $libraries["mymodule_util"] = array(
        "title" => "MyModule Javascript Utilities",
        "version" => "0.0",
        "js" => array(
            $path . '/UTIL.js' => array(),
            $path . '/UTIL.HTML5.js' => array(),
            $path . '/UTIL.COLOR.js' => array(),
            $path . '/UTIL.MATH.js' => array(),
        ),

        'weight' => -10,
    );

    return $libraries;
}

Put the module in "site/all/modules" so all of your sites can see it, then enable it on the sites you need.

Then, wherever you need these JS libraries, you use drupal_add_library

drupal_add_library("mymodule_util", "mymodule_util", $every_page);

Typically, this is in a hook_block_view or a preprocess function.


It's pretty difficult to help you here. Are you trying to make your radio buttons inline?

If you are using Bootstrap theme with everything else working right, according to: W3Schools you should be able to just name it class="radio-inline" and then target .radio-inline class in CSS with what you are trying to achieve.


Feeds import - Skip importing item based on some condition

You can do this using hook_feeds_presave to check the data prior to it being saved.

function mymodule_feeds_presave(FeedsSource $source, $entity, $item) {

  // check that this is fired only for the importer being used
  if($source->importer->id=='my_user_importer'){

    // check that the age is over 18
    if($item['age'] < '18'){
      $entity->feeds_item->skip = TRUE;
      drupal_set_message(t("Skipping user who's age is below 18", 'warning');
    }
  }
}


On admin/config/system/mimemail you can tell mimemail to try and use the site's stylesheet when sending an email. You'll have to make sure that your css selectors apply to the elements of your email message or adjust it appropriately.

Alternatively if you want more control over the styles, do not tell mimemail to use the site's stylesheet but instead create a file named mail.css in your theme. Mimemail will automatically use it when sending emails.

Also make sure your theme is set as "Theme to render the emails" under admin/config/system/mailsystem, otherwise you might get the wrong stylesheets when your emails get sent via cron, for example.


Batch API processes next operation if existing operation is taking too much time

I have achieved this using php.

Here is the sample code

$operations[] = array('batch_function_1');
$operations[] = array('batch_function_2');

$batch = array(
  'title' => t('Processing'),
  'operations' => $operations,
  'init_message' => t('Please wait processing is starting.....'),
  'progress_message' => t('Processed @current out of @total.'),
  'error_message' => t('Processing has encountered an error.'),
  'finished' => 'processing_finished',
);

batch_set($batch);

In case of soap I achieved using default_socket_timeout

function batch_function_1 () {
  ini_set("default_socket_timeout", $time);
  try{
    $client = new SoapClient($path_to_wsdl));
  }
  catch(Exception $e) {
    dpm('Timeout'); // echo 'Timeout';
  }
}

And timeout when using exec.

function batch_function_2 () {
  // $command : Which needs to be executed for communicating with server.
  exec("timeout {$time} {$command}", $output);
}

I also tried the set_time_limit which was not working with batch api.


If you are using the overlay module in Drupal 7. Create the main node but use the Node Reference URL widget on the referencing nodes. This will put links on every node view page that behave similar to the Relationships module. If you add Field Collections module to group all the fields, you can get edit in place with overlay popups on the node.

The workflow would be like this. 1. Create a node. 2. The node form only asks for the title of the node. 3. Return to the node with several different parts, each getting their own popup form or if JavaScript is enabled a return destination back to the node after creating or editing.


Very unclear what you did. Read the Views Data Export module's documentation here. It also has a youtube video at the end (for D7 though)


Error when get rest resource : The controller result claims to be providing relevant cache metadata

The problem is, that render() produces metadata which leaks to the outside of the controller. You can try renderPlain() if you don't care about the metadata or see this question how to provide your own render context to catch the metadata and add it to the response:

How to get cache metadata from nested render array when returning response?


You may have to jump through several hoops to get the data from the entity reference field.

  // Query entity types
  $query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'your_content_type');
  $entity_ids = $query->execute();

  // Query paragraph types
  $paragraph = \Drupal::entityQuery('paragraph');
  $paragraph->condition('status', 1);
  $paragraph->condition('type', 'paragraph_type');
  $paragraph_ids = $paragraph->execute();

  // Loop through entity IDs
  $paragraph_output = array();
  foreach($paragraph_ids as $pid){

    // Load each paragraph
    $paragraph = Paragraph::load($pid);

    // Load each entity reference field
    $entity_id = $paragraph->get('field_entity_identifier')->getValue();

    // Get entity parent Node ID
    $parent_node = \Drupal::entityManager()->getStorage('node')->load($parent_id[0]['value']);

    // You'll need to insert another foreach loop here drilling down further into the node that is being referenced.

  }

First you have to loop through the content types. Then you have to look to see if those paragraphs are set and have data. Then you loop through the paragraph types data and get the nodes they reference. Then you have to loop referenced nodes.

It's not an exact solution, but it's how I load data in modules and create my own API endpoints for some fairly heavy frontend javascript applications.


Using Slick Carousel with Views - How to setup a slideshow with View

Use the Slick views module.

  Slick views adds a new display style to views called Slick
  carousel. Similar to how you select HTML List or Unformatted
  List as display styles.


A Multi-step Form to display Database Data at the End

Don't really need the views to make it much complicated. It is all about creating a module. Here is a basic format.

In Drupal, start by creating a simple module. Two files should be created: The .info file and the .module file. For the sake of simplicity call the module multiform.

multiform.info
name = Multi Form
description = Creates a multi-step form.
core = 7.x
package = Custom
version = 7.0

Now that have the .info file, and go create the .module file. The first thing  to add is a menu entry to the page in which the form will show on. Implement hook_menu() inside the module like this:

/**
 * Implements hook_menu().
 */
function multiform_menu() {
  $items['multiform'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Multi Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('multiform_primary_form'),
    'access callback' => TRUE,
  );
  return $items;
}

hook_menu() was implemented with a page callback that renders a form. This function will register a menu item for us to use as our form page.

Add the wrapper form. The reason it need a wrapper form is because the other forms will need to be contained. Without it they are just separate forms. The wrapper form will glue them together. A submit handler must also be created.

    /**
     * Form implementation of primary multiform.
     *
     * @see hook_menu()
     */
    function multiform_primary_form($form, &$form_state) {
      // Check to see if anything has been stored.
      if ($form_state['rebuild']) {
        $form_state['input'] = array();
      }
      if (empty($form_state['storage'])) {
        // No step has been set so start with the first.
        $form_state['storage'] = array(
          'step' => 'multiform_first_form',
        );
      }

      // Return the current form
      $function = $form_state['storage']['step'];
      $form = $function($form, $form_state);
      return $form;
    }

    /**
     * Submit handler for the primary multiform.
     *
     * @see multiform_primary_form().
     */
    function multiform_primary_form_submit($form, &$form_state) {
      $values = $form_state['values'];
      if (isset($values['back']) && $values['op'] == $values['back']) {
        // Moving back in form.
        $step = $form_state['storage']['step'];
        // Call current step submit handler if it exists to unset step form data.
        if (function_exists($step . '_submit')) {
          $function = $step . '_submit';
          $function($form, $form_state);
        }
        // Remove the last saved step so we use it next.
        $last_step = array_pop($form_state['storage']['steps']);
        $form_state['storage']['step'] = $last_step;
      }
      else {
        // Record step.
        $step = $form_state['storage']['step'];
        $form_state['storage']['steps'][] = $step;
        // Call step submit handler if it exists.
        if (function_exists($step . '_submit')) {
          $function = $step . '_submit';
          $function($form, $form_state);
        }
      }
      return;
    }

$form_state['storage'] is used to store which step of the form that is on. Each time this wrapper is called it will call the next step in the sequence of forms. Add first form with a few example fields. Notice that the $form_state['storage']['step'] is storing this function as the default first called.

    /**
     * Menu callback form. First of three.
     */
    function multiform_first_form($form, $form_state) {
      if(!empty($form_state['storage']))
        $values = $form_state['storage'];
      $form['user_info']['username'] = array(
        '#type' => 'textfield',
        '#title' => t('User Name'),
        '#size' => 15,
        '#maxlength' => 15,
        '#default_value' => isset($values['username']) ? $values['username'] : NULL,
        '#description' => t('The user name that will appear to other users. You should not use your real name.'),
        '#required' => TRUE,
      );
      $form['user_info']['first_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First Name'),
        '#size' => 32,
        '#default_value' => isset($values['first_name']) ? $values['first_name'] : NULL,
        '#required' => TRUE,
      );
      $form['user_info']['last_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Last Name'),
        '#size' => 32,
        '#default_value' => isset($values['last_name']) ? $values['last_name'] : NULL,
        '#required' => TRUE,
      );
      $form['user_info']['email'] = array(
        '#type' => 'textfield',
        '#title' => t('E-mail Address'),
        '#size' => 32,
        '#default_value' => isset($values['email']) ? $values['email'] : NULL,
        '#required' => TRUE,
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Next'),
      );
      return $form;
    }

This is a simple form that asks the user for some basic information. $form_state['storage'] is used to store the values of each form. As the form progesses it will populate the content here if returned. Easy enough. Now going to skip the validation hanlder, but that should be easy to code. The important part is the submit handler where we will be storing the user's data. Below is an example of the first submit handler.

    /**
     * Submit handler for the first form.
     *
     * @see multiform_first_form()
     */
    function multiform_first_form_submit($form, &$form_state) {
      $values = $form_state['values'];

      // Save values to the form storage, add the next step function callback
      $form_state['rebuild'] = TRUE;  // This is very important to have!
      $form_state['storage']['username'] = check_plain($form_state['values']['username']);
      $form_state['storage']['first_name'] = htmlspecialchars($form_state['values']['first_name']);
      $form_state['storage']['last_name'] = htmlspecialchars($form_state['values']['last_name']);
      $form_state['storage']['email'] = check_plain($form_state['values']['email']);
      $form_state['storage']['step'] = 'multiform_second_form';
    }

The first thing to do is make sure `$form_state['rebuild']` is set to true. This will allow the next form to be returned for rendering rather than a reload. Any value that collected should be placed in `$form_state['storage']`. The last part is setting the next step. This information will be sent to the wrapper form and will process the next form. In this case it is `multiform_second_form()`. In this form there will add checkboxes. The first part of the function is to make sure if checkboxes have been set previously that they are reset. Take a look.

/**
 * Form that is called second
 */
function multiform_second_form($form, &$form_state) {
  // Make sure the default values for the checkboxes are set correctly.
  if (!empty($form_state['storage'])) {
    $values = $form_state['storage'];
    if (!empty($form_state['storage']['food'])) {
      foreach ($form_state['storage']['food'] as $value) {
        if (!empty($value)) {
          $default_values[] = $value;
        }
      }
      if(empty($default_values)) {
        // Storage and experience are set, but no values were selected.
        $default_values = array();
      }
    }
    else {
      // Storage was set, but experience wasn't.
      $default_values = array();
    }
  }
  else {
    // Storage is not set.
    $default_values = array();
  }

  // Set options
  $checkboxes = array(
    1 => 'Pizza',
    2 => 'Hot Wings',
    3 => 'Subs',
    4 => 'Salads',
    5 => 'Garlic Bread',
    6 => 'Pasta',
    7 => 'Cake',
    8 => 'Ice Cream',
  );

  $form['additional'] = array(
    '#type' => 'fieldset',
    '#title' => t('Additional Information'),
    '#collapsible' => FALSE,
  );
  $form['additional']['food'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Food you like'),
    '#options' => $checkboxes,
    '#default_value' => $default_values,
  );
  $form['additional']['company'] = array(
    '#type' => 'textfield',
    '#title' => t('Company'),
    '#size' => 32,
    '#default_value' => isset($values['company']) ? $values['company'] : NULL,
    '#required' => TRUE,
  );
  $form['additional']['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Additional Information'),
    '#description' => t('Please provide information about your job'),
    '#size' => 32,
    '#default_value' => isset($values['message']) ? $values['message'] : NULL,
  );
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('multiform_second_form_submit'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Next'),
  );
  return $form;
}

The first part may seem confusing, but just gathering what the user has picked before (in case they went to another portion of the form and came back here). Here doing the same thing as the other form, but now with two submit forms. One will take to the next form and one to the previous form. See how the submit handler handles this:

/**
 * Submit handler for the second step.
 *
 * @see multiform_second_form_start()
 */
function multiform_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;
  if (isset($values['back']) && $values['op'] == $values['back']) {
    $input = $form_state['input'];
    // The user clicked the back button, save values that were input
    if (isset($input['food'])) {
      $form_state['storage']['food'] = $input['food'];
    }
    if (isset($input['company'])) {
      $form_state['storage']['company'] = htmlspecialchars($input['company']);
    }
    if (isset($input['message'])) {
      $form_state['storage']['message'] = htmlspecialchars($input['message']);
    }
    $form_state['storage']['step'] = 'multiform_first_form';
  }
  else {
    $form_state['storage']['food'] = $values['food'];
    $form_state['storage']['company'] = htmlspecialchars($values['company']);
    $form_state['storage']['message'] = htmlspecialchars($values['message']);
    $form_state['storage']['step'] = 'multiform_third_form';
  }
}

The submit handler checks to see what button was pushed. If the back button was pushed it will set the step back to the previous form, if not it will set the step to the next and final form (at least for this form). Make the last form a nice and simple terms of use with a finished button.

/**
 * Form that is called third
 */
function multiform_third_form(&$form, &$form_state) {
  $form['terms'] = array(
    '#type' => 'fieldset',
    '#title' => t('Terms of Use'),
  );
  $form['terms']['terms_text'] = array(
    '#type' => 'textarea',
    '#title' => t('Terms of Use'),
    '#default_value' => t('I agree to the terms of use'),
    '#disabled' => TRUE,
    '#resizable' => FALSE,
  );
  $form['terms']['terms_checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => t('I agree to the terms of use'),
    '#required' => TRUE,
  );
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('multiform_third_form_submit'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

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

  return $form;
}

Simple like the others, this last form just collects some more information. The storage of information, creation of users, etc can be placed in this form's submit handler.

/**
 * Submit handler for the third step.
 *
 * @see multiform_third_form()
 */
function multiform_third_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;

  if (isset($values['back']) && $values['op'] == $values['back']) {
    // The user pushed the back button. Clear out the terms checkbox.
    $form_state['storage']['terms_checkbox'] = NULL;
    $form_state['storage']['step'] = 'multiform_second_form';
  }
  else {
    $form_state['storage']['terms_checkbox'] = htmlspecialchars($values['terms_checkbox']);
    $form_state['storage']['step'] = 'multiform_form_complete';
  }
}

Done! Well, maybe. Notice the last part, calling another form. This is just to get the user to a new page and say "

  You have completed the form

". You could redirect to a new page or anything else you want. Here is the code for multiform_form_complete().

/**
 * The complete form (Thank you page) for parent form templates.
 */
function multiform_form_complete($form, &$form_state) {
  $form['message'] = array(
    '#markup' =>  t('Thank you for submitting the form!'),
  );
  return $form;
}

Please have a try with this module. Modify it according to requirements. Let me know if any questions or comments about this process. It is rather long so didn't get much time to explain every detail!

Get more about multi-step form from the Drupal support here.
https://www.drupal.org/node/717750


Filter price according to Maximum Price of Product

In view, add sort criteria for price filter i.e. Sort descending.


wget or curl executables not found. Curl activated but not working

The problem was with the php.exe path in drush.bat

The solution is to properly edit it. In my case ( I use xampp ) here is the path:

@echo off
REM See http://drupal.org/node/506448 for more information.
@c:\xampp\php\php.exe "%~dp0drush.php" %*


Add content from one content type into another content type

You can achieve this using reference module

Install this module, enable the references and node reference checkbox in the Module menu.

Create the people and book content type with the respective field

In Book content type, Add the People name field, and choose the node reference , then it will the show all the content types.

Select the People content type, set the widget types as select list.

Then create a content in Book, People Name field will show the people title as options in select list..

DO this thing, Please ask me if you have any queries.

Before that: Create some contents in People content type.


Add a class to a field based on the page regions

A quick look shows that the content region is wrapped in a class derived from that $columns variable, getting it from this function...

/**
 * Returns the correct span class for a region
 */
function _bootstrap_content_span($columns = 1) {
  $class = FALSE;

  switch($columns) {
    case 1:
      $class = 'span12';
      break;
    case 2:
      $class = 'span9';
      break;
    case 3:
      $class = 'span6';
      break;
  }

  return $class;
}

...so you should be able to use the cascading features of CSS to theme your field, eg...

.span12 .your-field-stuff {
  /* widescreen */
}

.span9 .your-field-stuff {
  /* one sidebar */
}

.span6 .your-field-stuff {
  /* two sidebars */
}


If you do

drush vget theme_THEMENAME_settings

it will give you all nested variables but nested variables  don't work

drush vget theme_THEMENAME_settings.toggle_name
drush vget theme_THEMENAME_settings:toggle_name

so the only way I found to get nested variables is with the use of grep

so for my theme I would do something like this

drush vget theme_THEMENAME_settings | grep toggle_name:

or do further processing using cut to get just the value of this variable

drush vget theme_THEMENAME_settings | grep toggle_name: | cut -f2- -d:

where theme_THEMENAME_settings is my variable and toggle_name is the nested variable name


A much much easier way to do this is leave it at the default style and use CSS to replace it with an image. That is how it is done 9 times out of 10.

Now onto the question at hand, Drupal automatically adds certain classes based on the form type. The only way to remove the default classes is to override the THEME_button function and do it there, for more information see https://api.drupal.org/api/drupal/includes%21form.inc/function/theme_button/6


Creating a thumbnail Navigation for a Flexslider

Install Flexslider module
If you need to display images as a view, select "slider w/thumbnail controlnav pattern" option set in Flexslider display mode settings.
If you displays images a multi-valued image field, select "slider w/thumbnail controlnav pattern" for the field in Manage display tab.

Please note that controlNav pattern (you mentioned) is not the same as thumbnail slider.


How can I style fields in custom content type

The body and title have no prefix field_, this should work:

{{ node.body.value }}
{{ node.title.value }}

But is not the preferred way to style the fields on the page level. If you access the field values in the database, which you basically do when you access the node object, you get the raw value, only escaped by twig for security reasons. Without the formatting, that is integrated into drupal for each field type, and that you can easily extend with additional modules.

To style the fields of the custom content type go to:

admin/structure/types/manage/mycontenttype/display

If you can't find all the options you need for your fields in the ui, you can make a copy of the field twig and apply the changes there.

field--field-myfield.html.twig


Programatically change exposed filter value based on another exposed filter

You don't have access to your filter options inside hook_views_pre_view.

$filters = $view->display_handler->getOption('filters');

give only informations about the filter something like:

 "field_country_target_id" => array:20 [▼
    "id" => "field_country_target_id"
    "table" => "node__field_country"
    "field" => "field_country_target_id"
    "relationship" => "none"
    "group_type" => "group"
    "admin_label" => ""
    "operator" => "or"
    "value" => []
    "group" => 1
    "exposed" => true
    "expose" => array:13 [▶]
    "is_grouped" => false
    "group_info" => array:10 [▶]
    "reduce_duplicates" => false
    "type" => "select"
    "limit" => true
    "vid" => "countries"
    "hierarchy" => false
    "error_message" => true
    "plugin_id" => "taxonomy_index_tid"
  ]

To get the selected filter values with:

$filters_selected = $view->getExposedInput();

Even you get the filter options you can't alter it because exposed filters are form inputs.
So i thing the best way to achieve this is by using hook_form_FORM_ID_alter like the following.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODUOLE_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Here is options of your country filter
  // Note that they key is FIELD_NAME_target_id
  // Change the FIELD_NAME with you field name
  $countries = $form['field_country_target_id']['#options'];
  // Get the city options the same way .
  /**
   * TODO: To alter options array change $form['field_country_target_id']['#options'] not the $countries
   */
}


Have a look at the Easychart module, which has an official release for Drupal 8 (also for Drupal 7).

It is a graphical user interface, using the Highcharts javascript library as its charting engine (which may require a commercial license though). It claims to support every Highcharts chart-type and option.

Some more details about this module:

It defines a new content type (= Chart) used to add charts to your site.
It creates a chart widget that can be used in your own content types.
It integrates with the WYSIWYG module and provides an editor button to add charts to your WYSIWYG content (CKeditor and TinyMCE are supported).
It provides an intuitive interface to configure charts through the Easychart plugin.
It supports pasting of CSV data to create charts from it.
overheid.vlaanderen.be contains some real world examples of a Drupal website (not yet D8 though) with some charts created with Easycharts (ignore the text on that page if you're not familiar with this language, just concentrate on the charts).

Resources:

Module documentation.
Video demonstration.


How to use same database for two website but different panel?

You should start from https://www.drupal.org/docs/8/multisite
Drupal supports multisite structure out of the box. You don't need Domain Access module to reach it.
You may share some db tables among your websites, e. g. content but keep settings (Views, display settings unique). It depends of your purpose. Also you may have shared or unique modules and themes.
The idea is that you specify the list of the sites in sites.php and have several subfulders under /sites folder. At least it worked with Drupal 7. I'm sure there is no drastic charge with Drupal 8.
But be careful with cache. Mind which caches you want to keep shared or unique.


You need to understand that the default tab is not used for anything but the title and the weight of it. For an example, check node/%node/view in node_menu. Also check how node/%node is not a tab and yet when you are on example.com/node/1 you see the View because it's the default.

So. Since Drupal already provides a page on taxonomy/term/% all you need to add is a dummy Views display contents irrelevant, path should be taxonomy/term/%/does_not_matter_what with the title 'Overview' and a nice, negative weight and "default menu tab". All other displays are going to be "menu tabs" plain and these can get paths like taxonomy/term/%/travel.

You can play the same game with a Views display of your own instead of a Drupal provided page if you set that display as a page and the dummy as a children.

To summarize

Have a page, a Views display or a Drupal page at foo/bar.
Add a display at foo/bar/dummy with the title of the default tab and set it as type default tab.
Now add any number of foo/bar/baz displays with the relevant titles as a normal tab.


Install entitycache - it will load the nodes quickly from a persistent cache ( e.g memcache, but db ok )
Use EntityFieldQuery to fetch the relevant nodes.

e.g:

  // Get published articles created in last 7 days.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'article')
        ->propertyCondition('status', 1)
        ->propertyCondition('created', strtotime('-7 days', REQUEST_TIME), '>');
  $result = $query->execute();
  if(!empty($result['node'])){
    // These will be loaded from entitycache
    $nodes = node_load_multiple(array_keys($result['node']));
    // Process result nodes
    foreach($nodes as $node){
      // Do stuff
    }
  }


How to display batch progression with default theme of my site?

In fact, my question was irrelevant.
It appears that I ran my tests of my batch using a user with administrator role. Hence the theme (Seven) used during the execution.
I checked that using another user (not being an administrator) and it was the default theme    of my site that was used.
By the way, I got the opportunity of some interesting readings. Thanks!


Why so many "page not found" for statistics.php?

If file exists, but Drupal still captures calls to it, it may mean one of few things:

Obviously this happens if filename is misspelled in one place (request or filesystem) but not the other (or misspelled differently in both).
As above, sometimes this happens when paths are (slightly) different.
Path you see in your address bar and path your server use to test for file existence are not the same thing. May look the same, but may not, depends on your .htaccess, nginx.conf or whatever you use to control that.
Language prefixes may break things. If file /sites/default/files/example.jpg exists, server may fail to find en/sites/default/files/example.jpg. If that's the case, and for any reason you can't fix broken code, you can try setup like this in your htaccess:

RewriteCond %{REQUEST_FILENAME} ^(en|de|fr)/(.*)$ [NC]
RewriteCond %2 -f
RewriteRule ^(en|de|fr)/(.*)$ $2 [NC,QSA,L]

Notice, I didn't test it. OP preferred to use %{DOCUMENT_ROOT}%{REQUEST_URI} instead of %{REQUEST_FILENAME} to deal with the potential dependencies on the environment/timing etc - that are implementation details beyond the scope of this site, I believe. The logic behind it is, line by line:

Test if request filename contains one of the specified prefixes (should match your site's languages.
Test if file without prefix (second regex group) is there, and really is a file.
If so, rewrite request to remove language prefix.

Apply this logic and you should be good. Actual implementation may vary, but logic you want is just that.


In order to use the "node reference" field in Drupal 7, you need the References module.


Could be that you have private file setting turned on and have not given permission to authenticated users to see an uploaded field.

But the commenters above are correct, there are literally a dozen or more ways a field may not display an image. A few that come to mind:

Images styles aren't writeable
A preprocess function has a weird permission it's checking
.htaccess or server settings is screwing up the image headers
the path is getting rewritten because of a path alias
Some access module is being wonky
The access permissions are out of date and need to be flushed
You have a field-level access module preventing authenticated users from seeing the image field
You are using some display module that is tweaking your template or display mode based on permissions
The views module is tweaking your field availability
etc


Programmatically submit form / save all nodes

I don't think trying to fake form submissions is a good idea - there is a lot that goes on behind the scenes, and it is easy to get something wrong.

I would suggest instead you implement a script similar to the one you pointed out in Load and Save nodes with script? in which you actually set the missing values to the empty data you require. In that script, after the node_load (and before the node_save) you could do something like:

$empty_value = array(
  'value' => ''
);
$node->field_my_custom_field[$node->language] = array(
  0 => $empty_value
);

You would need to do this for each field that needs fixing. The value you need for $empty_value will depend on the field type. You could work it out dynamically by calling field_info_field ;  however as your script is a one-off, it's simpler to just set the right value for each field. To know what the right empty value should be, just create a node with the right empty value and then inspect it (eg. using var_dump, dpm, etc.)


In case anyone is experiencing the same problem:

1) Go to each display's Page Settings.
2) Set the Path $path/week, $path/month, etc., where $path the respective path you have in the month display.
3) Set the Menu Type in Menu to Menu Tab.

Save view and clear caches.


Hide page title if the image field has a value

This method works for me. (Thanks to kim.kennof on Slack for the assistance.)

In my THEME.theme file:

function THEME_preprocess_page_title(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if ($node instanceof \Drupal\node\Entity\Node) {
      $variables['node'] = $node;
    }
  }
}

Then in page-title.html.twig:

{% if node.field_image is empty %}
  {% if title %}
    <h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
  {% endif %}
{% endif %}


Injecting configuration into mock config object

Your mock of the Config object needs to also have a ::get method and return the appropriate value using your array. The core UnitTestCase class provides ::getConfigFactoryStub(array $configs), which does all of this automatically.
In your setup, create the config factory like this:
$this->configFactory = $this->getConfigFactoryStub([
  'mymodule.job' => ['bucketName' => 'test_bucket'],
]);

Unfortunately, the mocked config does not quite work like a real config object; namely, it doesn't accept dotted keys but only top-level keys. The following will not work:
$this->configFactory = $this->getConfigFactoryStub([
  'mymodule.settings' => [
    'key' => [
      'subkey' => [
        'subsubkey' => 'value',
      ],
    ],
  ],
]);
$this->container = new ContainerBuilder();
$this->container->set('config.factory', $this->configFactory);
\Drupal::setContainer($this->container);

\Drupal::config('mymodule.settings')->get('key.subkey.subsubkey');

This bug report shows a workaround: https://www.drupal.org/node/2862248
Update: The above problem was fixed in Drupal 8.5.0, so the workaround is no longer needed.


Formatting looks OK in input field using CKEditor but does not appear on page when published

If CKEditor is applying the styles correctly but the display of these styles is not showing up after a save, I think you may need to check out the 'Text format' you're using for that CKEditor profile.  It should appear directly under the CKEditor in a drop-down.

After you see which text format you're using, check the configurations of that particular text format here: <your site>/admin/config/content/formats.

Make sure, when you check the settings, that the 'Limit allowed HTML tags' checkbox isn't checked, which may not allow certain html tags to be displayed.  Look through all the options there and make sure there isn't something else that could be messing up your display.

Let us know if text formats end up being the issue.


Drupal 7 Query database and display results same page in custom module template

I got it.

    $form_state['storage']['results'] = $results;
    $form_state["rebuild"] = TRUE;

(I do not know whether this method is correct.)

Modified code.

custom_search.module

<?php
function custom_search_menu() {
    $item['customsearch'] = array(
            'title'         => t('Form and Result'),
            'page callback' => 'custom_search_callback',
            'access arguments' => array('access content'),
            'type'          => MENU_CALLBACK,
    );
    return $item;
}
function custom_search_theme() {
    $path = drupal_get_path('module', 'custom_search');
    $rtn = array(
            'custom_search_template' => array(
                    'path' => $path,
                    'template' => 'node--customsearch',
            ),
    );
    return $rtn;
}

function custom_search_form($form, &$form_state) {
    $form = array();

    $form['my_checkbox']=array(
            '#type'=>'checkboxes',
            '#title'=>t('checkbox'),
            '#options'=>array(
                    '1'=>t('option1'),
                    '2'=>t('option2')
            ),
    );

    $form['submit']=array(
            '#type'=>'submit',
            '#value'=>t('Submit')
    );
    if(isset($form_state['storage']['results']))
    {
            $form['results'] = array
            (
                    //'#value' => array('results' => $form_state['storage']['results']),
                    '#value' => $form_state['storage']['results'],
            );
    }

    return $form;
}

function custom_search_callback() {
    return theme('custom_search_template');
    //return theme('custom_search_template',array('results' => $results));
}

function custom_search_form_submit($form_id, &$form_state) {
    $options = $form_state['input']['my_checkbox'];
    //external database query use input options
    $results[] = array('1','2','3'); //sample results
    $results[] = array('2','3','4'); //sample results
    $form_state['storage']['results'] = $results;
    $form_state["rebuild"] = TRUE;

}

node--customsearch.tpl.php

        <?php $form = drupal_get_form('custom_search_form') ?>
        <form role="form" id='<?php echo $form['#id'] ?>'
                            action="<?php echo $form['#action'] ?>"
                            method="<?php echo $form['#method'] ?>">

            <?php echo drupal_render($form['my_checkbox']) ?>
            <?php echo drupal_render($form['form_id']);?>
            <?php echo drupal_render($form['form_build_id']);?>
            <?php echo drupal_render($form['form_token']);?>
            <?php echo drupal_render($form['submit']); ?>

        </form>
<?php
?>

results

      <!— I want results here —>
      <?php
      if(isset($form['results']['#value'])){
        $results = $form['results']['#value'];
        foreach($results as $row) {
           echo "
";
           echo $row[0];
           echo "
";
        }
      }
      ?>


How to get data from previous step in Drupal commerce checkout process

I have found solution.

global $user;
$order = commerce_cart_order_load($user->uid);
$line_items_ids = array();

// get all line items IDs
foreach($order->commerce_line_items as $line_item){
  $line_items_ids[] = $line_item["line_item_id"];
}

// load only "shipping" line items
$shipping_line_items = commerce_line_item_load_multiple(
  $line_items_ids,
  array('type' => 'shipping'),
  FALSE
);

I haven't found cleaner way how to do this. Hope it helps somebody. I still would be glad if anyone knows how to do this better.


Search API view doesn't display placed block

Database Search Default module expects the page and article content types that exist with the Standard Drupal install. You should be able to recreate these content types (and then later delete them) if you want to install that module. You should create Page|page, Article|article and keep both with the default body field. I think that'll be enough to let you install the Database Search Default module and see the configuration. You'll probably want to remove the configuration for page and article from the search configuration before you delete the content types.

If you don't choose to expose your form in block than you cannot place the form as a block on a page. If you're search results view is a block then I believe choosing to expose the form as a block will not work at all. If you want to expose the view as a block, you'll want to be sure that "Exposed form in block: No." Alternatively, if you're view is a page and you want your form to be a block, "Exposed form in block: Yes" and make sure Ajax is not enabled. (Afaik, Exposed form in block and ajax are not compatible at this time.


Uppercase module names - what could go wrong, technically?

Update functions, for example, go wrong: The regular expression that looks for them only works if the module name is lowercase only.

I don't remember exactly how it fails, but I used to have a case once where someone wrote a module that had uppercase characters and it wasn't possible to have update functions.

That's the only thing that I'm aware of.


As said in the comment: If you want to give user access to unpublished content you can have a look at view_unpublished

You can also try to use this in combination with the 'Content: Published or admin' filter, but I didn't have a change to try it.

A filter like you're describing can be a good addition to views, consider creating an issue for it.


That code needs to be changed for the following reasons.
In PHP, $entity->getEntityType() == ('Deadline' || 'Message') doesn't check that $entity->getEntityType() returns either 'Deadline' or 'Message'. Actually, the code you wrote is equivalent to the following one.
if ($entity->getEntityType() == TRUE) {
  createNotification($entity);
}

getEntityType() doesn't return the ID of the type of the entity, but its definition. The method that returns the ID of the type of the entity is getEntityTypeId().
It doesn't make sense to check the value returned from $entity->getEntityTypeId() in hook_ENTITY_TYPE_create() because hook_ENTITY_TYPE_create() is invoked only for the ENTITY_TYPE entities. (You are also supposed to implement hook_ENTITY_TYPE_create() by replacing ENTITY_TYPE with the entity type, for example node for the Node entity, or user for the User entity.)
EntityInterface is an interface, not a class; as such, it's never used to call a method, even if it's statically called as in the code you are using.
The correct code is similar to the following one. I assume that ost_hook is the module machine name, notification is entity type, and Notification is the class implementing the entity you are trying to create.
function ost_hook_entity_create(EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'Deadline' || $entity->getEntityTypeId() == 'Message') {
    $new_entity = Notification::create([
      'title' => $entity->label() . " notification",
      'field_content' => $entity->toLink()
    ]);
    $new_entity->save();
  }
}

Alternatively, you could use the following code.
function ost_hook_entity_create(EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'Deadline' || $entity->getEntityTypeId() == 'Message') {
    $new_entity = \Drupal::entityTypeManager()->getStorage('notification')->create([
      'title' => $entity->label() . " notification",
      'field_content' => $entity->toLink()
    ]);
    $new_entity->save();
  }
}

If the file containing the hook is ost.module (as I suspect), the function implementing the hook is ost_entity_create(), not ost_hook_entity_create().
I used hook_entity_create() because the code needs to be executed for two different entity types. Using hook_ENTITY_TYPE_create(), I should  implement two hooks. (I assume that dealine and message are the entity machine names, in the same way the machine name for the Node entity is node.)
function ost_deadline_create(EntityInterface $entity) {
  $new_entity = \Drupal::entityTypeManager()->getStorage('notification')->create([
    'title' => $entity->label() . " notification",
    'field_content' => $entity->toLink()
  ]);
  $new_entity->save();
}

function ost_message_create(EntityInterface $entity) {
  $new_entity = \Drupal::entityTypeManager()->getStorage('notification')->create([
    'title' => $entity->label() . " notification",
    'field_content' => $entity->toLink()
  ]);
  $new_entity->save();
}

As side note, functions implemented from a module should always be prefixed by the module machine name. A module shouldn't have a createNotification() function, which should instead be called ost_create_notification() (assuming that ost is the module machine name).


Take a look at this answer, I believe it goes into great detail about enabling SSL support on pages and image assets for Drupal 7;

How to force drupal 7 to load HTTPS assets?

Also if your still having problems, take a look at this documentation on drupal.org;

https://www.drupal.org/https-information

Hope that helps!


How to call up the argument passed to the View?

I don't think it's possible with HTML, but 'No result case' allows you to use PHP, so arg(x) should work, x being the zero based position of your argument in the URL.


How to Modify Drupal 7 Bootstrap Theme Title?

This thing is come under $head_title variable on html.tpl.php.
So for changing this you need to override template_preprocess_html
where replace statement
$variables['head_title'] = implode(' | ', $head_title);
with
$variables['head_title'] = implode(' - ', $head_title);
I am assuming you have enough idea about overriding of templates.


Profile2 and profile fields by user role

I've done with hook_process_page() and removed the variable secondary_local_tasks before rendering to the template if the logged-in user is role C. No need additional module.

function mymodule_process_page(&$vars, $hooks){
    global $user;
    if(array_key_exists(6, $user->roles) && arg(0) == 'user' && arg(2) == 'edit'){
        # if user role C, hide profile tab
        $vars['tabs']['#secondary'] = array();
        if(isset($vars['secondary_local_tasks'])){
            $vars['secondary_local_tasks'] = array();
        }
    }
}

I have also tried this from hook_preprocess_page(), but it did not work on the sky theme.
Related question is here : Menu local tasks and hook preprocess


Suddenly I can't use the "Media" file uploader in Full HTML CKeditor edit screen but can do in Filtered HTML edit screen

Solved! For some reason (most probably a bug) the Media module button wasn't added automatically to the Full toolbar even after I check-marked "Plugin for inserting images from Drupal media module" in "Editor appearance" at the desired profile's settings page.
So, What I did was after I check-marked "Plugin for inserting images from Drupal media module" I just went on to add the button manually from "Available buttons" to "Current toolbar" (see img), saved, cleared cache, and Vwalla - it worked again!


The only way I've found to do this so far is to alter the ctools jumpMenu behaviour with the following JS. This is probably a lot more code than I need, but it seems to do the job. Better answers are appreciated.

JS

// place this outside your .ready() function
Drupal.behaviors.CToolsJumpMenu = {
   attach: function(context) {
     $('.ctools-jump-menu-hide:not(.ctools-jump-menu-processed)')
       .addClass('ctools-jump-menu-processed')
       .hide();

     $('.ctools-jump-menu-change:not(.ctools-jump-menu-processed)')
       .addClass('ctools-jump-menu-processed')
       .change(function() {
         var loc = $(this).val();
         if (loc) {
           location.href = loc;
         }
         return false;
       });

     $('.ctools-jump-menu-button:not(.ctools-jump-menu-processed)')
       .addClass('ctools-jump-menu-processed')
       .click(function() {
         // Instead of submitting the form, just perform the redirect.

         // Find our sibling value.
         var $select = $(this).parents('form').find('.ctools-jump-menu-select');
         var loc = $select.val();
         if (loc) {
          // console.log(loc.slice(loc.indexOf('::') +2) );
           // location.href = loc.slice(loc.indexOf('::') +2);
           window.open(loc));
         }
         return false;
       });
   }
 }

Source


How to check if field is empty and hide a css class in render array?

I achieved this by the code below;

    function template_preprocess_node__event(&$variables, $hook) {
    $node = $variables['node'];
    $custom_tab = field_get_items('node', $variables['node'],    'field_override_group_label')
    if (! isset($custom_tab[0]['safe_value'])){
        drupal_add_css(drupal_get_path('theme', 'template some ') . "/css/customtab.css");
    }
    // jQuery UI accordion lib
    drupal_add_library('system', 'ui.accordion');
}

In customtab.css file, I add a css to hide the class.
I think this might have impact on the general site performance.


Use Twig to render HTML email body for SwiftMailer

Sure, that's possible. It works exactly as if you would render something for the page.

After preparing your render array like you always do, all you need to do is call the renderPlain() method of the renderer service, that gives you a string (Actually, a Markup object containing a string).

contact_mail() does exactly that, the relevant part:

$build = entity_view($contact_message, 'mail');
$message['body'][] = \Drupal::service('renderer')->renderPlain($build);

PS: The fact it is a Markup object is important, do not try to cast it to a string.


Execute user_save() after the form submission handler

In your code, your submit handler ( mymodule_user_register_submit ) and actual function name ( custom_user_form_submit ) are different.

Also, your submit handler is using

$form_state['field_magentopass']

instead of

$form_state['values']['field_magentopass']...

It should be something like

/**
 * Implements hook_form_FORM_ID_alter
 * User register form id: user_register_form
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  drupal_set_message("Form ID is : " . $form_id);
  array_unshift($form['#submit'], 'mymodule_user_register_submit');

}

function mymodule_user_register_submit(&$form, &$form_state) {
  $form_state['values']['field_magentopass'][LANGUAGE_NONE][0]['value'] = $form_state['values']['pass'];
}

UPDATE: OP changed their question to use matching function names. Apparently new $user is saved, but field_magentopass wasn't updated.

Lastly, an alternative approach, based on form_set_value and the #validate handler

/**
 * Implements hook_form_FORM_ID_alter
 * User register form id: user_register_form
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  drupal_set_message("Form ID is : " . $form_id);
  $form['#validate'][] = 'mymodule_user_register_validate';

}

function mymodule_user_register_validate($form, &$form_state){
  $form['field_magentopass']['#parents'] = array('field_magentopass');
  form_set_value($form['field_magentopass'], array(LANGUAGE_NONE => array(0 => array('value' => $form_state['values']['pass']))), $form_state);
}


Taxonomy term option is missing in view category

All you have to do is to choose "Taxonomy terms" under VIEW SETTINGS when you add a new view on MYSITE/admin/structure/views/add.


Orders have a removeItem method defined on their interface. You just need to pass the loaded order item to that method, and then delete the orderitem.

/**
 * Removes an order item.
 *
 * @param \Drupal\commerce_order\Entity\OrderItemInterface $order_item
 *   The order item.
 *
 * @return $this
 */
public function removeItem(OrderItemInterface $order_item);


"Uncaught ReflectionException: Class DOMDocument does not exist" error

DOMDocument is included in the extension php-xml.  To install it on ubuntu, run:

sudo apt-get install php-xml


As long as core is not modified in any way, there should be no risks of updating it straight from 7.14 to 7.31. It will apply all database updates from each version in between. There's literally no difference in doing it one version at a time compared to doing it straight to 7.31.

But as always, test it in a development environment before doing it in production and always make backups.


Issue using Exposed filters along with contextual filters in views

Sorry! I should have looked at the issue queue. There is already an issue logged for this. Here is the link to the issue https://www.drupal.org/node/2179169

The issue got resolved when I applied the patch provided by Jim Keller in the issue link
https://www.drupal.org/files/issues/better_exposed_filters-fix_exposed_block_link_path-2179169-1.patch


To default RSS feed page goes for example every node with promote to front page flag set to true.

You can use Views to create your own, highly configurable RSS feeds. If you want even more control you can use this module https://drupal.org/project/views_rss.

You can override default RSS feed with a Views one too


Take a look at Drupal Instant Search, or Finder. Even if it isn't exactly what you want, it should be a good starting point.

Drupal Instant Search:

  It works as follows: The url for the instant is at /instant The user
  types his search word, once he finishes typing (javascript keyup) the
  module automatically submits the search word and returns the search
  results. The search results are displayed at the same page of the
  instant search.

  Instant search is also integrated with Top searches module. if Top
  searches module exists, the instant search auto-completes top search
  words.

Finder:

CHECK MODULE FIRST DUE TO THIS WARNING:

  This module is unsupported due to a security issue the maintainer
  didn’t fix.


Many

Drupalise Me Feature introduction

Phase 2 feature slides.

Code Karate Feature Series Video

Acquia Video Series

As far my experience features is not just about how to do it, but also how well you do it. Doing it in wrong way can make the development nightmare. Once you get acquinted with features, I would recommend you to look for features best practices. Do's and Don'ts for feature module.


how to retrieve field collection data associated with a node

I believe you are looking for field_collection_item_load or field_collection_item_load_multiple function both are in field_collection.module


Table not creating while installing a custom module in Drupal 7

I can see 2 problems with in your code:

You should not call drupal_install_schema() from hook_install() in Drupal 7. hook_schema() will be called and the table will be automatically created/dropped on installing/uninstalling. See here: https://drupal.org/node/224333#install-schema
As @Ollie also stated, there's no field type named bigint. You should use int and set its size to big.

Like following:

'amount' => array(
  'description' => t('Amount'),
  'type' => 'int',
  'size' => 'big',
  'unsigned' => TRUE,
  'not null' => TRUE,
),


Hi Sumit check the below query and it not showing any error.

Use Query coder module to create any query in drupal format

Query coder Convert SQL query to Drupal Database abstraction layer code.

$query = db_select('users','u');

$query->join('users_roles', 'r', 'u.uid = r.uid'); // JOIN users_roles with users

$query->fields('u', array('name','uid')) // SELECT the field name from users
    ->condition('r.rid', 5);

$results = $query->execute();
     $rows = array();

foreach($results as $result)
  {

$rows[] = array(
    $result->uid,
    $result->name,
    );

}


Did you modify cron-curl.sh to use the URL for your site? By default, it tries to load http://example.com/cron.php.


Seems you have infinite redirection which causes the page not to load. (stops after x redirects)

It happens on every page (the once that load and the once that don't load) see my screenshot of the network tab to see it in action:


One solution, if you're wanting to force your site to always to use SSL, is to do it at the Apache level by adding this to your .htaccess:

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

That's probably the quickest way. The best way is subjective; your needs might be different depending on priorities (e.g. for performance reasons you might want to force many static pages to HTTP).


Removing prefix for default language breaks all the link

Google into htaccess rules if you have the apache module mod_rewrite on the apache server (if it's an apache server you're using), you can make redirections based on REGEX patterns, so there's a little work for you there....


basics of settings.php and settings.local.php?

Its common to either include a local settings file from settings.php or create a site folder for local development (local.mysite.com) that has a settings file that will be used. In either case, both are gitignored so its only for you. This also avoids the annoying issue when Drupal locks the site folders from being written, causing git errors when pulling or switching branches.


[fixed]Trigger an ajax Submit Form button by clicking on a div

Your code is not triggering an AJAX call, it will just submit the form normally via JavaScript rather than pressing a button, etc. If you want submit the form via AJAX you will need something like:

  var url = $('#form-id').attr('action');
  $.getJSON(url, {
    field1: 'data1',
    field2: 'data2'
  }).done(function(data) {
    console.log(data);
  });

Place this inside $('#rectangle-div').on('click', function () {


The ComplexData plugin does not exist, after upgrade

I read in another post where an OP wrote that Composer didn't put all the /core files in place, so he manually copied the /core directory and all its files and that solved a similar problem he was facing.

I tried that last night, manually copying the Drupal 8.51 /core folder into my local install. It fixed the problem. I then copied the files into production and all is well. Thanks to all who commented.


Override default profile view with profile2's profile fields

I thought Profile2 had an option to override that.

Maybe you could use Global Redirect or Path Redirect to redirect users visiting the account page to the profile page.

Another option could be creating a view for the searches, and then adding the user/profile relationship.


How do I alter the page title after a controller sets the title?

Yes, #title from the controller overrides the title set in the route. There doesn't seem to be another override to override #title.

Though you could try to alter the controller output in a KernelEvents::VIEW with a priority higher than 0 like this:

$result = $event->getControllerResult();
// change the controller output
$event->setControllerResult($result);

Metatag

Working on a project I found out, that the metatag module in default configuration gets the title with the token [current-page:title], which retrieves the title from the route, ignoring #title set in the controller. Most times this would be considered as an unwanted side effect, but in your case you get the title you want from the route title callback in HTML <title> and only have to take care of the page title block, which should be no problem in a preprocess hook.


Take a look at the IMCE module.

It's a powerful upload manager that requires either CKEditor or IMCE Wysiwyg API bridge to work.

It supports per-user upload directories and space quotas, amongst other useful stuff.

As for the XML-RPC, you should take a look at the Services module.

Regardless of the path you take, you will definitely need to add some custom code and, to help with that (Drupal 7 only) take a look at the FileTransfer class. (related question)


How to get the current version of a node?

For those who need it. It is included in the node structure under value:

$node->workbench_moderation['current']->vid


The Ticket module is a good point to start.

  Ticket is a module that provides ticketing and registration for events
  (and more abstractly, entities). Events may have multiple ticket
  types, each with a unique set of requirements and registration fields.


Nice question  you are right  no module for that . but  you can configure it by rules
like
after saving node
add action - sand e-mail userA
on this add conditions according to your need
like  account type userA
I think this is the possible way for that


Infinit loop when I 'print_r' variables like $form_state, $form

You might not like the answer, but it's still true: Don't use print_r() for $form/$form_state, entity or other complex objects. It just doesn't work.

Try kint() from the devel module instead, make sure to install the kint submodule too.


Modify metatag description programmatically Drupal 8

That depends on your theme and its use of $variables in combination with the description meta tag.

A code snippet for Drupal 8 that does what you want for the Bartik Theme would be the following:

function bartik_page_attachments_alter(array &$page) {
  $description = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'description',
      'content' => 'your description content',
    ),
  );
  $page['#attached']['html_head'][] = [$description, 'description'];
}

This was inspired by this post => https://drupal.stackexchange.com/a/134145/57183

Maybe this does solve your problem!


How to edit views twig template to process node information

In Drupal 8 using views-view-fields.html.twig file:

{{ row._entity.field_example.value }}

Trying the preprocess route for the views-view-fields template file:

$node = $vars['row']->_entity;
$field_value = $node->field_example->value;


How to check whether a username already exists?

I guess you can use a simple EntityQuery.

  $ids = \Drupal::entityQuery('user')
        ->condition('name', 'USERNAME_TO_CHECK')
        ->range(0, 1)
        ->execute();
    if(!empty($ids)){
      //then this name already exists
    }


How to sort view by a field that is part of a field collection?

Duplicate of Sort view items by field collection's field value (But it's answer is not accepted yet)

You can use field_collection_views module which it creates a default View of field collection type. Its address is /admin/structure/views/view/field_collection_view and I recommend you clone this View and configure the rest of the options. The Fields section contains a few items that are very helpful, like Host Entity ID, Host Entity Type and ... .


The only way to get the page title of any URL/route would be to actually request the page and see what the title is. The reason is that any module or the theme could alter the title from what it normally would be, like fx metatags module.


Finally found it! In my Views configuration, under the Arguments configuration the incoming Argument was set to use the "Second" argument but the Term Id was the First argument.

I have a different problem now... but I'll post another question.


How to save uploaded image in an content type to picasa?

Picasa Node Album module provides gallery support in the form of
  associating Picasa albums with nodes.

Features

Link any public Picasa album to a node
Thumbnail view with a template you can override
Lightbox2 support already in the default template
Select albums of the current Picasa account with autocomplete
Supported node types configured via admin settings
Define if thumbs should show on teasers and/or page views
Define how many images in the gallery should be displayed on teasers/page views
Define the sizes of thumbnails and images to request from Picasa
Define whether you want an Albums tab on the node or not
Image data results cache with a defined expiration
Restrict what picasa accounts content can come from
Restrict how many albums a user can upload per node


how to change output html of variable $output on file views-view-field--field-image.tpl.php

You kind of answered yourself already.

open the views-view-field--field-image.tpl.php file, look for that  and add what you need.

however, use the file you can find inside your theme folder ( usually named templates or tpl), not inside the view module.

if you can't find it in there, copy it from the view module. In this case clear the cache for drupal to register the new file.

Always and only edit the .tpl of your themes.


How to override the display of a field in a view: is preprocessing possible?

I would suggest implementing the Semantic Views module. This allows you to easily customize the HTML that Views outputs for each level of elements (the entire view, row wrappers and field wrappers) from the UI. It is a bit easier to use and maintain than custom templates and preprocess functions.


Why doesn't "drush --debug en color" show any output?

It seems that your drush installation is broken. So you have to reinstall it again.

The easiest way would be to install Composer and follow the instructions from drush-ops (especially check Windows section). Then check How to configure Drush on Windows 7?

If this is still happening, check your PATH environment variable if it contains the correct directories (maybe you have some non-drush binary within your system list of folders which could cause some conflict).


How to map different entity types as layers with OpenLayers?

So, OpenLayers requires Geofield as a spatial data format, which is better than the Location Module for spatial formats. There's no simple solution to convert the data, so you spatial content will have be updates with Address or Geofield formatted data. I used Views CSV export and Feeds to dump and spit back the data to the right fields. From there, I followed the tutorial here Multiple Layer Maps with OpenLayers creating multiple data overlay views to a build a map based on layers of different views. This let me overlay my users over my other spatial nodes.


It is possible to revert a single item of the component programmatically?

In order to revert, you need to remove a single component from the database, so the configuration from the code can be loaded instead.

So to revert a single rule, load the rule and delete it, e.g.

$rule = rules_config_load("my_rule");
$rule->delete();

This can be placed in hook_update().

Check Add drush rules-revert patch which provides such functionality for the drush command, e.g.

drush rules-revert my_rule

In addition, to revert all rules by not using Features module (which will take much quicker), you can try:

if ($rules = rules_config_load_multiple(FALSE)) {
  foreach($rules as $rule) {
    if ($rule->hasStatus(ENTITY_OVERRIDDEN) && !$rule->hasStatus(ENTITY_FIXED)) {
      $rule->delete();
    }
  }
}

So by deleting the rules from the database, they're loaded from the code.