Assign new role to user after puchasing a product

For Drupal Commerce on Drupal 8, Rules is not complete or integrated. This leaves many such tasks like this for custom development. Fortunately, it's also easier to alter individual parts of the Commerce system thanks to Drupal 8's object oriented architecture. In this case, you'd write a new class called an event subscriber to assign that user role on the "placed" transition - the point at time an order completes checkout or is placed by an administrator. It should then handle assigning the user role to the order owner.

There may be contributed modules available for Rules integration to support individual tasks like this, but it hasn't been a core priority as of yet while we focus on other major feature groups (e.g. shipping, addressbook, recurring billing, etc.).


There is a patch available for this. Please refer the below link

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


Compare a single value entity reference field to a multi-value entity reference field

$Article_Countries = $article->field_article_countries->getString();

This returns a string

->condition('field_user_countries', $Article_Countries, 'IN')

From the docs, condition with IN accepts an array.

So, you need $Article_Countries to be an array of entity IDs. My first thought was $article->field_article_countries->referencedEntities() to get an array of objects, and then foreach them to build an array of IDs, but that's a bit round-the-houses. So I searched for a neater way and found this: http://drupal.stackexchange.com/a/207715/89581 which suggests:

$ids = array_column($entity->field->getValue(), 'target_id');


Using hook_form_alter() to add the "None" value in the select list of a required field

By default, the label for the first default option is automatically set to "- Select -" for a required field and "- None -" for an optional field. To force the #empty_option to also show "- None -" for a required field, assign it with something like:

"#empty_option" => t('- None -'),

This will keep everything else intact and will do exactly what you want. See class Select.


Can be managed by strpos easily. Below code will be in validateForm function

 $email = 'abc.def@mycompany.com';
 if (valid_email_address($email)) {
  if (strpos($email, '@mycompany.com') !== FALSE) {
       // Set form error message
   }
 }


Obtain the total (count) of the contents associated with a nested taxonomy (only in the parent taxonomy)

I tried something similar I think, here's my code but keep in mind it's not perfect.

first get alle the terms

$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$nodes = $node_storage->loadMultiple();
$node_tags = [];
foreach ($nodes as $node) {
  if ($node->hasField('field_terms')) {
    foreach ($node->get('field_terms')->getValue() as $value) {
      array_push($node_tags, $value);
    }
  }
}

after that you count all the terms

foreach ($node_tags as $key) {
  if (isset($count[$key['target_id']])) {
    $count[$key['target_id']]++;
  }
  else {
    $count[$key['target_id']] = 1;
  }
}
arsort($count);

then (and this still needs a lot of work) you search for them

$tags = $terms_storage->loadTree('tid');
$i=0;
foreach ($count as $key => $c) {
  foreach ($tags as $tag){
    if($tag->tid == $key){
     //here you can get the $tag->tid
     //you can get $tag->name
     //time used = $c
    }
  }
  $i++;
}

if you want to get the other terms

foreach ($tags as $tag){
  if(!array_key_exists($tag->tid,$count)){
   //here you get the same info
  }
}


How to get visitors count of a page created using views

Enable the statistics module that comes with core in admin/module. You can start tracking pages once you enable the log settings in admin/config/system/statistics

Once you enable the Setting Enable access log drupal will start tracking all pages. Now follow below process to create a view.

Create a view with base type as access log
Enable aggregation in the other settings
Add Access Log path field and set "Group results together" in aggregation settings next to field settings.
Add one more field access log path and select Aggregation type as count.
Now you can see all paths and number of visits associated with them.
Add filter access log path and provide the path for which you would like to see number of visits.

Find the exported view below.

$view = new view();
$view->name = 'statistics';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'accesslog';
$view->human_name = 'Statistics';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Statistics Custom';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Access log: Path */
$handler->display->display_options['fields']['path']['id'] = 'path';
$handler->display->display_options['fields']['path']['table'] = 'accesslog';
$handler->display->display_options['fields']['path']['field'] = 'path';
/* Field: COUNT(Access log: Path) */
$handler->display->display_options['fields']['path_1']['id'] = 'path_1';
$handler->display->display_options['fields']['path_1']['table'] = 'accesslog';
$handler->display->display_options['fields']['path_1']['field'] = 'path';
$handler->display->display_options['fields']['path_1']['group_type'] = 'count';
$handler->display->display_options['fields']['path_1']['label'] = 'Count';
/* Filter criterion: Access log: Path */
$handler->display->display_options['filters']['path']['id'] = 'path';
$handler->display->display_options['filters']['path']['table'] = 'accesslog';
$handler->display->display_options['filters']['path']['field'] = 'path';
$handler->display->display_options['filters']['path']['value'] = 'admin/config/system/statistics';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'statistics-custom';

That's it :-)

If you would like to display page counter contextually then below code in a custom block will help.

<?php
$path = $_GET['q'];
drupal_set_message($path);
$visits = db_query("SELECT count(*) FROM {accesslog} where path = :path", array(':path' => $path))->fetchField();
echo "Views: " . $visits;
?>


You can set the default-values in your Content-type > Field-settings > More settings and values > Default values, (Now, Relative, No default value) set it to "No default value".


Convert vertical (portrait) picture to horizontal (landscape), filling empty space around with blurred background

I have created custom module called "Blurred". It can be described as "post scale blurred background effect for images".


Views Sort Criteria: Sort by Taxonomy terms

Check out Views Distinct module. Once you enable this module, for every field there will be a setting Views Distinct Settings where you can choose to filter repeats.


Allow multiple taxonomy term values on term listing page

I've found the path taxonomy/term/203+221 (which will yield the nodes tagged with either 203 OR 221) is possible by making a slight change to the Contextual Filter of the taxonomy/term/%tid view (which you should have enabled in Structure > Views > Taxonomy Term.

Expand the Advanced section of the view configuration, click on the first Contextual filter "Content: Has taxonomy term ID (with depth)".

You will see a checkbox that allows multiple values, which is checked by default.

However, to get this working I had to scroll further down to the "Specify validation criteria" section and change the "Filter value type" to "Terms separated by a , or +".

Now you should be able to use multiple term IDs in your URL, combined with a "+", to see all nodes tagged with any of the IDs in the list. You can test out various URL arguments using the Views Auto preview:


How do I include custom CSS files in the styles dropdown?

Have tried going adding the css file via the configuration page?

yoursite.com/admin/config/content/ckeditor/edit/

navigate to the page, edit the target profile and click on the CSS link to expand the configuration pane... you should be able to tell CKeditor what to do from there. I'm not sure if its necessary but you may need to refresh the site's cache before the new files get picked up.
hope this helps.


I'd suggest checking against a permission, rather than an entire role.

In your custom module, add:

function mymodule_permission() {
    return array(
        'view site logo' => array(
            'title' => t('View Site Logo'),
            'description' => t('Allows a user to view the site logo'),
        ),
    );
}

And in your theme's template.php page preprocessor, add:

if(!user_access("view site logo")) {
    $variables['logo'] = "";
}

This way, $logo will not be processed in page.tpl.php for a user without the permission.


How can I get a custom number of posts on the front page without views?

The default front page article count is on the Site Information admin page @ admin/config/system/site-information. For some reason you can't select 16 as a value. If you have drush you can manually set the default_nodes_main value:

drush vset default_nodes_main 16

If you don't have drush you can set its value in the variables table.


How to trigger an Action on an Entity from a button in a Views row (without VBO)?

What you're asking for is perfectly possible using the Rules Link module (no need for VBO). Some details about this module (from its project page):

  Features: ... The links are usually displayed using Views...

  Usages: ... The Rules Link module will create a Views field for each link, which can be hidden, using the visibility conditions ...

However, assuming you're familiar with the basics of Views, it isn't obvious at first about how to actually add such extra column. The clue to get it to work, can be found in this part of the module's README.txt:

  Rules Links link
  will create a Views field for each link, using the title of the link as title
  for the field. So if you have link for nodes with the delete 'Delete node',
  you'll find the Views field under name 'Content: Delete node'.

Example

Below is a list (= Views result) of "All blocked/active users" shown to a user with role Administrator:

User name      Active  Created date        Last login
Hillary.Trump  No      06/18/2016 - 13:45                      Unblock user
Donald.Clinton No      06/18/2016 - 13:42                      Unblock user
Someone.Else   Yes     05/12/2016 - 12:09  09/17/2017 - 11:18
Pierre.Vriens  Yes     03/11/2016 - 21:05  10/06/2017 - 16:04
Dries.Buytaert Yes     11/23/2015 - 10:11  09/17/2017 - 10:38
Anonymous      No

Note the extra column added (to the right), with links labeled Unblock user which are only shown for the blocked users, and not for Anonymous. After using (clicking) that link, for some user with Active=No, the user's status becomes Active (an example of "an action triggered on a user entity", as in your question), and the link is no longer shown for that user. If you wonder how to create such extra column (using Rules Link), refer to my answer to "How to show authorized users a link for relevant Views results using the Rules Link module?". Obviously, transforming such link into a button is just a matter of some (basic) CSS to be applied to that link.


Go to CAPTCHA Points and enable reCaptcha for your form.


I typically do things like this outside of modules, and instead use a drush script.

The script itself, would go something like

Go into maintenance mode
Do an EntityFieldQuery to get my nids.
Loop through each nid, and
Load the node, and make an entity metadata wrapper
Do the search and replace on the fields
Save the node
Exit maintenance mode

Before and after running the script, I usually do a drush sql-dump.  You can even combine all of this into a single script

#!/bin/bash

drush variable-set -y --always-set maintenance_mode 1
drush sql-dump --result-file=~/db/before.sql
drush scr path/to/my/script.php
drush sql-dump --result-file=~/db/after.sql
drush variable-delete -y --exact maintenance_mode

By doing a drush script, you can really ensure that the task runs when you want it to, and you aren't bound by execution time limits.  I also find it easier to debug.

That said, you should just be able to use Pathologic to rewrite the URLs.  Install/enable it, and add it to your text formats, and configure to do the path fixups.


views filter: broken filter - but what's broken about it?

You are looking at Drupal 6 documentation.

You don't need hook_views_handlers() anymore in D7. Instead, you add the file(s) that contains your views handler(s) to your .info file like this:

files[]=ds_regions_handler_filter_view.inc


I would recommend starting with the "Stark" Drupal theme.  It's the minimal theme,  easier to customize.

You are also going to need to read about some basic Drupal concepts.  Views, blocks, page templating.

Your question is far too "big" to be answered in this forum.  You will have to read the documentation at drupal.org


That code has been moved in template_preprocess_username(), which is called before the theme function.

// Set the name to a formatted name that is safe for printing and
// that won't break tables by being too long. Keep an unshortened,
// unsanitized version, in case other preprocess functions want to implement
// their own shortening logic or add markup. If they do so, they must ensure
// that $variables['name'] is safe for printing.
$name = $variables['name_raw'] = format_username($account);
if (drupal_strlen($name) > 20) {
  $name = drupal_substr($name, 0, 15) . '...';
}

If you need to use the full-length name, you should use $variables['name_raw'] in your implementation of theme_username(), remembering that the value has not been passed to any sanitization function.


How to use the Theme Page reactions in context

You need to use a theme preprocess hook to pass the variable to the right zone template. Here's how I added it to my header zone:

function my_theme_preprocess_zone(&$vars) {
    $zone = $vars['zone'];

    if ('header' == $zone) {
        $theme = alpha_get_theme();

        // set via context module
        if (isset($theme->page['section_title'])) {
            $vars['section_title'] = $theme->page['section_title'];
        }
    }
}

Then in your zone--header.tpl.php file

<?php if (isset($section_title)): ?>
<div class="grid-<?php print $columns ?>">

<?= $section_title ?>

<?php endif; ?>


setHandler into views_pre_render OR count results in views_pre_render

Found an alternative solution, by using hook_views_pre_render and $view->attachment_after

$view->attachment_after = array('#markup' => 'Button');


You cannot sort by a global text field in views by default.

This is because global text field values are not populated until the view is being rendered, but the sorting of the view is done in the sql query, which is much before the global text field value exists.

One way to do it would be to add sorting ability with javascript.
Because this would happen on the front end it could work for any fields.
The views tablesorter module does this for drupal 6 table views but I have not yet found the time to make a drupal 7 version.

Another option is to make a custom views field handler that actually includes the data in the sql query or just making a custom sort handler.

For more information on creating handlers install the advanced help module and then go to the advanced help UI and look at the views help (advanced_help/views).


How to get node url/address from entity reference (content type)?

No need to add the <a> tags, because Drupal will automatically create the link.

So just simply do <h2>{{ related_links.entity.toLink }}</h2>

You don't even need the label with .toLink() because Drupal will automatically grab it when generating the link.

The above is suppose to work, but I get an error

  Twig_Sandbox_SecurityError: Calling "toUrl" method on a
  "Drupal\node\Entity\Node" object is not allowed. in
  Drupal\Core\Template\TwigSandboxPolicy->checkMethodAllowed() (line 105
  of
  /home/ubuntu/workspace/drupal-8.5.3/core/themes/bartik/templates/node.html.twig).

There is an issue about this on drupal.org Add $entity->toUrl() and $entity->toLink() methods to whitelist in Twig sandbox policy applying the patch in #30 solved the issue.


Defining functions in a module and calling them from a controller

This is exactly the case when you define a Service:

In your controller you call the service with Dependency injection
In your module you call the static \Drupal::service('..')


Can I expose the signup form through views 2?

This is currently a feature request for the Signup module (originally submitted to that module's issue queue 3 days before this StackExchange post). For the latest progress on this feature, see the issue: http://drupal.org/node/1118448 .


Target EntityBrowser in custom validation constraint

I think this is a limitation of Entity Browser module. Drupal is ultimately using setErrorByName() to add the error to the form and Entity Browser does not provide a name attribute that Drupal can attach it to. So if a name attribute is added somewhere in the entity browser widget Drupal could attach the error. That is, Drupal does only visibly attach the error to (visible) input, select and textareas in the form. Other elements may be targeted and get the class "error" added, but this will not show visibly as an error in the form.
I have created a small module to provide the error flagging for the entity browser widget: https://www.drupal.org/project/entity_browser_validation


How to reverse engineer a section of a Drupal Page

Your question could use more specifics, but I think I understand what you are experiencing.

I've been there. If you cannot find it anywhere, a good bet is that it is part of the theme tpl pages. If you want to confirm this, you should go to the sites/all/themes/whatever-theme-you-are-using and search for files ending in .tpl.php, which are the files that control the theme you are currently using.

Frequently, any special effect or non-drupal configurable behaviour is likely inserted directly into these files. If your intention is to re-use whatever you are seeing at the top of the page, look for js (javascript) files: it is likely that dynamic pages are using some library, and that by googling the js filenames you can find a reference that might be useful.

At least, it has worked for me.


How to track Drupal user login-logout session length and registration activities?

For standard login, and 3rd-party login modules that are properly integrated with core, you can use:

hook_user_login()
hook_user_logout()
hook_user_insert()

For 3rd-party login modules that aren't properly integrated with core (i.e. don't fire those hooks), you'll need to approach each on a case-by-case basis, and find out what hooks they provide.

You could measure the duration of the session in hook_user_logout, by checking the account object's login property against the current time -  there's no hook for such a thing as it's not an event, just a value which needs some context to give it meaning.


How to make language choice Required for Taxonomy term

Write a custom module and use the following code

function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='taxonomy_form_term'){
     $form['#after_build'][] = 'MYMODULE_after_build';
  }
}

function MYMODULE_after_build($form, &$form_state) {
   if($form['language']['#value']=='und'){
     $form['language']['#default_value']='en';
     $form['language']['#value']='en';
   }
   return $form;

}

NOTE: In your custom_module.info file use this dependencies[] = i18n_taxonomy, so that your module can only be enabled if internationalization is enabled


How to create a filter in views which only shows contents that current user can edit?

It's probably not a very well-elaborated patch/module but it might solve your problem: https://www.drupal.org/node/620392 I've just found it...


Gmap, Views Draw Lines on Field Collection Locations Map

off the top of my head a custom module using hook_views_pre_build or 1 of the views hooks functions should let you "alter" the Macro value from something you load and compose from the database.

To be of more help we'd need to see your full content type admin page with field collection admin page, and the master layout of the view for example if you wanted coding help ...


Assuming you want to know when the update was really applied to your system, e.g. to check if the security fix was applied on time before the exploit was active in the wild:

If you are using drush for your updates and didn't delete recent folders, and didn't do any additional updates of your site, you can look up the last core update in your drush-backups folder. The updates have a timestamp in the folder names

e.g. in linux

find  ./drush-backups/<site-name> -name "drupal" -type d
or

find  ./drush-backups/<site-name> -name "modules/<module_name>" -type d
for a module update.

Otherwise you have to resort to the file modification attributes of the file-system, which might show write access from after the update.

To get the information in php you could try to use the php function filetime https://secure.php.net/manual/en/function.filemtime.php
on the CHANGELOG.txt file. This file should be updated with core each time, even if the content is not up to date.


What causes DatabaseSchemaObjectExistsException error on existing table while reverting feature?

This is usually caused when the initial feature revert or install went bad. The feature has attempted to created a field (I've only seen it happen with fields) and it's got as far as creating the base table and it's revision table but as far as features is concerned the field doesn't exist. Features then tries to re-create the field but Drupal errors out with that error message because the fields tables already exist.

My usual solution to this is to take a backup of the fields tables (including revisions) and then drop the effected tabled. You should then be able to revert the feature successfully and restore the data from your backup.


Is there a reliable way to see what other users see when logged in?

I can't vouch for either of those modules, but I've been using the 'Switch' feature in the Devel module to do just that for years. I've used it on probably hundreds of sites and I've never found a problem with it.

When logged in with appropriate permissions you can visit /devel/switch/[username] and it will log you in as that user. There's also a list of users in the admin toolbar that you can choose from directly, but I'm not sure if that's only available if you have the Admin Menu module installed.

It doesn't add a link to log back in to the admin user like the Masquerade module does (it's more 'bare-bones' than that), but if you've got your admin password saved in the browser it'll only take a couple of clicks to log back in anyway.


How do I show a "results count" on my search results page?

In the view that I'm using to override my search results, I added "Global: Result summary" to the views Header and it seems to be working with the facets. Thanks.


Altering a URL alias without using a module

Drupal allows to add (and alter) a path alias using the user interface. Generally, there is no reason to alter a database table directly, especially when a Drupal core module allows to do what you are trying to achieve through an administrative page.

If you need to do it from code, then you can use path_set_alias() function as pointed out from tim.plunkett. Differently, Drupal user interface is preferable for such tasks.

The query used by path_set_alias() to update an existing alias is similar to the following (I simplified the query by removing the reference to the language field):

UPDATE {url_alias} SET src = '<alias>', dst = '<destination>' WHERE dst = '<old_destination>'

If your Drupal site is using table prefixes (e.g. dr6_) then you need to replace {url_alias} with dr6_url_alias; if your Drupal site is not using table prefixes, then replace {url_alias} with url_alias.
Replace also <alias> in the query I wrote with the path alias, <destination> with the path to alias, and <old_destination> with the old path (which can also be the same value used for <destination>).

If there isn't a path alias, then the query becomes the following one:

INSERT INTO {url_alias} (src, dst) VALUES ('<alias>', '<destination>')

<alias> and <destination> have the same meaning I reported before.


Can I create a form with a route like this /rooms/{node.alias}/booking?

Is this possible? path: 'booking/{url_alias}' or path:
  '{url_alias}/booking'

path: '{url_alias}/booking' paths can never start with a slug/placeholder.

You'll have to use path: 'booking/{url_alias}'

In your form:

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $url_alias = NULL) {

    // Some DB query to check if $url_alias is the 2nd path of an alias.
    // In other words, check if "/rooms/$url_alias" exists.

    if ($db_query == false) { // if $url_alias is not the 2nd path of an alias.
       throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
    }

    // Your Form code goes here

    return $form;
  }


How to name a template file for the following theme hook suggestions?

You can also output the theme_hook_suggestion with DSM. You'll see all the suggestions and template candidates for your content. (https://drupal.org/project/devel_themer could help you too)


How to hide programmatically timezone and location on a custom user edit profile page in Drupal 7?

Solved. I had to use the solution suggested #35

This is the code i used

<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'MYNODETYPE_node_form') {
    $form['#after_build'][] = 'MYMODULE_SOMETHING_MEANINGFUL';
  }
}

function MYMODULE_SOMETHING_MEANINGFUL($form_element, &$form_state) {
  //note that I only have one location on this node type
  $form_element['locations']['#access']=FALSE;
  $form_element['timezone']['#access']=FALSE;

  return $form_element;
}
?>

I have not quite understood what is going on. An explanation about after_build would be appreciated.


Render taxonomy type custom fields individually

{{ content.field_type_poi }} doesn't necessarily render the entire content of the taxonomy term. You can select the field in the tab Manage Display where you've added the field field_url to the vocabulary.

If you need multiple field selections, here only this field, but in all other places the default selection, then add a custom view mode in Custom Display Settings at the bottom of the page.

Finally go to the content type and configure the  field field_type_poi in the tab Manage Display to be rendered in the view mode you've configured above.

Edit:

If you want to use different fields from the taxonomy in different locations you would need to clone the field, see Show field twice in node page, or install the module Twig Tweak and render single fields in Twig:

{% set tid = node.field_type_poi.target_id %}
{% if tid %}
  {{ drupal_field('field_url', 'taxonomy_term', tid) }}
{% endif %}


Disallow specific combination of checkbox selections in term reference field?

Take a look at the Field Validation module, it attaches a UI where you can set custom validation rules for each field on a content type.

I am not sure whether any of the inbuilt options will work for what you want, but you can select the PHP code option and write the rules you require. There is a short reference for the PHP validator here: http://drupal.org/node/1537028


How db_query works when I pass query parameter directly

According to Writing secure code for Drupal 8 (same for D7)

Use the database abstraction layer to avoid SQL injection attacks
Use the database layer correctly. For example, never concatenate data
directly into SQL queries.
Don't do this:
db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);

Instead, use proper argument substitution with db_query. The DB layer works on top of PHP PDO and uses an array of named placeholders:
db_query("SELECT foo FROM {table} t WHERE t.name = :name", [':name' => $_GET['user']]);


Execute Javascript when the registration form is completed

You need to add callback for the form submission. Something like this

function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#form_id'] == 'your_form_id') {
    $form['#submit'][] = 'custom_callback';
  }
}

function custom_callback() {
  drupal_set_message('This is my custom message');
}

Now, after the form submission, the custom_callback will also be executed.

If the code is Javascript and the form submission is via Ajax, you may have a look at the Ajax framework and Ajax framework commands topics in the API documentation. How to execute custom javascript code after an ajax succes (using the Drupal Ajax framework) ? is another useful page/


Is there a module that will add an image field that displays an image from an off site source?

You should take a look at the remote stream wrapper module and this issue that explains how to do it.


Path Redirect Import module getting "Line 1 contains invalid status code"

Looking at the csv row you provided, it looks like that the syntax is not correct:

Try to separate fields only with ',' and not with ', ' (comma + whitespace)
Use regular double " quotes or single quotes ', not these opening “ and closing ” double quotes you get when using word processors. I guess for the last two columns (status code and language) you won't need quotes at all.
You may also remove the headers line from the csv and check the "no headers" option if it contains non-ascii bytes.

See also this tutorial: Module of the Day: Path Redirect Import.


How do I profile a site that is on shared hosting?

Two of the most important optimizations to consider adding to optimize Drupal web server performance for ecommerce are APC & Memcached.

With Memcached, you will need to install the Drupal integration module & make some edits to the settings.php file. (tutorial)

With APC, there is also a Drupal integration module, but you need to edit the php.ini file on the web server. (tutorial)

You can also see if your web host supports Zend Opcache on shared hosting. Otherwise make sure to run Drupal 8 on PHP 7.x settings & upgrade to NGINX, Varnish Cache, & Redis solutions for the best web server performance for ecommerce.


One way to do this would be using rules.

Rules allow you to execute some rules/action sometime in the future.

See http://dev.nodeone.se/node/1032 shows a great similar example.


Well, as it turns out, the problem was that the form definition was in an .inc file and Ctools couldn't find it. The solution was to simply put the form definition, submit handler and ajax callback for select in a .module file.


How do I get total webform submission count of multiple webforms?

I found a solution to my problem - albeit not using Views - to accomplish what I wanted to do.

My goal was to have a counter on a page where it showed how many submissions for certain forms have been submitted. I needed to show a combined total of 2 or more webforms but could not accomplish this with Views.

I did find this code that led me to my solution:

First, need to include webform_submissions:

module_load_include('inc', 'webform', 'includes/webform.submissions');

Then added this line:

webform_get_submission_count($nid, $uid = NULL)

I took out the $uid as I did not need to filter by user and made multiple calls for the different webforms I needed:

$a = webform_get_submission_count($node->nid = '6');
$b = webform_get_submission_count($node->nid = '7');

I then put the following line to add the 2 variables to get me the total that I can then use on my page:

$c = $a + $b;

This solutions was actually better for me because with Views I could never get the No Results Behavior to show 0 when there were no submissions.


It seems that there is no autoescaping, at least for Drupal 8.7.3 which the version I tested.
For example:

{{ "
Is this escaped?
" }}
{{ " "}}

These lines are not escaped by default. However:

{{ "
Is this escaped?
"|escape }}
{{ ""|escape}}

These are escaped, so better be safe than sorry and use |escape for the input you're getting from your users.


Importing and filtering RSS feeds into nodes

The friendliest UI driven way to do this is probably with the Feeds module. Make your content type(s) using Drupal Fields and use Feeds to ingest the content via Cron or job_scheduler module. You might still need to code a simple module to do some things ... but it would require little coding I think.

The less friendly way would be the Migrate module (has a status-indicator UI, but no helpful UI for creating/moving fields). You'd end up coding alot of php to rip through XML and create X nodes in some content type. But, you'd still get a way to import/update/rollback items from RSS. They do have XML "News" examples I think in the Migrate modules example folder in the project.

I'd go with Feeds if you're new to this and stumble your way through that ... I haven't used it. I can only recommend it.


Can I create an "unlimited" values variable?

I'm not sure how well it will scale, but here is an example for a multiple variable in the Variable issue queue https://drupal.org/node/2019629

<?php
/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {
    // Use '[custom]' as a placeholder for the variable name.
    // It will set these properties ('type' and 'multiple') automatically.
    $variables['custom_vars_[custom]'] = array(
        'title'        =>    t('Custom multiple variable'),
        'group'        =>    'site_information',
        'repeat'    =>    array('type' => 'string', 'default' => 'some default value'),
    );
    // if you need to expose your custom variable as token
    // you have to set 'token' key as TRUE,
    // and ought to set the properties (name, description and type)
    // Notice that 'first' it is a name of variable defined in custom_variable_options().
    $variables['custom_vars_first'] = array(
                    'token' => TRUE,
                    'title' => 'Custom variable',                        // name
                    'description' => 'My first variable description',    // description
                    'type'    => 'string'                                    // type
                    );
  return $variables;
}
/**
 * Implements hook_variable_type_info().
 * @return
 *  An array of information defining variable types.
 *  The array contains a sub-array for each variable type
 *  with the variable type as the key.
 *  The possible attributes are the same as for hook_variable_info().
 */
function MY_MODULE_variable_type_info() {
    $type['custom'] = array(
        'title' => t('Custom variables'),
        'type'    => 'select',
        'options callback' => 'custom_variable_options',
    );
    return $type;
}
/**
 * Callback for custom options.
 * @return
 *  An array of variables with the variable name as the key.
 */
function custom_variable_options($variable, $options) {
  return array(
    'first'  => t('My first variable', array(), $options),
    'second' => t('My second variable', array(), $options),
    'third'  => t('My third variable', array(), $options),
  );
}

I dont think this is exactly what you want -- but may give you some ideas (it does the multiple value per "variable". I'm not sure offhand how you build a variable_form to edit the values in function custom_variable_options().


in your exposed filter, is the "expose operator" option checked ?

This might be the obvious answer.


Unique field value for all nodes and content types

Check out this example

function custom_node_validate($node, $form) {
  if ($node->type == 'page') {
    //retrieve the value for your field using Entity API
    $wrapper = entity_metadata_wrapper('node', $node);
    $value = $wrapper->field_collection->field_unique->value();

    //Execute a count query to see if there's other similar values.
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type', 'field_collection_item')
      ->fieldCondition('field_unique', 'value', $value)
      ->count();
    $count = $query->execute();
    if ($count > 1) {
      form_set_error('field_unique', 'Unique field value is already used.');
    }
  }
}


How to store css & js in separate file & call in custom 'tpl' files through variable in drupal 7?

If you do not want, or are unable, to modify the theme html or page templates, you can also use drupal_add_css and drupal_add_js in the page_callback function defined in your modules menu array youmodule_menu().

If you have access to the template.php of the theme,  you can use the preprocess hook to assign a variable to the file name, then do an include in the html template.  Or from within your module use drupal_add_html_head, but this has limitations.

Using drupal_add_(css|js) the links go into the head element of those pages by default before the themeing phase begins, but you can also specify the boostrap phase and location.

EDIT

Using drupal_get_path from within yourmodule_init hook or the page_callback, and with the css and js stored within your module structure, you can then add the css and js using the drupal_add functions.  This makes a single place you need to maintain the 'paths' to the files.


Fatal error: Call to a member function execute() on a non-object - db_select() addExpression

The addExpression method returns the unique alias that was assigned for this expression, and thus cannot be chained.

Please look at this example and the document.

$q = db_select('parser_subtasks', 'st')
 ->condition('QueueID', $task['ID'])
 ->condition('IsDone', 0);
$q->addExpression('MIN(Delay)');
$min_time = $q->execute()->fetchField();


Module similar to module filter to filter content and users?

Contentment (along with VBO) looks like a winning combination.


There is no equivalent in D8. What would be the closest to this is to assign a custom cache tag to the page and then invalidate it. See https://www.drupal.org/docs/8/api/cache-api/cache-tags.

But normally you don't need to invalidate cache tags in custom code. If you set the correct cache metadata this should happen automatically.


It doesn't totally help with the default paths, but I explicitly define them for each theme:

/**
 * Implements hook_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $path = drupal_get_path('theme', 'MYTHEME');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/favicon.png',
      'rel' => 'icon',
      'type' => 'image/png'
    ),
  ), 'MYTHEME-favicon');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-iphone.png',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-iphone');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-ipad.png',
      'sizes' => '72x72',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-ipad');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-iphone-retina.png',
      'sizes' => '114x114',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-iphone-retina');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-ipad-retina.png',
      'sizes' => '144x144',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-ipad-retina');
}


Change Omega4 Layout Based on Content Type via template.php

As per referenced question I would go with something like the following:

function THEMENAME_omega_layout_alter(&$layout) {
  if (arg(0) == 'node' && is_numeric(arg(1))
      && $node = node_load(arg(1))) {
        switch ($node->type) {
          case 'article':
            $layout = 'article';
            break;
          case 'blog':
            $layout = 'blog';
            break;
          default:
            $layout = 'default';
        }
   }
}


How can I display a block only when a node meets a particular condition?

I would use the PHP visibility settings to display the block on a node's page if a cck value in that node has some value, assuming that this cck field's value is an indication of that node containing calendar data. Once you've created the block that you want to display (or not display) add the following code to the "Page specific visibility settings" in the block configuration menu:

<?php
$node = node_load( arg(1) );

if ($node && $node->type =="[your_content_type]" && $node->field_has_cal_data[0]['value'] =='Yes'){
return TRUE;
}

return FALSE;

?>

This is assuming that the url is built like "content/name-or-id-of-node".


Restrict translation and editing of node to one language

I would suggest here checking NodeTranslationHandler class, in entityFormAlter you could find a way how to restrict a user from creating a new translation.


Custom node migration for multi-value imagefield

I think your problem come from source migrate. When you using process sub_process source data must be an array like this:

[
    'fid' => 1,
    'another_key' => '...'
],
[
    'fid' => 2,
    'another_key' => '...'
],
[
    'fid' => 23,
    'another_key' => '...'
]

Note: fid is old fid of database need to migrate.

I'll show you a example migrate field image with multilple value. I have a content type with machine name galary. This content type have body and field images (machine_name: field_images) ullimited value.

I'll migrate data to this content. Create migration group galary with file name migrate_plus.migration_group.galary.yml and content

id: galary
label: Import galary images
description: Import field images has multilple values.

Create migration file_images with file name migrate_plus.migration.file_images.yml

id: file_images
label: 'Migrate images files'
migration_group: galary
source:
  constants:
    file_destination: 'public://galary/'
  plugin: embedded_data
  data_rows:
    -
      fid: 1
      alt: 'Bootstrap'
      src: 'https://www.drupal.org/files/styles/grid-3/public/project-images/bootstrap_project_1.png'
      filename: 'bootstrap_project_1.png'
    -
      fid: 2
      alt: 'Adminimal - Responsive Administration Theme'
      src: 'https://www.drupal.org/files/adminimal-logo-slogan.png'
      filename: 'adminimal-logo-slogan.png'
    -
      fid: 3
      alt: 'AdaptiveTheme'
      src: 'https://www.drupal.org/files/styles/grid-3/public/project-images/Adaptivethemes_220.png'
      filename: 'Adaptivethemes_220.png'
    -
      fid: 4
      alt: 'Drupal8 Zymphonies Theme'
      src: 'https://www.drupal.org/files/styles/grid-3/public/project-images/desktop_8.png'
      filename: 'desktop_8.png'
  ids:
    fid:
      type: integer
process:
  public_path:
    -
      plugin: concat
      delimiter: ''
      source:
        - constants/file_destination
        - filename
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - src
      - '@public_path'
destination:
  plugin: entity:file

Create migration node_images with file name migrate_plus.migration.node_images.yml and content

id: node_images
label: Node galaryy
migration_group: galary
source:
  plugin: embedded_data
  data_rows:
    -
      nid: 1
      title: 'Bootstrap'
      body: 'Body Bootstrap'
      images: 1|3
    -
      nid: 2
      title: 'Adminimal - Responsive Administration Theme'
      body: 'Body Adminimal - Responsive Administration Theme'
      images: 2|4
  ids:
    nid:
      type: integer
destination:
  plugin: entity:node
  default_bundle: galary
process:
  title: title
  'body/0/value': body
  'body/0/format':
    plugin: default_value
    default_value: basic_html
  field_images:
    plugin: sub_process
    source: images
    process:
      target_id:
        plugin: migration_lookup
        migration: file_images
        source: fid
migration_dependencies:
  required:
    - file_images

In my case, two source file_images and node_images I use the embedded_data source plugin for the sake of simplicity so that this example can be copy-pasted as a working example.

Let see images: 2|4 or images: 1|3 in data_rows.
I'll use source: images for process sub_process plugin but data is not like data example. So I need use hook_migrate_prepare_row or method prepareRow in your source plugin to prepare soure.

/**
 * Implements hook_migrate_MIGRATION_ID_prepare_row().
 */
function MODULE_NAME_migrate_node_images_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
  $images = $row->getSourceProperty('images');
  $images = explode('|', $images);
  $data = [];
  foreach ($images as $index => $fid) {
    $data[$index] = ['fid' => $fid];
  }
  $row->setSourceProperty('images', $data);
}

Now, you can import data to this content have multiple field images with

drush mim file_images && drush mim node_images


How to position javascript file as the last one to load?

I was surprised hear that "only negative values are allowed" as JS weights, so I had to hunt that down.  And it's true... https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Asset%21LibraryDiscoveryParser.php/function/LibraryDiscoveryParser%3A%3AbuildByExtension/8.2.x There is an exception error message that says, "The $extension/$id library defines a positive weight for '$source'. Only negative weights are allowed (but should be avoided). Instead of a positive weight, specify accurate dependencies for this library."

This of course reminded me that, yes indeed, dependencies were added/improved in Drupal 8 so that we didn't have to worry about this.  Oddly enough, there are several core JS files that define weight, so I guess we are only part way there.

So, this is just a long-winded way of saying, what scripts does the Zurb Foudation depend on?  And can you list those dependencies in your libraries file under the Zurb script?  See https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module for more info.


If "#edit-radiobutton" should launch the state, just do:

jQuery('#edit-radiobutton').click().trigger('change');


Attach a submit handler on an ajax-y form (hook_media_format_form_prepare_alter)

It always pays to test your assumptions.  The media_format_form only saves metadata edits into the embedded media tag in the edit text contents; the alt and title information attached to the file object are not adjusted.  There is an advantage to this, in that different instances of the same picture embedded in different locations can also have different alt and title text.  Unfortunately, though, it also means that if an image is uploaded via the embedded media image tool in a wysiwyg editor, then the alt and title fields will be empty the next time that image is used, whether it is used as an embedded image or attached to a media image file field.

It would be helpful if media_format_form would save metadata changes back to the file object, just as media_file_edit_modal does.  However, it appears that at the moment, that capability is not present in the code.


Views date field does not follow custom date format

I still did not find the answer to this problem, but fixed it. I fixed it by simply saving the custom date format form in Date & Time in Drupal. Simply submitting that form, without making any changes, refreshed the Drupal views, and it started working properly.

I will look into the submit handler to see what caused the problem, and post if I find anything.


How to add image field to module install file

You are reading the wrong documentation. Please read Data Types instead. There is no image type for database field.

The available data type are:

serial
int
float
numeric
varchar
char
text
blob

Since Drupal manage file (including image files) in file_managed table with key fid. What you need is to create a int column for storing the value of foreign key fid. The column definition should be:

'image_fid' => array(
  'description' => 'The {file_managed}.fid being referenced in this field.',
  'type' => 'int',
  'not null' => FALSE,
  'unsigned' => TRUE,
),


How to set a file upload monthly quota on a role basis in Drupal 7?

The IMCE module allows, "configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions."


Drupal 8 Permission to see Structure > Menu

You would have to grant the following permissions to the role:

Required

"Use the toolbar
Administer menus and menu items
Use the administration pages and help

Optional

View the administration theme


D8 - show view in comments depending on user role

There is many ways to do it, but the simplest way is to check if user is admin or has exact role..

global $user;
   if ( !in_array('administrator', $user->roles) ) {
     ... do something ...
   }

OR

if( $user->uid !== 1 ){
  ... do something ...
}

OR

path_is_admin(current_path())


views to display list and related content on same page

I got it solved myself! What I did is:

Create a views page to display all contents having these taxonomy terms. This page has path "views-page".
Create a block view of those taxonomy terms, now while enabling this block the setting for pages tab is under Show block on specific pages --> select radio of "Only the listed pages" and the values for this should be :

  views-page
  views-page/*

This way when you select a term all related posts appear on the page and taxonomy block is also there.


Yes, you need to use a separate .htaccess file for your local version of the site.

It often makes sense to sync just the sites/all and/or sites/default folders (minus settings.php of course) of a Drupal site, so you can avoid this sort of problem without even having to think about it; unless you're hacking at core of course, which isn't recommended anyway :)


How do I allow full HTML while rendering a view?

I would suggest having your view display "content" of type "teaser" which would then allow you to use a twig template file such as node--content-type--teaser.html.twig.

This way you can add whatever markup you want to the twig file... even iFrames.

If you must have fields, for instance in exposed filters combine, remember you can "force" use fields in views :)


You'll need to create a database first:

mysql -u quaaout -p
create database quaaout;

Then you can continue your drush install adding a db name after localhost:

drush si standard --db-url=mysql://quaaout:PASS@localhost/quaaout --site-name=Quaaout


Drupal can help you doing this by its unicode functions.

https://api.drupal.org/api/drupal/includes%21unicode.inc/7

"ALYSSA" to "Alyssa" would be

<?php
  $name = drupal_ucfirst(drupal_strtolower($name));
?>

And "ENGANIO" to "E." would be:

<?php
  $name = drupal_strtoupper(drupal_substr($name, 0, 1)) . '.';
?>


I am unaware of any module that does this for you. So, you'll need to use a little bit of code to tweak things. What you need to do is implement hook_menu_alter() in a module to alter the way the tabs are organised. In particular, you will need to swap the menu type of the default tab and your video tab. The types in question are MENU_LOCAL_TASK and MENU_DEFAULT_LOCAL_TASK; i.e., change the default tab to MENU_LOCAL_TASK and your video tab to MENU_DEFAULT_LOCAL_TASK which should set the latter as the default. More information on these constants are provided on the hook_menu() page.


Share one User Table with two Drupal Sites

I believe this module does what you need Domain Access


You can define your own custom Twig functions in a custom module (but not in a theme). To find an example for how to do this, see this example in core/modules/system/tests/modules/twig_extension_test/src/TwigExtension/TestExtension.php.

Also see this blog post: Create Twig extensions for Drupal 8.

  In this example, we will build an extension to display a Drupal block
  directly in a Twig template:

{{ display_block('my_block_id') }}

  src/MyTwigExtension.php

<?php

namespace Drupal\MyTwigModule;

/**
 * Class DefaultService.
 *
 * @package Drupal\MyTwigModule
 */
class MyTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'block_display';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('display_block',
        array($this, 'display_block'),
        array('is_safe' => array('html')
      )),
  }

  /**
   * The php function to load a given block
   */
  public function display_block($block_id) {
    $block = \Drupal\block\Entity\Block::load($block_id);
    return \Drupal::entityManager()->getViewBuilder('block')->view($block);
  }

}

  src/MyTwigModule.services.yml

services:
  MyTwigModule.twig.MyTwigExtension:
    class: Drupal\MyTwigModule\MyTwigExtension
    tags:
      - { name: twig.extension }


I think this approach is fine for your use case, since it's so unlikely you'd intentionally begin a title or body with a colon on purpose.

I'd clean up the code a bit though for coding standards like

/**
 * Implements hook_node_presave().
 */
function my_module_node_presave($node) {
  if ($node->type == 'mytype') {
    $node->title = _my_module_my_function($node->title);
    $node->body[$node->language][0]['value'] =  _my_module_my_function($node->body[$node->language][0]['value']);
  }
}


Showing All Taxonomy Terms count based on a given contextual filter

You Did your jobs correctly but you have only one mistake, you should create  views according to nodes then relate it to taxonomy instead create taxonomy view then relate it to nodes.
I explain my mean by example

Nid           title         termid
1           title1       55
2           title2       43
3           title3       55
4          title4        --
5          title6       16

So when  there is not set termid view has a row result with no termid then this mean you can  put 0 value in  "No result"


Views: alter data of a View of another module

You would create a module.  It only needs a simple modulename.info file and modulename.module file.

If you called your module 'mymodule', then in mymodule.module add the function:

mymodule_views_data_alter(&$data) {
  \\custom code
}

Clear the caches and you should be good to go.

The hook system allows modules to interact with other modules code. By naming your function MODULENAME_views_data_alter you are telling Drupal that you want to take advantage of the hook HOOK_views_data_alter.


Will upgrading PHP version affect my current site that running Drupal 6?

As reported in System requirements, Drupal 6 requires PHP 5.x, since support for PHP 4.x has been dropped by PHP maintainers; it is recommended PHP 5.2.5 or higher, but PHP 5.3.x and higher may produce errors or unexpected behavior.

So, yes, PHP 5.6.14 is going to affect your Drupal site, especially if you installed third-party modules or themes.

Bear in mind that Drupal 6 core code will not be changed, after Drupal 8 will get its first official and stable release. If they don't fix Drupal 6 code before, it will not get fixed. Once Drupal 6 code is not fixed, it is also probable third-party modules stop to get updates too.


How to install Drupal without interaction via web UI?

You can Install Drupal using Drush without interacting WEB UI.
You have to use following command

drush dl drupal-7.x --drupal-project-rename=D7
cd D7
drush site-install standard --account-name=admin --account-pass=admin --db-url=mysql://YourMySQLUser:YourMySQLPassword@localhost/YourMySQLDatabase

Ofcourse You have to install Drush if not already installed and change Mysql Database details in command as per details.

Choose installation profile that you want to install

site-install standard OR site-install minimal


Seat reservations for (recurring) events on given days

I don't think you are going to find a solution that does 100% of what you need, I expect there will need to be custom development here.

Sounds like a custom content type (CCK) + ubercart + paypal (with ubercart) will be the most flexible solution. Perhaps read through the reservation module to see how it limits the available supply of tickets (i.e. sold out).

I would also suggest to remove the graphical part of the event registation, as this looks like it could be tricky, and instead focus on the core functionality of the app, i.e. the registration and payment workflow.

Every problem can be solved in drupal, but some of them are unique, and have their own solution.

If you need this solved ASAP, looks like you may need contractors, or some late nights ;) If you want to attract more quality answers, consider placing a bounty on this


You can use the role based theme switcher module. It allows you to switch the whole theme. If you only want to change one template you can use this thread.


How to create a custom content type region template?

There is a lot of ways to accomplish your goal. I'll point some of them:

Using template files

One of them is to add the new region to your current theme and just use the modules suggested by Sohail (Delta and Context) to make the blocks to be shown in the project detail page. This means that your current theme will be a new site wide region to be used as you need.

There is some other questions that cover this:

How do I create custom regions in a theme?

Render a custom region inside node template

Using GUI

Another way to do this is by using the Display Suite module. Here goes a summary of the module description:

  Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files.

You can also use the Panels module suite and also the Panelizer module to achieve this goal.


Those links appear in Google's index because they're linked to on your site (presumably the pager generates those links for you) and you allow Google to crawl and index them.

If you do not want those pages to be crawled and indexed by Google, then you can disallow it by adding the following to the robots.txt for your site (btw.: this has little to do with Drupal):

Disallow:*?page=*

This will stop googlebot (and msnbot) from crawling the pages that is linked to with a link that contains this pattern.

Note that wildcards are not part of the Robot Exclusion Standards (but are supported by googlebot and msnbot), so don't expect any rule with wildcards to be widely recognised by robots.


Integrating file management with Organic Groups

Partial answer is that CKFinder doesn't integrate with OG out of the box, or easily at all. They do offer an access control list, but you would need to know the specific directories and specific people who need access. It won't work to create folders/permissions on the fly when creating groups or add/remove permissions as members are added/removed to the group. They mentioned that a custom plugin may be possible to do to modify the access control list but that it would be quite a bit of work. Java was recommended for the custom plugin.


Omega 4: despite of environment set to production, css-file is full of sass-debug-info

I cannot see anything wrong with your config.rb but if you are having problems you can use the following to force compass to strip out the debug info.

compass compile -e production --force

Source: https://www.drupal.org/node/1936986


Calculate values from multiple content items

did you try to use the Aggregate option (use SUM field aggregation option) and Views Calc at the same time ? That might do the trick.

If not, you can use a PhP block (you have to send it the engine node id, I hope you use Panels or node.tpl.php).

Then, the code would be (I guess) ;

$engine_usages_nids = db_select('yourentityreferencefield', 'n')
  ->condition('entity_id', $the_engine_nid, '=')
  ->field('n', 'field_yourentityreferencefield_nid')
  ->execute()
  ->fetchCol;

$myfields_values = $db_select('field_data_hoursuagefield', 'h')
    ->condition('entity_id', $engine_usages_nids, 'IN')
    ->join('field_data_mileagefield', 'm', 'h.entity_id = m.entity_id)
    ->fields('h', array('hoursuagefield'))
    ->fields('m', array('mileagefield'))
    ->groupBy('h.entity_id')
    ->execute()
    ->fetchAssoc;

$total = 0;
while($record = $myfields_values) {
  $total = $total + intval($record['hoursuagefield'])*intval($record['mileagefield']);
}

echo($total);

This is all made by heart, I advise you to double-check :)

Have fun !


How to modify the D7 user login page html to remove the register and new password options for non-admins?

I don't think you've thought this through. The standard login page (/user/login) only shows the login form when a user is not yet logged in. So if you want the ability for admin users to see the usual options on that page, you will need to show them to all users -- since you don't know whether or not the user is an admin before they log in. If a user is already logged in (whether through OAuth or standard login) they will not be prompted to log in again.

If, instead, you want to modify the user login options for all users, this can be accomplshed via hook_form_alter() in a custom module, replacing MODULENAME with the name of your module in the hook implementation:

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    // Your code to modify the form goes here
    $form['some_text'] = [
      '#markup' => '
Some text to inform users of new registration procedures
',
    ];
  }
}

EDIT: If you have never made a Drupal module before, don't be intimidated! The type of thing you're trying to do can be accomplished with a very small module.

Keep in mind that the Drupal Form API is basically just a bunch of PHP arrays.

To add markup to a form array, use the #markup form element as I've shown im my example above.

To remove an element from a form array, you can unset() that value before the array is rendered. For example:

<?php
unset($form['buttons']['preview']);
?>

I'm not sure what form elements you'll want to remove, but this technique should help.

This stuff is well documented on Drupal.org and all over this forum.

Remove unwanted form elements
Add markup to a form
hook_form_alter()
Drupal Form API reference


You can find the CSS class or id by installing firebug in your Firefox installation. It let's you point and click on every area of the page.
If this is not enoug install the Theme Developer module (http://drupal.org/project/devel_themer). It helps you to find the appropriate theme merhods and template files to tweak the output to your needs.

If this is all strange stuff, make yourself familiar with basics about drupal theming. This is a good starting point: http://drupal.org/documentation/theme


Get the raw URL of an image in views-view-table.html.twig

Thanks to all, especially @belltouche and @Jaypan, for taking the time to respond. After all the kind suggestions and lots of reading and trial-and-error, I ended up using the following code in views-view-table.html.twig to display an image URL:

{% for i, row in rows %}
  ...
  {% if view.field.field_image.value(view.result[i]) %}
    {{ row.columns.field_image.content|render|striptags|trim }}
  {% endif %}
  ...
{% endfor %}

Note that I'm using the URL to image formatter for the image field in the view.

To explain, view.field.field_image.value(view.result[i]) gets the raw value of the image field, which turns out to be the entity id for the image. Checking it makes a concise test to see if there is an image in the field (if there's a better way, please say so).

It also turns out that there isn't any other information about the image in the raw value. Just the entity id, which is why I could never find the image URL in the raw value.

There was a suggestion made that I could use Twig Tweak to load the image entity by its id and get the URL from it. I'm sure this would have worked, but since my purpose was to avoid the overhead of render|striptags|trim processing, loading the entity after it had already been loaded to produce the content didn't seem an advantage.


Commerce - How to hook into ajax call on commerce cart form variation change

There's a hook for that: hook_commerce_cart_attributes_refresh_alter. This is invoked when the variation is selected by the user and reacts to changes in the cart widget.

It gives you the chance of using ajax commands, so you basically have the complete control over elements and behaviors, there's an excellent tutorial in here: https://drupal.stackexchange.com/a/73325/2322

Also, a couple of examples, Commerce itself invokes the hook from the cart module
and there's this sandbox module called Commerce Single Page Checkout that uses the technique for adding a view on the refresh event using ajax_command_replace.


Looking at the code used from Drupal core, I found that book.admin.inc uses the following code, to define a require radios element.

$types = node_type_get_names();

$form['book_child_type'] = array(
  '#type' => 'radios',
  '#title' => t('Content type for child pages'),
  '#default_value' => variable_get('book_child_type', 'book'),
  '#options' => $types,
  '#required' => TRUE,
);

The code you shown doesn't work because #default_value is set to NULL.

'#default_value' => isset($which_option) ? $which_option : NULL,

You don't show how $which_option is initialized; either that variable is never initialized, or it is not initialized when you tested the code. In both the cases, isset($which_option) returns FALSE and #default_value is set to NULL.

Instead of that, the code should avoid setting #default_value, which is what form_test.module (a module for testing form elements) does. (See the first form element in the following code; the other form elements are shown to make a comparison.)

$form['radios'] = array(
  '#type' => 'radios',
  '#title' => 'Radios',
  '#options' => $options,
  '#required' => TRUE,
);
$form['radios_optional'] = array(
  '#type' => 'radios',
  '#title' => 'Radios (optional)',
  '#options' => $options,
);
$form['radios_optional_default_value_false'] = array(
  '#type' => 'radios',
  '#title' => 'Radios (optional, with a default value of FALSE)',
  '#options' => $options,
  '#default_value' => FALSE,
);

Notice the first radios element, which is required, doesn't have any #default_value property set.


drupal running really slow on apache mac os x

Install devel module in your drupal site. After enabling devel module, you need to enable query log and page timer in devel configuration page. by doing this you will see how much time each function is taking to load and will able to analyze you site.


Install the references module, once you done that, you can enable the node_reference submodule and attach a "Node Reference" field to your "event" content type. Choose the "select list" widget and the user will be able to link any location to the event.

If you want to let the user choose only from locations he created, here's a way:

On the field configuration page, you can see a fieldset called "Views - Nodes that can be referenced". It says that options from the dropdown can be filtered based on a view using the "References" display type.

Just create a view listing location nodes and select the correct "display type" as shown below:

And display nodes from the current logged-in user by adding a contextual filter "Content: Author uid"

Save all that and refresh the field configuration page. Select the view from the dropdown list that just appeared and you should be good to go ;).


Removing posted by admin date from a contact form

There are multiple ways you can do it

For all content of same content type

Go to the content type for which you want to hide Author info.
Scroll down to see the tabs at the bottom and select Display settings.
Uncheck Display author and date information.
Save content type

For Single Node

Go to node.tpl.php and search for $submitted
Give below condition for you case

if ( arg(0) == 'node' AND is_numeric(arg(1)) AND arg(2) == FALSE AND arg(1)==7) {  print $submitted; }


You are looking for hook_theme_suggestions_HOOK_alter().

HOOK is the name of the template, in your case, page. You should be able to add the following to your theme in the .theme file.

In there, do something like this:

function yourtheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $suggestions[] = 'page__node__' . $node->getType();
  }
}


You should really try to get to the bottom of why hook_init is being called twice, but for a band-aid solution, you can use a static variable (using drupal_static) to keep track of whether your implementation of hook_init has already been called.


How to show views filters on a block or page

Choose exposed form in block to yes in views advanced settings, Then you can find your exposed form block in block listing page and can configure to any page or region


Use hook_menu_alter(&$items).

function yourModule_menu_alter(&$items) {
  $items['jquery_ajax_load/get']['delivery callback'] = 'yourModule_jquery_ajax_load_delivery_callback';
}

That's clean and "Drupal way" to solve your problem.


function uc_stock_adjust($sku, $newStock); not returning any value

Function uc_stock_adjust has no return value.

  Description: This function adjust a particular product SKU by a
  certain value (a positive integer will add to stock, a negative
  integer will remove from stock).

  Parameters:
  $sku - The product SKU that will have its stock level adjusted
  $qty - The quantity to add to the stock level

  Return value: No return value.


Calling a javascript function from a form item ajax callback?

PHP:

$commands[] = ajax_command_alert("Here!");
$commands[] = array(
  "command" => 'your_custom_command',
  "latitude" => "45.23",
  "longitude" => "23.25"
);

Javascript:

Drupal.ajax.prototype.commands.your_custom_command = function(ajax, response, status) {
  if( response.latitude != "" ) {
    // do something
  }
};


Omit blank lines when trimming fields with views

I've had a similar problem in the past, especially when making the summary trimmed to a shorter length.

When it tries to truncate certain tags like tables or images that can be quite long - and the number of characters you allow is reached before the table/image has been fully parsed, you can end up with a blank summary.

What I do is that I strip certain HTML tags from my fields that are trimmed to only display paragraphs, etc - not images and/or tables.

Just click on the field to set up the new configuration, and you'll find the option in the 'Rewrite Results' section:

Let us know if this works!


Dealing with compressed JSON string from external API

Ok, I'm sorry I just figure it out. I wasn't looking at the $request->headers to see what method to uncompress I have to use. Here is the solution:

$request = drupal_http_request('https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&site=stackoverflow');

if (isset($request->headers['content-encoding'])) {
  if ($request->headers['content-encoding'] == 'gzip') {
    $request->data = gzinflate(substr($request->data, 10));
  }
  elseif ($request->headers['content-encoding'] == 'deflate') {
    $request->data = gzinflate($request->data);
  }
}

$json_response = drupal_json_decode($request->data);


You can also use setRedirectUrl(), which needs a URL object. There are many ways to create one, for example for an arbitrary path: Url::fromUri('base:some/path')


Limit image file size; if bigger, then decrease file size with lossy compression/resizing/etc. for saving disk space

The built-in functions will not do this.

You will have to write a hook for the form,  upload the image at the original large size and then use Imagemagick (or similar) to process the image.

I only suggest Imagemagick because it's got more tools than GD and you should be able to re-size the image in a loop, testing for filesize and resizing/re-compressing as necessary.


How to override some text in the login form located in a block put on a panel?

This sounds like a job for hook_form_alter() and it can be used from either a custom module (eg, MODULENAME_form_alter()) or in this case probably more easily from your theme, eg, something along these lines inside your template.php file:

function THEMENAME_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {

    case 'user_login_block':

      // drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>');  // uncomment to see what you have to work with

      $form['name']['#title']='Enter UserID here'; // originally "Username or e-mail"
      $form['pass']['#title']='Enter Secret here'; // originally "Password"

      break;

    // other form ids go here

  }

}

The above (after clearing caches) will turn this:

into this:

If you need to change other text in the form, you can uncomment the drupal_set_message() and look in the form to see what you have to work with and change it appropriately.

ADDITION:

If you want to get rid of both of the links, eg, the Create new account and Request new password you can either do:

unset($form['links']);

or set the access to them to FALSE, eg:

$form['links']['#access']=FALSE;

Lots more information about this can be found in the Drupal Form API Reference.  I would look into the #weight key for changing the position/ordering of elements in the form.


Drupal's form API has CSRF protection built in, so submitting a form from an external domain won't work. You could either look at disabling the CSRF (very bad idea), or as you suggest, use the Services module.

There's no one-to-one mapping between the services module and forms on the site, rather modules implement resources for certain tasks to be consumed from an external client. You get node, user, taxonomy term, and probably others by default. So you can (for example) add a new node/user/term, but you do so by sending xml/json/etc requests to the server after having authenticated, not by submitting a form as such.

Getting data works in much the same way. You can either use Services to do that, or if you can manage/don't need your own authentication see indrock's answer for a good method.

Services is very extensible, so even if the answers module doesn't implement resources, it's a pretty easy job to add your own that wrap around API functions from the answers (or any other) module.

The documentation for services would probably be a good place to start.


How to mark product if it has already been purchased by current user?

This really seems like a perfect fit for the Flag module. Excerpt from its project page (bold markup added here):

  ... 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.

  Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.

  In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

Refer to Flag's Community documentation for (way) more details.

You should configure an appropriate (non-global) flag, which you should then use to (automagically) flag products each time a user buys some product. And next time some products are shown to such user, you use that info about "has this product yes or no been flagged by this user already".

To actually flag such products, you should use the Rules module, which integrates extremely well with the Flag module. All that's left is to find the appropriate Rules Event for such rule to be triggered (somewhere along the lines of "checkout completed" I would assume).

If you'd want to take this even a step further, you could also consider what is described in the accepted answer to "How to add a custom icon or symbol to a flag link?".


Can I use the $language variable in a Drupal 6 template file?

The variables that are usable in a page template are visible in the source code of template_preprocess_page(). The template file you are referring to has the variable $language, which is a copy of the global $language, where $language->direction has instead the values "rtl" and "ltr."
The content of $language is an object with the following properties:

'language'
'name'
'native'
'direction'
'enabled'
'plurals'
'formula'
'domain'
'prefix'
'weight'
'javascript'

The line of code you wrote needs to be written as if ($language->language == 'es').


Check out file_create_url() function:

Example of usage in a preprocess hook:

$variables['image'] = file_create_url($variables['directory'] . '/images/image.png');

Example of usage in a twig template:

 <img src="{{ file_url(directory ~ '/images/image.png') }}"/>


Proper way of removing/hiding unwanted elements?

It depends what you are hiding.

If it is something like a page or block title or labels or other semantic type markup, you should hide it using the element-invisible class, which effectively hides it but without using display: none. This way screen readers can still see the text, which helps give visually impaired users context for the subsequent content, which is required for accessibility reasons.

If you are hiding actual content, like fields, or whole blocks, or menus etc. you should not be doing it in the CSS. It is best to do it on the back end.

The time when this is most important is hiding for access control. Never use css to hide data or fields that a users should not be allowed to see. Because that data is still available to the user, it just isn't visible by default. So that would be a security issue.

For forms you can use hook_form_alter(), hook_form_BASE_FORM_ID_alter() or hook_form_FORM_ID_alter().

For other areas, there are many possibilities depending on what you are themeing and what you are intending to do. Some examples, are hook_node_view_alter() for node pages, hook_user_view_alter() for user pages, other alter hooks, template preprocessors, theme functions and template file overrides.

For more information on drupal hooks see http://api.drupal.org
For more information on overriding theme functions and template files see http://drupal.org/theme-guide/6-7


Override default node form submit handler

Wow, The magic was using form alter along side the menu callback which created and handled the node like this:

function my_module_form_node_form_alter(&$f, &$fs) {
  $f['actions']['my_action'] = array(
    '#type' => 'submit',
    '#value' => t('My Button'),
    '#submit' => array('the_submit_func_here'),
  );

dpm($f);
}

Notice it's not a button type but is of type "submit". I have no idea how Form API handles submits, I thought I was having issues because of FORM_ID_submit but now I have no idea what is happening?


How to get searched item value in search form?

You can catch your entity in the preprocess and put data into drupal_static. After that you can display it where you want.


drupal 7 views structure: Different nodes should collect different (term) lists

Yes, this is absolutely doable with one View.

What you are looking for is under Format: Unformatted list (or whatever your view style is) | Settings.

Click Settings and set a Grouping Field based on the field you would like to group - "content type" in this case.


Operations bulk form for custom content entity

You need both an action plugin and an action config entity

Create the plugin with drush: drush generate plugin-action
Create the action config entity: look at
"system.action.comment_delete_action.yml" for an example.

After creating these, clear the cache and it should be available in views under the label "Bulk update".


How can I mock a class during a functional request that is called from within a controller?

Since the request your test is making spins up a completely new PHP process to deliver the contents of that request, nothing you do in-memory during the execution of the test will be reflected in the new HTTP request process.

Fortunately there are some techniques to create HTTP clients that can be used inside functional tests that span longer than a single request. The technique involves creating a test module, which replaces the HTTP client in the container, for all requests that happen while the module is enabled.

Your test may then:

Switch the module on during setup.
Use the new HTTP client in HTTP requests during the lifetime of the test.
Switch the module off, if you're required to clean-up.

The key parts of a test module like this are:

my_module/tests/modules/my_module_http_client/services.yml

services:
  my_module_http_client.http_client:
    decorates: 'http_client'
    class: 'Drupal\my_module_http_client\MockHttpClient'

my_module/tests/modules/my_module_http_client/src/TestHttpClient

<?php

namespace Drupal\my_module_http_client;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;

/**
 * Test HTTP client for the air quality test.
 */
class TestHttpClient extends Client {

  /**
   * {@inheritdoc}
   */
  public function get($uri, array $options = []) {
    return new Response(200, ['type' => 'text/xml'], file_get_contents(__DIR__ . '/some-test-fixture.xml'));
  }

}

Of course in the body of ::get, you can program any logic you like. A common pattern is to use the state API to allow the test to specify a behavior for the client. An example might be something like, setting which response fixture to return.

These kind of functional tests are really valuable to ensure your whole system is working end to end. I would however caveat this with saying, it is also valuable to identify units in your controller which can be tested in isolation. Unit tests can often test a lot more scenarios at a might higher speed than a fully bootstrapped implementation might be able to.


Sorry for this late reply... but here is the module you are looking for:

Twitter API Block

As explained in its README file, you need to download it and the required library with composer, as follow:

composer require drupal/twitter_api_block drupal/j7mbo/twitter-api-php

Then go create a new app in Twitter and finally, place the block in your Drupal site.

Simple :) Enjoy!


You can add a standard menu item to any menu with a path of user/logout.


Upgrade Status module reports PHPUnit\Framework\TestCase is not an interface

Are you using the latest versions?
Upgrade Status recently released a new version (3.3) a couple days ago, and it seems something is wrong with PHPStan.
Testing on Drupal 8.9.13 with Upgrade Status 3.3 and Admin Toolbar 3.0, after scanning Admin Toolbar, I get only this issue:
web/PHPStan failed  0   PHP API deprecations cannot be checked. Reason: Array ( )

Which is linked to the bug report listed above.
In any case, regarding your error, if you go to the Admin Toolbar module page on drupal.org, you'll see that both the 3.x and 2.x versions are marked as compatible with Drupal 9.
In general, it's safe to trust modules that say they are compatible with Drupal 9 on their module pages whose most recent release is after the release of Drupal 9.0 (June 3, 2020).  Maintainers of some modules that were last updated earlier in 2020 marked their modules as compatible with Drupal 9 while it was still in alpha or beta, and then Drupal 9 changed before the release, breaking compatibility with those modules.


You can use CSS rules to position the images like you want.

Another options would be to use views to display the images, which has built in support for displaying items in a grid.

If you want a more detailed answer, you should provide more info in your question.


How to customize a single default taxonomy page?

If you are using the standard issue taxonomy module to output your pages, eg:

www.yourhost.com/taxonomy/term/###  (or whatever its eventual alias is)

you can modify taxonomy-term.tpl.php to do almost anything you want.

In D7, it's provided for you and basically looks like this:

<div id="taxonomy-term-<?php print $term->tid; ?>" class="<?php print $classes; ?>">

  <?php if (!$page): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

  <?php endif; ?>

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

The key variable to your question is $term and you could do something like this:

<div id="taxonomy-term-<?php print $term->tid; ?>" class="<?php print $classes; ?>">

  <?php if (!$page): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

  <?php endif; ?>

    <?php if ($term->tid==THE_TID_YOU_ARE_LOOKING_FOR): ?>
       <?php // do something different here ?>
    <?php else: ?>
      <?php print render($content); ?>
    <?php endif; ?>


How can I have multiple versions of the same form, in different pages?

You can use hook_menu() with drupal_get_form() to use any form on any path (see Using a node editing form on a page that not a node edit page).

You can then use hook_form_alter(), and get that to work differently depending on the path.

You can use $_GET['q'] for the full path or arg() to get parts of the path. and use if() logic to determine how to alter the form.


Anything inside a t() function can be overridden, you need to paste the exact contents into String overrides in settings.php or use the String Overrides module


drupal_get_form has to be called to render a correct form.

Alter the hook_menu definition to this:

function tournament_menu() {
    $items['tournament/newteam'] = array(
        'title' => t('Créer une nouvelle équipe'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('form_newteam')
        'access callback' => TRUE,
        'file' => 'form_tournament.inc',
    );
}


Removing input formatting options and description from comment form

Ok found this drupal issue discussing the matter: Node and Comment Input Format fieldset is not working (I found it by searching for "edit-comment-body-und-0-format" which html id of the fieldset that contains all the input format mumbo jumbo).

At the end of this issue is a link to the following site which gives a solution:
How To Remove Format Options / Guideliness From Comments Textarea in Drupal 7.

Here's the code I'm using on my site, in template.php of my theme (I'm using a zen subtheme):

function mytheme_form_comment_form_alter(&$form, &$form_state) {

  $form['comment_body']['#after_build'][] = 'mytheme_customize_comment_form';

}

function mytheme_customize_comment_form(&$form) {
  $form[LANGUAGE_NONE][0]['format']['#access'] = FALSE;
  return $form;
}

I just tried it and it does seem to be working. Woohoo!


In D8 the fields of a comment can be configured in a comment type where you can define a field with a maximal number of characters. For a character countdown you need some javascript code or use a field module like Maxlength.


Profile 2, user relation access? A hard one!

Here is a zero code solution.

Flag + Rules + Rules Block Visibility
 + Views

1 flag for "request"

1 flag for "allow"

When "request" flag is flagged >> send e-mail with link to flagging user profile.

Then other person opens link and sees their profile and clicks the "allow" flag.

If user is listed in the Allowed flag list, then show View Block with the all the fields, if not, then show View block with limited fields.

Here is an indepth example to using Rules Block Visibility: How to stop a Views block from displaying to admins, such as user/1?


"Questions that may already have your answer" Stackexhange Module For Drupal

If a 'Question' is a node, you could use the Similar Entries module as a starting point:

  Similar Entries provides lists of links to site content related to the current node being viewed. Links can be displayed in standard blocks or as part of custom views. Similar content is located and rated using MySQL's FULLTEXT indexing for MyISAM tables. FULLTEXT is a special query that helps find relevant content in other nodes using a natural language search that interprets the search string as a phrase in natural human language.

It will require some customisation to get a similar workflow to the one Stack Exchange uses (you'll need to make the blocks appear on the node add/edit pages somehow, and implement an AJAX solution for suggestions while writing the title).

I'd be surprised if there's a module which replicates the functionality here straight out of the box.


VotingApi function takes time to update the database

I hope this code may work for you Try this code in your theme's js file:

Drupal.behaviors.Your-Theme-Name = {

 attach: function (context, settings) {

//add your class in click function

    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {

         location.reload();

        });

    });

  }

    };


Exposed Filters in Entity Type Reference

you can put your car categories in a taxomomy list and then use Hierarchical Select to filter the way you asked. quite straightforward.


Edit: Just looked at the code more closely, and saw this was the Services module.

From https://www.drupal.org/node/1971484#comment-7318114:

  For those of you who will probably have the same problem, here is the correct way to handle LIST type fields (in ex. below field_mosaic_bu):

{
  "type":"TEST",
  "title":"TITLE",
  "uid":"1",
  "field_mosaic_bu":{ "und": ["bu name"] },
  "field_mosaic_var1":{ "und": [{ "value":"test1" }] },
  "field_mosaic_var2":{ "und": [{ "value":"test2" }] },
  "field_mosaic_var3":{ "und": [{ "value":"test3" }] },
  "field_mosaic_image":{ "und": [{ "fid":"4" }] }
}

  Hope this helps someone. Took me a lot of time to figure this out.

When you get that message from Drupal, it generally means that you have tried to set a form value to a non-allowed value from the perspective of the field configuration. So, for example, field_kategorisi might be a Term Reference field. If you try to set it to a tid that isn't allowed according to the Drupal field configuration, that happens.

If it's a simple checkbox field, then adding the value you want to set to the Allowed Values in the field configuration should solve the issue.

If this doesn't help, please provide more information about the Drupal-side field configuration and whether you are using the form Drupal generates or not. It embeds various things like the form ID, form build ID, and so on into its form markup, so if problems persist, it could be related to it not receiving something it's expecting.


Inserting in user's field on creating the user?

If you're using Drupal 8,
See This one.

Update a node:

Example 1 : Update title

$node = \Drupal\node\Entity\Node::load($nid);
$node->setTitle('The new Title')
$node->save();

Example 2 : Update a field ('body' and 'field_name')

$node = \Drupal\node\Entity\Node::load($nid);
$node->set("body", 'New body text');
$node->set("field_name", 'New value');
$node->save();

To make changes after click on save / edit button, you can use the hook_entity_presave.
hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity);

Example:

function CUSTOM_MODULE_node_presave(Drupal\node\NodeInterface $node) {
  $node->setTitle('Edited Title');
  $node->set('body', 'this is the bew body');
  //CAUTION : Do not save here, because it's automatic.
}

  Note : Do not re save inside of hook_entity_presave().

Using HOOK_entity_presave()

function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityType()->id() == 'node') {
    $entity->setTitle('The new Title');
    //CAUTION : Do not save here, because it's automatic.
  }
}

Source : drupal8.ovh


unable to see drupal home page when configured live site into in my local system?

Try adding

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

in index.php file, that will be showing the actual error on front page.


How to use Drupal in the cloud with on demand instances

Rackspace put together a pretty decent start to this subject here which uses a couple of specific technologies which you might not want to use, but the principles are the same.

You might also need to look at Mysql clustering, but only really if you're hitting serious traffic levels


You can use hook_js_alter to replace your JS file (from parent theme) with the one in your child theme.
function child_theme_name_doc_js_alter(&$javascript) {
  $javascript['themes/parent_theme_name/js/parent_theme_name_navigation.js']['data'] = drupal_get_path('theme', 'child_theme_name') . '/js/child_theme_name_navigation.js';
}


Programmatic Content on a Node - preferably a non-code solution

I think you can achieve this using the Context module. Here is a quote about it (from the module's project page):

... allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.


How to redirect a node to an external URL?

Since you want this done in a view here is a possible solution

Add a link field to your content type external url which would need to be followed when available otherwise (if empty) it would take to node view (normal behaviour).

Modify the Fullcalendar View and add follow 2 fields

Link to content hidden

external url and adjust the No results behaviour to include {{ view_node }}

Use external url as the link

NOTE: it appears that Fullcallendar view module takes the link to node in a way that it cannot be modified within the view as described above.  There is a feature request that asks for such an option.  In the meantime perhaps the above can be achieved with another calendar module () or modify the URL from within a custom module.


Have you tried himuesgallery module?

  It implements a new node-type to show all pictures in an specified directory. Descriptions will be automatically generated from the filenames, so there is no need to administer a seperate databse table, etc.
  My gallery works with automated generetated thumbnails so it seems to be fast.
  It can use Lightbox2 or colorbox to simply generate lightshows and naturally it makes use of user configurable css-files to style the gallery. Some styles will be delivered with the module, so users don't be worried about this.


D6 -> D8 : Migrate only taxonomy terms from a specific vocabulary

You could create a plugin, where you can use sql to query what you need.

For example:

<?php

namespace Drupal\custom_migration\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;

/**
 * Minimalistic example for a SqlBase source plugin.
 *
 * @MigrateSource(
 *   id = "custom_vocab_plugin",
 *   source_module = "custom_module",
 * )
 */
class CustomVocabulary extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('vocabulary', 'v')
      ->fields('v', [
        [....] // YOUR SQL HERE
      ]);
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    return [
      [....]

    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['vid']['type'] = 'integer';
    return $ids;
  }

}

Then you just need to use that plugin in your D6 migration:

source:
  plugin: custom_vocab_plugin


Can I create a view of watchdog log entries?

You're probably looking for Views Watchdog

  The Views Watchdog module extends the Views module and allows to create customized lists (pages, blocks, feeds) of watchdog entries.


Can I programmatically add a string to the translation interface?

Assuming that your question is in regard to translating a (custom) module or theme. In that case, I'm using the Translation template extractor to get all strings of a module/theme that are used in the t() functions. For more information about using this module, look at this discussion. Though a pretty old discussion, it's still very useful.


If you have date_popup enabled you can achieve the calendar part by using this:

$form['date_starting'] = array(
  '#type' => 'date_popup',
  '#title' => t('Starting'),
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-3:+3',
);

Then you can style the input field as a calendar button and use javascript to copy the date value to your date select.


how to add taxonomy vocabulary and terms through code

Rather than writing code, I use the Taxonomy CSV module.  It allows you to export and import taxonomy as CSV files.  You can use the module's user interface or do it by command line with Drush to speed things up even more.

Initial configuration can be a little tricky, but it's able to preserve tree hierarchies and order, etc. so a bit of complexity is to be expected.


Determine front page for specific language

Found it. It was in "Administration » Configuration » System" that I didn't set the default front page !