Custom tokens and/or text filters for consistent link look? I have a site with a range of products. In order to ensure an easy input for the content editor and a consistent look throughout the site, I thought I'd make an input filter that would replace any occurrence of

[prod:product-name]

with a link to the node presenting the product (product-name == product code here). On output, this would be changed into, say:

Real [product-name]

However, I have doubts as per the efficiency side of such a solution, namely because - product-name would have to be a value of a field on the content type. Thus, for each replacement, Drupal would have to comb through all nodes, load each of them and perform a test to find a match. Quite database-intensive as I imagine.

So another thought was to provide a custom token. But would that change anything? Would it work within text fields, or would I have to use hook_node_view_alter to invoke the replacements?

What would be your strategy to provide this kind of tokens?

You could implement an input filter, or implement hook_node_view_alter().

Keep in mind that an input filter is not only used for node's body, but also for comments, user's signature, some part of a view, and theoretically with any module that uses check_markup() and that also allows the user to select an input format to use. As consequence of this, input filters should not take assumptions about when it is invoked.

There isn't normally any performance issue for accessing a node's fields; Drupal uses caches to avoid executing queries when not necessary.

If you are talking about the tokens provided from Drupal 7, or from the Token module, you could also implement a token, but you should consider that a token is accessible not only in the context you are expecting it to use it.
You should still need code to replace the token in text, using an input filter (for which the previous notes are still valid), or hook_node_view_alter().

If you need to provide a token that should be accessible in a specific context (e.g. to be replaced in the body of nodes), you could use the code used by Drupal, which (in _user_mail_text()) uses the following code.

  if ($replace) {
    // We do not sanitize the token replacement, since the output of this
    // replacement is intended for an e-mail message, not a web browser.
    return token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
  }

user_mail_tokens() is the function that provides the custom token that should not be available in other contexts.

function user_mail_tokens(&$replacements, $data, $options) {
  if (isset($data['user'])) {
    $replacements['[user:one-time-login-url]'] = user_pass_reset_url($data['user']);
    $replacements['[user:cancel-url]'] = user_cancel_url($data['user']);
  }
}


How to move Contextual Links? Added a wrapper inside a block.tpl.php called block-content:

<section id="<?php print $block_html_id; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <h2<?php print $title_attributes; ?>><?php print $title; ?>

  <?php endif;?>
  <?php print render($title_suffix); ?>

  <?php print $content ?>

As you can see there is no sign of contextual links in it.

But if you look at the source, contextual links block is put inside the new block-content.

How to move contextual links block outside block-content one level up inside section so they both become children elements?

Goal is to separate block content wrapped in a separate container without contextual links because it interrupts a lot when it comes to CSS.

I got a solution with jQuery, but it's impractical on every page load for every block.

you can create multiple tpl.php files for blocks based on the specific block, the module that created the block.

  Clone block.tpl.php to "block--block--[block-id].tpl.php" file

after try code, I don't' encourage you to do this, but it maybe the solution for you:

<section id="<?php print $block_html_id; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

      <?php print render($title_prefix); ?>
      <?php print render($title_suffix); ?>
      <?php if ($title): ?>
        <h2<?php print $title_attributes; ?>><?php print $title; ?>

      <?php endif;?>
      <?php print $content ?>

=> Clear cache


How programmatically display the Image field before Taxonomy name in Better Exposed Filters? Third day I'm looking for a solution, but I can not find an answer.
I use Taxonomy term as a filter (Better Exposed Filters) on Views.
To Taxonomy term added a field image. How programmatically display the Image field before Taxonomy name in Better Exposed Filters?

I tried modules  taxonomy_icon, vocabulary image, taxonomy image
All of them do not provide an opportunity for filters Views to derive taxonomy terms in the form of "image taxonomy name".

I was prompted how to do it. Thanks a lot to xandeadx.

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

foreach ($form['TAXONOMY_ELEMENT']['#options'] as $tid => &$name) {
    $term = taxonomy_term_load($tid);
    $name = '<img src="' . file_create_url($term->FIELD_IMAGE['und'][0]['uri']) . '" />' . $name;
  }
}

In my version TAXONOMY_ELEMENT = tid_1


Assign ID to Main Menu I am working on Drupal 7 project (omega 4 subtheme) with panels and views. I need to assign ID an ID (id="nav") to a DIV that wraps main menu UL. It is a child of div.l-region--navigation. It's the second row of the example bellow.

Home

Home

Anyone knows how to do this? Is there a specific drupal way of doing this?

function mytheme_links__system_main_menu($variables) {
$site_frontpage = variable_get('site_frontpage', 'node');
  $html = "\n";
  foreach ($variables['links'] as $link) {
      if($link['href'] == '<front>') {
        $html .= "" .$link['title'] ."";
      }
      else {
        $html .= "" .$link['title'] ."";
      }
  }
  $html .= "\n";

  return $html;
}

The code can be used in template.php to override the output of the . However, the only variable it seems to accept is $tree, which prints out all the contents of a  and so is not very helpful.


how to fetch user related tables from live sever with drush sql-sync If you have a live server where some people have registered to your iste and you push new content from your dev,server regularly. What is the best workflow to fetch user related data from the server before you sql-sync and r sync an updated site to the live server with drush?

It is not recommended to push your database from dev to live.  Instead, push just the code from dev -> stage -> live, and pull the database in the other direction.

There are a number of solutions for moving content from dev or staging to live.  One option is the content staging module; other people use feeds to import new data.


How drupal.org found a website installed module I want to know how drupal.org counts the websites which use a specified module, as example in views module page reports:

Reported installs: 717,794 sites currently report using this module. View usage statistics.
Downloads: 4,815,869.

It is not hard to find the number of downloads but I want to know how drupal.org gets Reported installs?

Is there any way to find out the number of websites that use my custom modules that are not published in the drupal.org website?

Drupal.org gets 'reported installs' from the Update manager module. So to do something like that you would need you custom module to report back to a server of yours, and preferrably have your users be notified for that.


Pass value of a field to another content type in Drupal 7 I have a content type 'Exhibit' with fields 'uuid'(text with single value), 'name'(text with single value), 'description'(long text and summary), 'section'(text with unlimited values). I have used views to display 'Exhibit' in table format.

Now when i click on Add section. I want the field Section in Exhibit view to be uuid values in Section content type. I want the uuid values as a drop down . so that customer can select one uuid and enter the details for that uuid. How can i achieve this? Please help.

I think it would make sense if your 'exhibit' content type references sections, which are themselves nodes (through nid reference fields) or through a reference field on the section that points back to the exhibit.  Then you can build the view with relationships to look however you want.

The point of having everything be a node is that you can take advantage of a lot of built-in functionality, as well as a lot of contrib modules which are geared towards nodes.

So if you create the structure as I mentioned above, you can add sections to exhibits with this module: Node Reference URL, which allows you to automatically fill in the nid reference field.

Does that work?


Drush 9 pulling incorrect site information on Multi-site We have a multisite set up with Drupal 8.6.1 and Drush 9.4.0.  This is set up on two servers that were set up identically.

The issue we are running into is that Drush is only detecting defaultsite, no matter what directory we are in.

This is creating two issues:

On server #1 - defaultsite no longer exists.  Drush is still trying to use it's URI and DB variables, so is throwing an "unable to bootstrap the Drupal database" error, and we cannot run any database-related commands.

On server #2 - defaultsite exists, so it is able to run commands.  But, when we try to enable a module, it enables the module on defaultsite no matter what site's folder we are in.

Here is what drush status outputs (whe inside of the directory: gtest.ng.evenvision.com):

 Drupal version   : 8.6.1
 Site URI         : default
 DB driver        : mysql
 DB hostname      : localhost
 DB port          : 3306
 DB username      : defaultuser
 DB name          : defaultsite
 Database         : Connected
 Drupal bootstrap : Successful
 Default theme    : ev_base_child
 Admin theme      : ev_seven
 PHP binary       : /usr/bin/php
 PHP config       : /etc/php.ini
 PHP OS           : Linux
 Drush script     : /usr/bin/drush
 Drush version    : 9.4.0
 Drush temp       : /tmp
 Drush configs    : /var/www/nginx/vendor/drush/drush/drush.yml
                    /var/www/nginx/drush/drush.yml
 Install profile  : minimal
 Drupal root      : (removed)
 Site path        : sites/default
 Files, Public    : public
 Files, Private   : private
 Files, Temp      : /tmp

And, this is what settings.php for gtest.ng.evenvision.com contains:

$databases['default']['default'] = array (
  'database' => 'gtest2018',
  'username' => 'gtest2018',
  'password' => '54352432346greg433',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

I don’t know how your setup is now but you need to have something like this.

 sites/site-name-1/settings.php

Containing

$databases['default']['default'] = array (
  'database' => 'gtest2018',
  'username' => 'gtest2018',
  'password' => '54352432346greg433',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

And then the same for the other instances.

Then when you want to install a module in one instance run drush en MODULE_NAME -l site-name-1.

For more info look here: Multisite folder structure in Drupal 8.


How do I modify the individual links on comments (reply, delete, any others I add in Flags, etc...)? I'm in my sub theme's comment.tpl.php, and I have print render($content['links']) - how do I access the individual links within that?  I tried doing a print_r to see if it was a bunch of nested arrays - it appears it is(?) - but I can't seem to dig into those arrays to get the individual links?  I tried $content['links']['comment']['#links']['comment-reply'] for example (based on the structure returned form the print_r) to get just the reply link, but I get nothing.

Ultimately what I'm trying to do: Due to various modules and some flags I have 5 links on every comment: reply, delete, edit, flag, and like.  I want to group edit, delete, and flag (and any other future miscellaneous) into a little dropdown menu at the top of the comment.  Then put reply and like in individual styled buttons at the bottom.  I was planning to just handle the menu and buttons using Bootstrap since that's my theme base, but I can't "get to" the individual links to add the classes and markup I need.  Additionally I want to change the displayed text, capitalize Reply for example and add some inline icons for edit, delete, etc.

I've come across theme_links, but that page is over my head.  Sounds like maybe I need to understand this?  If so I don't even understand where to start to apply it - I searched across all files in my base theme (Bootstrap) and found nothing with that name to start from?

Where and how should I be trying to do all this?

thanks to your link to the theme_links i managed to solve my problems, so here's how i would solve yours.

the idea is to split the links in two parts, one to print before and the other after the content.

$group = $content['links']['comment']['#links'];
$plain = array();

if( isset($group['comment-like']))
{
    $plain['comment-like'] = $group['comment-like'];
    unset($group['comment-like']);
}
if( isset($group['comment-reply']))
{
    $plain['comment-reply'] = $group['comment-reply'];
    unset($group['comment-reply']);
}

$first = $content['links'];
$first['links']['comment']['#links'] = $group;
$second = $content['links'];
$second['links']['comment']['#links'] = $plain;

//before the print render( $content);
//note: apparently, you can't add a class to the <ul> element from here, so you should manually wrap it and fix your css accordingly
print '<wrapp class="something">'.render($first).'</wrapp>';

//after
print render($second);


Edit default views (books, basic page, etc) I am using Views 3 with drupal 7. Views provide you some default views so you can edit them and customize them.

I want to do the same thing, for example, with book pages. I don't want to start from scratch with a new view. I just want to edit the default view of book pages.

Is there any way of editing it ? Or should I go directly to the code ? If so, which code is it ?

You can edit any existing view. Go to the views list and click on enable button that you would see on the view that you want to edit. Then you would get access to go inside the view and make your changes.

Hope that Helps.

Best Regards
Shameem


How to inject the database connection into a custom service? I have a custom module that pulls data from several different external databases that have been defined as connections in settings.php. The current setup includes a series of controllers that have a service I have created called DataAccess injected into them. My DataAccess service has several methods that accept a $schema parameter and based on this I use the following each time:

$connection = Database::getConnection('default', $schema);

I can then query each database as needed with this setup. I thought about injecting Database into my service from the Drupal container, but I would then need a base class like ControllerBase's create method to get that service in the first place. What would be the correct way to do this as it isn't a controller - would I use a different base class here? I am new to Drupal 8 development and trying to ensure I am following the best practices, but at the same time I don't want to overcomplicate things.

Any advice?

You can't inject Drupal\Core\Database\Database, it's a container of static functions, constants, & variables for core database functions.

If you'd like to inject the Connection object, that is be possible, and is more like something you want (unless you have scenario where  setting.php is dynamic an all possible values of $schema can't be known).

You can follow the example Drupal sets with the default @database class in core.services.yml:

  database:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default]

In your mymodule.services.yml you can define the factory/arguments for each database connection you have, plus your DataAccess service class with the injected connections.

services:
  mymodule.database_schema:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default, schema]
  mymodule.database_schema2:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default, schema2]
  mymodule.data_access:
    class: Drupal\mymodule\DataAccess
    arguments: ['@mymodule.database_schema', '@mymodule.database_schema2']

From there you can store the database connections in DataAccess's constructor and reference them as required by DataAccess's methods.


Custom module access denied I just have followed two tutorials on Youtube, https://www.youtube.com/watch?v=79zYcIoheCc&t=43s and https://www.youtube.com/watch?v=SAP9clnOf9E&t=8s.

The result was a "You are not authorized to access this page." error.

In the routing file, I have made the correct indentation for both modules.

my_module.routing:
  path: '/admin/structure/my_module'
  defaults:
    _title: 'My module'
    _content: '\Drupal\my_module\MyModuleController::test'
  requirements:
    _permisions: 'access administracion pages'

hello_world:
    path: '/hello/world'
    defaults:
        _controller: 'Drupal\hello_world\Controller\HelloWorldController::hello'
    requirements:
        _permisions: 'access content'

You have a typo in one of the permissions. It should be “administration”. Permissions itself is also spelled incorrectly.

Please refer to the official docs for creating routes and links. YouTube videos may be out of date.


Preventing webform save Goal: Using webform (and it's hooks) in drupal 7 I need to, under certain conditions, avoid saving the form submission (i.e. under those conditions I need to discard the submission instead of saving it to submissions models or, if that's not possible, correctly reference the submission and delete it).

Question: How is that done? Either of the solutions would be fine for me. I didn't try anything yet, since I have no clue at all about how to do any of them. I can just barely imagine it should be done on _alter or _presave hooks, but I'm not sure, and can't find about.

Current state: Totally n00b and clueless about.

Notes: Assume hooks as:

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    //validations occur here to test whether the current form is a webform node.
}

EDIT - Additional IMPORTANT notes I forgot: Depending on the value of some fields, I have two possible scenarios:

Avoid saving, then redirect (to external URLs, i.e., urls not belonging to my Drupal install. The redirection url must be the result of an evaluated expression, and not just a single url which I could specify in the webform settings).
Save, then redirect (to internal URLs, i.e., urls belonging to my Drupal install. The redirection url must be the result of an evaluated expression, and not just a single url which I could specify in the webform settings).

yes hook_form_alter is the right hook you are looking for.

Something like below. Please check the values of form field inside $form_state and fix the code accordingly.

Basically hook_form_alter will allow you wo conditionally add submit handler to your webform which means if form field value is Y then only your custom submit handler will call, also the way we adding the custom submit handler is by replacing the other handlers so no conflict with your sudmit handler and any other comes by default.

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
   if($form_id == "your_webform_id") {
     if($form_state['your_form_field']['#value'] == 'Y') {
       $form['#submit'] = 'custom_submit_handler_external';
     }
     if($form_state['your_form_field']['#value'] == 'X') {
       $form['#submit'][] = 'custom_submit_handler_internal';
     }
   }
}

function custom_submit_handler_external(&$form, &$form_state) {
  drupal_goto("redirect to a page");
}

function custom_submit_handler_internal(&$form, &$form_state) {
  $redirect_to = $form_state['redirect_field']['#value'];
  $form_state['redirect'] = $redirect_to;
}

The above code is just an idea of how you can approach, please debug it at every step and make it workable for you.


Cannot change date input format in views exposed filter I am unable to change the date format for an exposed field in views. I am using BEF datepicker popup. I overrode the jquery settings to get it to enter a UK date in the dd-mm-yy format but because views is expecting it in mm-dd-yy form, the results of the filter are wrong.

This problem is addressed in this discussion https://www.drupal.org/node/1409120 but supposedly has been fixed for other people in Date 7.x 2.x. I am using BEF 7.x-3.0-beta4, Date 7.x-2.9-alpha1+2-dev, and Views 7.x-3.8, and the problem isn't fixed. I can't see any extra options in the view settings or in the config menu to change the date format.

The field name is field_activity_date_time and I have created a custom module with the following code, based on other stackoverflow suggestions (I don't have a max and min field, just a single date)

function hook_form_views_exposed_form_alter(&$form, &$form_state) {
    if($form['#id'] == 'views-exposed-form-test-page') {
       $form['field_activity_date_time']['#date_format'] = 'd/m/Y';
      }
    }
}

I have tried a number of different possibilities for the array key, such as 'activity_date_time', and 'views_field_activity_date_time', none of which worked. This date field is coming from a CiviCRM table which may be why the other suggestions haven't worked, but it feels to me more of a drupal problem than a civicrm one.

as suggested by harsh in the comments, I have used a different hook, but the problem still persists...

function HOOK_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page') {
     $form['activity_date_time']['#date_format'] = 'd/m/Y';
     echo '<pre>';
     print_r($form);
     echo '</pre>';
 }
}

This gave me the following

Array
(
    ...

    [activity_date_time] => Array
        (
            [#type] => textfield
            [#size] => 30
            [#default_value] =>
            [#attributes] => Array
                (
                    [class] => Array
                        (
                            [0] => bef-datepicker
                        )

                )

            [#date_format] => d/m/Y
        )
)

Well, I am not proud of the clunky fix but it works!

function gmcvo_date_format_views_query_alter (&$view, &$query){
    $newDate = DateTime::createFromFormat('Y-d-m H:i:s', $query->where[1]['conditions'][0]['value']);
    $query->where[1]['conditions'][0]['value'] = $newDate->format('Y-m-d H:i:s');
}

If someone has a better way to do this it would be great to hear it...

edited to use the new datetime object instead of strtotime


site-install error: /var/www/drupal7 does not contain a valid installation I am running on Windows 7 Enterprise and have done to following to set up my site:

Downloaded and installed Virtual Box VirtualBox-4.3.18-96516-Win.exe
Downloaded and installed vagrant_1.6.5.msi
Downloaded vdd-8.x-1.0-alpha4.zip
Extracted the zip file and copied the vdd folder to /Test so I have /Test/vdd as my vdd directory
opened a command prompt and went to /Test/vdd
Ran vagrant up and it seemed to work.
Accessed the vm by using vagrant ssh
Changed permission on all directories to 777 (i.e. chmod -R 777 sites and I verified that all directories are 777)
The drupal7 directory did not have a setting.php file. I copied default.setting.php from default directory to the drupal7 directory and named it settings.php.
Also copied settings.php to default directory so default has both settings.php and default.settings.php

Now when I run drush @drupal7 site-install -y I get the following:

  Command site-install needs a higher bootstrap level to run - you will
  need to invoke drush from a more functional Drupal environment to run
  this command. The drush command 'site-install' could not be executed.
  The directory /var/www/drupal8 does not contain a valid Drupal
  installation

A couple of things worthy to note is that my drupal7 directory has no files other than settings.php.
I don't know if that is the way it is supposed to be.
mysql is up and running.  If I run mysql -u root -proot it connects to the db.
I am assuming apache and php are working because 192.168.44.44 returns the proper landing page.

The Documentation shows the steps you should do are:

Start with empty directory and prepared empty database (or user with permission to create database)
drush dl drupal --drupal-project-rename=example
cd example
drush site-install standard --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]' --site-name=Example

You should not manually create, copy, move config files before executing drush site-install. And you should not use aliases like @drupal7 unless they are defined. In case of installation, I always set up site first, and aliass for it later, and it worked all right.


How can I update file attachment and keep filename? I understand changes of file attaching in D7, but problem is, if I delete and re-upload changed file, the deleted file is still on server and re-uploaded filename gets changed. If I understand correctly, removed file is deleted by cron, so there is a delay. Is it possible to get file deleted in real time, to avoid renaming of uploaded one?

It is not possible. If files were deleted "in real time", node your readers see would have a link and reference to a file no longer on server's hdd.

If you need to get the same file name, remove file, save node, upload new version, save node. That way you will avoid both broken links and name conflicts.


How do I create and synchronize product fields with entity fields on another site Case description:

I have one centralized 'Asset management' Drupal website "A" (something like a simple ERP site) which manages the administration of purchased Assets, being ECK entities. The assets are unique, no stock management required.

I also have a Drupal webshop "B" using the Drupal Commerce modules, which has Commerce Product entities.

Goal:

The assets and products need to be two-way synchronized between the two sites, in such a way that:

New Assets in site A will create new Products in site B.
Some fields (title, price, status) will need to be two-way syncronized (so that when a product is sold, the Asset status field will be changed)

Requirements

Preferably without custom coding, but using existing Drupal modules in combination with Rules to allow flexibility in configuration.

Question:

What would be a good approach in this case? Preferably without custom coding.

My current investigations:

There are multiple ways to construct a non-coding contributed module combination to get the result needed. My preference is a lightweight but configurable solution using Rules. I checked out these modules:

Services module: Without other modules this requires custom coding to import and sync entities. Most services-based modules are dependent on it.
Web Service Data module, This module allows you to bypass the default data storage location for fields and entities and instead load the data from a web service. Does not import or sync. Probably not suitable because the entities are not identical (assets and products)
Remote Entity Api module but this might not be the
most efficient way because that module creates local copies of the
remote entities. This means that in site B there would exist also the
same amount of asset entities as in site A, which are synchronized
with the Product entities.
Feeds module allows one-way import and sync, could be two-way but probably complex.
The Migrate module: large framework, is a developer's tool, must have
php skills.
Services Client module the UUID needs to be inserted per entity? Not for many entities.
Service Rules module creates endpoint for Rules Components.
Requires a services client module. Might be of use (optional, see below)

[UPDATE MAY 30 2016]

According to my research the following modules combined, will likely be the most lightweight and configurable solution. I take into account that this case is not so much about migration of data, but about creating and updating using rules triggers and actions (as per the requirements).

Web Service Client module is made to consume services without custom coding. It integrates with Rules to perform the required actions.
Web Service Client for Feeds integrates the Web Servcice Client module with Feeds, which allows for a cron-based import of created or changed entities.
Sevices Views module: in order to create a view of the assets
fields that need to be created or updated.

TO DO:
The suggested approach mentioned above needs to be tested in order to prove that it works. I still don't quite understand how to configure the Web Service Client module configuration of the 'REST service descriptions'. Probably because I am a newbie to services. In order to figure that out, I posted a question about it. I will add screenshots to that where needed.

For those answering this BONUS question: The answers have been rather broad up to now. Using the abovementioned update (may 30) please provide specific support for the solution suggested by me using the Web Service Client module configuration. This allows me to choose who gets the bonus. You may answer in the connected question in order to keep the answers on topic per question.
I have also created two test sites with the modules installed and can provide admin login details if you want to test it out, or help me out with the configuration.

I'll start with saying, you should throw your "no custom coding" requirement out. That's not to say it's not possible, but it's going to require you stitching a patchwork of solutions that might drive you to conflicting or cumbersome processes. Every data migration problem, save for the most basic (e.g. migrating content title & body nodes), will have key details and rarely has pre-made default path in Drupal.

You don't want a patchwork solution to a detailed problem like this; it will be difficult to manage if you find  your future requirements or key module assumptions change in the future. Rather, you should rely on a few key tools to handle some big needs, and fill in the rest with custom code that leverages either Drupal's or contrib module's APIs.

You have 2 broad requirements. I'll list an outline of one approach.

An ETL solution between a new custom asset entities on Site A and commerce product on Site B.

You should, from the start, utilize a shared UUID on your asset entity & Commerce product; the alternative here is having some sort of shared PK mapping between sites that could have all sorts of problems.
The go-to-solution for Drupal data ETL is the Migration framework that allows you specify how to map fields, transform them if needed, and place them into your migrated destination. The duplicate insert problem is solved with UUIDs. Commerce Migrate provides extensions specific to the Commerce project.
You'll need to determine when/how such a migration sync will occur. A solution will need to be driven by your own workflow. As such, there's probably no one-size-fits-all solution here (e.g. if assets are periodically added on scheduled date a simple cron job to migrate products in might suffice a real-time requirement might require some RPC solution).

Data Field syncing.

You should rely on Serivces (as you have mentioned) and Services Entity API to provide CRUD transport. This will allow reliable data push/pull when you need it. Additionally, it could be the framework for providing a RPC service endpoint in the event you want to trigger an asset-to-commerce migration on site B from site A.
Just like with asset-to-product ETL, your sites' workflow is probably going to determine the best course of action. It could work with Rules (with a module provide custom conditions & actions to determine when to sync up via REST) or perhaps a simple custom module running a cron job.

In short, don't rely on a patchwork of module projects to somehow solve the problem for you through trial-and-error. Pick key tools that solve one single problem well (e.g. ETL, HTTP data transport, unique identification) and use your custom code to supply the logic that's unique to your use case.


How to apply css to all pages in custom module I have created one custom module in drupal-7. I want to apply same css to all pages belonging to that module.

I am able to apply css to one page by using drupal_add_css() but not able to do for all pages.

In module's info file, add following line:

stylesheets[all][] = folder/module.css

Substitute folder with a name of subfolder within your module you keep your CSS files in (or remove it). Repeat for all CSS files you need.

More about info files in the manual on Drupal.org.


How to limit users to posting 1 node per a day? I am making a diary website, where users can make a daily diary entry. A node acts as a diary page, so naturally I need to limit the user to make 1 node per a day. How can I do this?

Steps I have tried

Using Node Limit

This contains an option for 1 node per a day. But in fact, it is 1 node per 24 hours. So if my user makes a diary entry at 3:00pm, they have to wait until 3:00pm the next day until making the next one. Because it is diary, it would be better if the limit reset at Midnight every day, but there doesn't seem to be a way of doing this.

Using Rules

The problem with Rules is that you have to fire off the rule on Node Creation. This creates a usability issue, as my user will finish their (unallowed second) diary entry before being told that it is not allowed.

Check the answer here:
Denying access to node form edit.
Deny access to user by checking whether he has created a node the specific day.

function MYMODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($type == 'my_type' && ($op == 'create' || $op == 'update')) {
    my_module_check_if_user_has_published_content_today($account);
    if ($account->something == 'something') { // allow access
      return NODE_ACCESS_ALLOW;
    }
    else {
      return NODE_ACCESS_DENY;
    }
  }
// Return the default ignore value if your module doesn't need to get involved in this decision
  return NODE_ACCESS_IGNORE;
}

You should implement the select query that loads all nodes for the specific user on the specific day. You need to join node and user tables. Every node has a UTC value of the creation date. You can check if there is a node that was created after 00:00:01 and 23:59:59 in the specific day.


Save an article or story on Drupal 7 How can I save an article or story on Drupal 7?

Is there any modules to install, or do I need to do it programmatically?

Note : This is not offline bookmarks kind of stuff, nor is it related to browsers.

What I understood from your question and comments, you are looking String Overrides module.


Services Views module no longer maintaines. What are my options? My site relies heavily on the Services and Services Views modules. The Services Views module is no longer being maintained and it has a security vulnerability in it. Could someone help me either identify what the security vulnerability is. Or point me to a decent alternative module?

The Views Datasource's sub module called Views JSON is what I would recommend: https://www.drupal.org/project/views_datasource

It's very similar to Services Views, except you just create a "JSON Data Document" Page Display for your View, and specify a Path at which the View can be accessed.


Create a RSS feed of file attachments to a particular node I am looking to create a RSS feed of file attachments, filtered by the node they are attached to.

for instance the feed URL would be:

node/253/rss-attachments.xml

where 253 is the node ID in question. Using views 3 + drupal 7 I am able use 'files' as a base table, and create a list of files with a contextual filter of node ID, however upon adding the RSS display it complains saying:

  Style RSS Feed requires a row style but the row plugin is invalid.

I have the feeling that a custom row style plugin is required here. Does anyone have any ideas as to what options exist now for solving this issue?

Thanks

You can use Views RSS module for creating complex feeds with Drupal Fields. The module provides a lot of RSS settings:

RSS format plugin “RSS Feed - Fields” with settings
Support for core fields.
Enclosure elements

The result can look like this:


change order of shipping services in checkout I build two Shipping services in a drupal commerce shop. One with calculated rates. One with 0€ for pickup by the customer.
It looks like this:

But i would like to change the order and make shipping service with costs as default.
I tried to change the wight of the calculation rules, but without effect.
Is it true, that I need a module for this task?
It would be no problem, but I don't won't to overlook a easy solution.

Unfortunately, there's a pending feature request to make these orderable via the user interface, but in the meantime you're dependent on code to change their ordering. The hook to use is hook_commerce_shipping_collect_rates(), and what you need to do is alter the weight value of the line items in the $order->shipping_rates array.


Separate 403 path per role? On admin/config/system/site-information, one can specify "Error pages" for 403 (No access) and 404 (Page not found).

It would make a lot of sense to specify different pages here, depending if you are logged in or not.

Currently my idea is to show my custom login + registration page for anonymous users, but something else (not sure yet) for logged-in users.

Is there any solution for this in contrib?

You can work with panels as suggested in the above comment.

Without panels nor any contrib module you can show blocks limited to roles on the specified error node. Review the blocks settings.

Maybe you need multiblock to place blocks several times.


How to store user meta data? I've seen that it was possible to store custom meta data in Drupal 7 but I didn't find the equivalent for Drupal 8 ?

https://martsie.github.io/2015/03/04/drupal-how-to-use-user-data/

The data that I need to store is temporary user data that might differ from each users and it's not needed to put it as field (no sql query needed).

You can use the user.data service

\Drupal::service('user.data')->set('mymodule', $uid, 'some_key', 'some_value');

You can then retrieve it with the same service:

$some_key = \Drupal::service('user.data')->get('mymodule', $uid, 'some_key');


How do I restrict uploaded images to a specific aspect ratio? What I would like to do is, using the Image field in core, to restrict uploaded images not just on resolution, but also on aspect ratio.

In other words, the image must be 2:3 width to height, and at least 200 by 300 pixels.

I know that Image Styles can manipulate the way an image is viewed. I'm not interested in that. Rather, I want to restrict uploads the same way that you can currently set min/max settings for resolution, I want to add aspect ratio.

My guess is that I'll need to write my own module to add a new check to Image's checks, but perhaps you know of a simpler way.

My advice would be to implement a custom file validator.

To see how these are used when saving files, you can check out file_save_upload. For an example implementation that is very close to what you want to achieve, check out file_validate_image_resolution.

My super quick attempt at this

/**
 * Validates an image upload as having a particular aspect ratio
 *
 * @param $file
 *   - the uploaded file
 * @param $aspect_ratio
 *   - the apect ratio in the format [WIDTH]:[HEIGHT]. E.g. '3:2'
 */
function file_validate_image_aspect(stdClass $file, $aspect_ratio = 0) {
  $errors = array();

  // Check first that the file is an image.
  if ($info = image_get_info($file->uri)) {
    if ($aspect_ratio) {
      // Check that it is smaller than the given dimensions.
      list($width, $height) = explode(':', $aspect_ratio);
      if ($width * $info['height'] != $height * $info['width']) {
        $errors[] = t('The image is the wrong aspect ratio; the aspect ratio needed is %ratio.', array('%ratio' => $aspect_ratio));
      }
    }
  }

  return $errors;
}


How do I exclude the current user from the search? In a normal Views user search, you can simply add a User: Current filter to remove the logged-in user from the search results.

I have a Search API Views search of a Solr index of users, and I want to do the same thing.  However, the User:Current filter is not available.  How can I achieve the same function?

You could write a simple module using hook_views_pre_view.

Be sure to index the User ID
Under Filter Criteria, add Indexed User: User ID, and set it to NOT EQUAL TO and use 0 (anonymous user, which will never be in this list).
Using MY_MODULE_views_pre_view with the global user value, replace 0 with the UID of the current user.

function MY_MODULE_views_pre_view(&$view) {
  global $user;
  if ($view->name == 'VIEW_NAME') {
    if ($user->uid) {
      $view->display['default']->handler->options['filters']['uid']['value'] = $user->uid;
    }
  }
}


views slideshow: display multiple items but scroll only one item at the time i'm using drupal 8 and slideshow module to create a block of slides (fields with images and descriptions to it) to put it on some pages.

I have managed to show slides horizontally and they scroll nicely but problem is how to show 4 slides and scroll only by one at the time.

In setting for slideshow there is an option "Items per slide" if i use it and put 4 - i will get 4 slides on an block but it will scroll 4 items at time.  If i put 1 - it will scroll one item at the time but will show only 1 slide and need 4.

plus to all that it should be responsive if only 3 slides can fit on the screen it should show 3 slides and scroll only one by one.

I'd suggest using the owl carousel module from Git hub for responsive slide shows.  It has lots of options to define how many slides based on breakpoints, support for mobile touch events, number of slides per next, and more.

We've been using it since 8.0 without a problem.  Note that despite the Readme, the author has released it under GLPv2.  See issue #4.

There is a cleaned up pull of this project as well.  I have not used this but it may be a slightly better alternative.

Just install the module as a manual module or you can add the git hub repo as a repository in your composer.json and install it via composer.  Once enabled, change your view format to Owl Carousel and then use the settings to define things.


Multisite and symlinks doesn't work I just tried to implement Drupal Multi site installation with the link 2 Minute Multisite With cPanel. We found Warning: symlink() [function.symlink]: File exists in /home/ioss/ashokks/sites/test1/index.php on line 5. We are trying to installing the below domain http://test1.ashokks.com/index.php, i have already setup Drupal 7 in ashokks.com, and we add sub domain test1. We want a Multi drupal site test1, with the sub domain of ashokks.com

Thanks in advance

I fixed it by changing the folder name test1 in sites to test1.ashokks.com, following what reported in this question.


How can I show all registered users per event in Calendar? I am using Entity Registration together with Calendar. I'm trying to list all registered users in the event, but I don't know how to configure the view properly. Take a look at this image:

I only want one listing of the event and then all the registrants inside that entry. Now it lists one event per registrant.

The view is like this:

I figured this out by creating a seperate view for registrants and then with the module Views field View I could show that view inside the Calendar view


How can I let a plugin depend on another module? Is it possible to let a plugin depend on a module (other than the declaring one)?
Use case: I want to create a field widget plugin that should depend on the 'date_all_day' contrib module, but I don't want the entire declaring module depend on this.
Is it possible to declare this in the annotation?
E.g.
/**
 * @FieldWidget(
 *   id = "my_daterange",
 *   label = @Translation("Date and time range + All day"),
 *   field_types = {"daterange"},
 *   dependencies = {"date_all_day"}
 * )
 */
class MyPlugin {...}

The plugin should only become available if both the declaring module and the dependency module are enabled.

Yes, this is possible.
You may declare a dependency on a module by using the "provider" key in the annotation. For your example, this would look like:
/**
 * @FieldWidget(
 *   id = "my_daterange",
 *   label = @Translation("Date and time range + All day"),
 *   field_types = {
 *     "daterange"
 *   },
 *   provider = "date_all_day"
 * )
 */
class MyPlugin {...}

Note that you can only list ONE provider, but of course that provider module can depend on other modules ...
This is a feature added to the DefaultPluginManager in order to allow plugins to declare a dependency on one (and only one) module. This only works for plugins that use a plugin manager derived from DefaultPluginManager.
Specifically, @FieldWidget plugins are managed by the WidgetPluginManager, which DOES subclass DefaultPluginManager, so this will work. (Most, if not all, core plugin managers subclass DefaultPluginManager.)


Error in Submit handler for custom node add form Trying to theme my own node add form with hook_theme() in my own module. In the *.tpl.php page for the node add form, submit button is not actually adding the content to database.

Issue: Why is "php print render($buttons);" not adding the right submit handler that actually adds a node (Content) entry.

In my stories.module file:

 /* Implements hook_theme().
 */
/*
function stories_theme($existing, $type, $theme, $path){
  return array(
    'stories_node_form' => array(
      'render element' => 'form',
      'template' => 'stories-node-form',
      'path' => drupal_get_path('module', 'stories'),
    ),
  );
}
*/

function template_preprocess_stories_node_form(&$variables){

    $variables['sidebar'] = array();   // Put taxonomy fields in sidebar.

    $variables['sidebar'][] = $variables['form']['field_tags'];
    hide($variables['form']['field_tags']);

    // Extract the form buttons, and put them in independent variable.
    $variables['buttons'] = $variables['form']['actions'];
    //hide($variables['form']['actions']);
 }

In stories-node-form.tpl.php:

    <?php //print drupal_render_children($form); ?>

        <?php print render($form['field_nicname']); ?>

        <?php print render($form['field_email']); ?>

        <?php print render($form['title']); ?>

        <?php print render($form['field_category']);  ?>

<?php print render($form['field_share_your_story']);        ?>

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

Found the solution. Needed to add print drupal_render_children($form); to the end of stories-node-form.tpl.php


How to create a view of Media images that do not have any Alt Text For accessibility purposes I want to create a view of Media images that do not have any Alt Text.
Creating a view of Media images and also displaying Alt Text is not difficult, as explained is this d.o post Media alt text not available in Views
However I do not know of a way to create a filter of 'Alt Text is NULL' so that a view can be built which only returns images without alt text.
Any suggestions for how could this be accomplished? Ideally this would be a view of media entities so that other filters relating to media can also be used.

There is the Filter called Thumbnail (alt) from the Media Category that is for the Alt text.
After you add the Relationship for the Image field the Is empty (NULL) Operator will become available. If the Relationship is not present only the string operators will be listed.
Add the Relationship image from field_media_image and then add the Thumbnail (alt) Filter with the Is empty (NULL) Operator.
It will filter out Media items that have the Alt field available in their structure but not filled in (empty), for example images, as opposed to Files that don't come with Alt fields in their structure.

On the other hand, using the Is less than 1 Operator/value combination can help in situations when you need to filter out different Media types to show the items that don't have the Alt field in their structure at all like File types, while Images with empty alt don't satisfy that condition.


How to use (reference) the uploaded file to a media(video) type? I have read https://www.drupal.org/node/2941420 and I can upload a image file then use it in article.

But I can not use it as video field after I upload a video file.

My Drupal version is 8.6.0-beta2.

I use the media type ( Drupal 8 core module) for my video field, this is a Entity reference.

When I use

POST  http://www.myhots.com/file/upload/media/video/field_media_video_file?_fo...

I get the response as the end shows (the fid =47)

{
    "message":"Unprocessable Entity: validation failed.
field_user_video.0.target_id: The referenced entity (media: 47) does not exist.
"
}

Then I use it :

curl -X PATCH -H 'Content-Type: application/json' -H 'X-CSRF-Token:YYYYYYYYYYYYYYYYYYYY' -H 'Authorization: Basic XXXXXXXXXXX=' -i 'http://www.myhost.com/node/5?_format=json' --data '{

"type":[
    {
        "target_id":"user_video",
        "target_type":"node_type"
    }
],
"field_user_video":[
    {
        "target_id":47,
        "target_type":"media"
    }
]

}

The response is as follows:

{
    "message":"Unprocessable Entity: validation failed.
field_user_video.0.target_id: The referenced entity (media: 47) does not exist.
"
}

Which information should I use to patch it? It seems that the "fid" is not correct.

Maybe I need  "target_id " of "media“， but there is no response after I upload a video file, any suggestion?

"field_user_video": [{
  "target_id": 3,
  "target_type": "media",
  "url": "\/d86\/media\/3"
}]

'

{
"fid":[
    {
        "value":47
    }
],
"uuid":[
    {
        "value":"cf69fac4-5ba2-4861-9cce-a959dee3c480"
    }
],
"langcode":[
    {
        "value":"en"
    }
],
"uid":[
    {
        "target_id":1,
        "target_type":"user",
        "target_uuid":"c2b09ff8-345a-43fa-b9ae-68af0c9cd3ea",
        "url":"/d86/user/1"
    }
],
"filename":[
    {
        "value":"example2.mp4"
    }
],
"uri":[
    {
        "value":"public://2018-08/example2.mp4",
        "url":"/d86/sites/default/files/2018-08/example2.mp4"
    }
],
"filemime":[
    {
        "value":"video/mp4"
    }
],
"filesize":[
    {
        "value":6320348
    }
],
"status":[
    {
        "value":false
    }
],
"created":[
    {
        "value":"2018-08-31T03:04:20+00:00",
        "format":"Y-m-d\TH:i:sP"
    }
],
"changed":[
    {
        "value":"2018-08-31T03:04:20+00:00",
        "format":"Y-m-d\TH:i:sP"
    }
]
}

after two days trying , i find the solution myself.
shortly ,

first,  post file , get the fid.

second, post a media , get the Mid (media id)

third , post a node ,use the Mid

I omit the second step.


search_update_totals() is not invoked / or search_cron() is not invoked I don't know when, but this is new: in my Drupal 7 installation the indexing of search terms doesn't work anymore.

Here is a trace, but don't know how to solve it:
it seems that in /modules/search/search.module the search_cron() is not invoked anymore. And that is why necessary inserts in the database table search_total are ommitted.

Any ideas?

Thanks
Selim

In some circunstances, you need to call search_update_totals() after indexing. The reason is that you need to make sure that it runs from the same location that you ran search_index, and after it.

In theory it is always called when you index using a cron job, but I am indexing with a drush command and I had to call it manually at the end. If the cron run failed it won't be called.


Node creation PHP – menu item under proper parent while I create node by PHP, I use this:

$node->menu['enabled'] = true;
$node->menu['link_title'] = $node->title;

but it puts link in 0 depth of the menu. It doesn't care for "Default parent" selected for content type. Neither this works:

$node->menu['parent'] = "menu-global-menu:961";

How to select parent then?

It looks like you need to set $node->menu['plid'] = "961"; to set the parent node.

You can have a look through the menu_link_save doco to get an idea of what is going on, or there is a smaller code snippet on this blog that explains in a simple, fast way.

As a side note, you can use node_object_prepare($node); to set default values after setting your node type, which should take care of your default menu parent. I've found this guide helpful with programmatic node creation.


So many users and their access I am developing a site which has around 46 departments and each dept has three Access types. Say Dept Admin, Dept Lead, and Dept Agent.

Site will use taxonomy terms Confidential, Restricted, Private and Public. Rules goes like this..

Dept Admin has access upto Confidential level records, Dept Lead->upto Restricted, Agents upto Private records.
dept records should be accessible by only that dept users and goes its content moderation
I am planning to use taxonomy access control along with Workbench Moderation. But this requires me to set up 46 * 3 (138) roles for my site. I am a bit concerned that it might reach some php memory limit, not sure.

Any advice is appreciated.

finally went with duo Organic Group + OG Taxonomy permission modules


How can I debug entity queries in Drupal 8? Is there an out-of-the-box solution for printing the query of an entity query in Drupal 8?

Right now I'm using kind of a hack, adding:

->addTag('debug')

and then in a custom module:

function mymodule_query_alter($query) {
  if ($query->hasTag('debug')) {
    mymodule_query_debug($query);
  }
}

and then the debug function:

function mymodule_query_debug($query) {

  $sql = (string) $query;
  $quoted = array();
  foreach ((array) $query->arguments() as $key => $val) {
    if (is_array($val)) {
      $val = implode(', ',$val);
    }
    $quoted[$key] = \Drupal::database()->quote($val);
  }
  $sql = strtr($sql, $quoted);
  $sql = str_replace('}', '', $sql);
  $sql = str_replace('{', '', $sql);
  print_r($sql);
  die();
}

For Drupal 8, there is the Devel module and the Web Profiler module. The latter module, once enabled, installs a toolbar at the bottom of the page for users with the appropriate permissions. The database button within this toolbar takes you to a inspection page that shows all database queries executed during the last request.

If you're able to trigger the entity query through any browser request, you should be able to inspect the list of DB queries for the specific entity query you're looking to debug.


How to use views exposed filters in d8? I have a view like as follows using exposed fliter fields in d6 , how can i recreate like that in d8 ?

Here the from date and to date is to be selected and result will come accordingly

for the date . Here the date field is exposed filter .

view page :

and in view

How can i recreate a form like this using view in D8 ?

For the same purpose in d8 i have only this option : Any help is appreciated .

1) Checkmark ☑ expose filters

2) Select Single Filter

3) Select is between

which will result in

Unfortunately there is no way to do it in drop downs like you have it until the better exposed filters module gets ported.

Well you could do it in Drop downs using Group Filter with is between, but you would only be able to do it by year only though.


Where is the documentation for the ACL module/api? Has anyone successfully created a client module that controls node access via the ACL module? I installed this module and created my own UIs to populate the three tables: acl, acl_node and acl_user. I started to create nodes, which populated acl_node with appropriate values, but nothing else seemed to happen. No new realm in the node-access table, nothing. Have I missed a step? I can't find any documentation on this module/api. Thanks.

The notes in the nodes_access_example module (part of the examples project) encourage you to 'read up' on the ACL module. I can't find anything to read though.

If you take a look at the ACL project page, you'll see that the following four client modules exist:

Content Access
Flexi Access
Forum Access
Image Gallery Access

You'll find plenty of examples on how to use the API in the source code of those.

The documentation for ACL are the comments embedded inside acl.module.  They are quite helpful when you try to create a client module.

P.S.: I am the maintainer of Flexi Access.  I can verify that ACL works as advertised.


Block visibily condition programatically I want to display a block I implemented in a module when $_SESSION['Group_id'] is set.

How can I achieve this?

In the block ::build() method, return an empty array() if the condition is false.


Body field of some nodes not displayed in teaser view Some of my nodes have an empty teaser field so when I visit a taxonomy page, you cannot see any of the body content. Only when you click on the node title to view the full node can you see the body. Why does this happen? I fix this by manually editing my database and adding content to the teaser field of the node_revisions table but it's troublesome to fix nodes this way.

This problem might be related to the WYSIWYG editor you're using. Some of them output a lot of redundant code, so you don't get anything or a bunch of white space before content on teasers. Try using the 'Edit summary feature' that comes with Drupal corer to fine-tune teasers (or you could always have a new teaser text field). Most of the WYSIWYG editors come with a Teaser button, so you should use that.


Modify the links included in the user menu On a base Drupal install, there are 2 links included in the User Menu, My Account, and Log Out. I want to modify the My Account link to be expanded, and modify the Log Out link to be a child of the My Account link. How can I do this?

I've tried:

function MODULE_menu_alter(&$items) {
  if (isset($items['user'])) {
    $items['user']['expanded'] = true;
  }
}

To at least set the My Account as expanded, but that's not working (ie. not setting the expanded property to true). And I don't know how to change the parent of the Log Out link. Preferably this could all be done without a database request.

EDIT:
I recently succeeded a little bit in using:

function MODULE_menu_link_alter(&$item) {
  if ($item['link_path'] === 'user' && $link['module'] === 'system') {
    $link['expanded'] = 1;
  }
}

That modifies the My account link to be expanded, but I still can't seem to modify the plid of the logout link ('user/logout').

Tested:

Go to yoursite.ca/admin/structure/menu/manage/user-menu
Click the edit button for "My account (logged in users only)"
Check the "Show as expanded" box
Click Save
Click the edit button for "Log out"
Select "My account" under the Parent link

Click Save


How can I 'trim' the users returned by a user reference fields' autocomplete widget? By 'trim' I mean that I want to restrict the usernames returned according to some criterion. For example, if I enter 'S' into my user reference field, I want the drop-down list to contain all usernames begining with 'S' and where, for example, the users favourite color equals 'Red'. 'Favourite color' would be a field added on to the user entity.

My first idea is to use hook_query_alter to add a condition clause to the relevant query in user_reference module, but I'm not sure if this is possible. Has anyone done something like this before?

Thanks

You can use hook_form_alter() to provide your own autocomplete path. After that you can code it just like if you were creating brand new autocomplete field. Examples for developers module contains pretty solid autocomplete example, use it as a reference.


Access denied on register form I wanted to edit my register menu link so I could show the registration link in the menu account only for anonymous user (not logged in users). But when I try to edit the register menu link the following error occurs:

Access denied
Home >> Administration >> Structure >> Menus
You are not authorized to access this page.

The link I'm trying to access supossedly

localhost/admin/structure/menu/item/8/edit?destination=/admin/structure/menu/manage/account

PS: I created a new registration form and in that one I could edit and show the the link in users menu only not logged in users but in this one I can't access even I have an admin role.
Log message:

Please visit to the permission page- /admin/people/permissions page and scroll down to check menu permissions for administrator and allow the checkbox to create and edit menus, check the checkbox for Administrator menus and menu items. It is checked by default, but in your case you can verify it.
Also I have seen your localhost link has a missing foldername, should be like this-
localhost/foldername/admin/structure/menu/item/8/edit?destination=/admin/structure/menu/manage/account


How to add twig template for OwlCarousel format? I am working with drupal8. I have created a views with owlCarousel format.I want to add twig template for this carousel views.How to name this twig template?

You need to rename it like this: owlcarousel-views--expert-talk.html.twig


Theme overrides for custom hook_theme() in Drupal 7 I have a custom D7 module which defines it's own hook_theme() which defines a few theme functions, of which they define their own template, for example:

function foo_theme($existing, $type, $theme, $path) {
    $items = array(
        'post_foot' => array(
            'template' => 'templates/post_foot',
            'variables' => array('node' => (object)array())
        )
    );
    return $items;
}

As you can see, it defines it's own template, which is located in the foo module, in this specific case sites/all/modules/custom/foo/templates/post_foot.tpl.php

I'd like to be able to define my own post_foot.tpl.php in my theme, and use foo's tpl as a fallback.

Does this happen automagically? Do I need to expand my hook_theme() to include overrides?

This should happen automatically. Most core modules define theme hooks which you wouldn't think twice about overriding in your theme. Take a look at node_theme for example http://api.drupal.org/api/drupal/modules--node--node.module/function/node_theme/7.

The devel themer module should help you out with such things. Needs some work for D7 but should help.


How to mass copy the title of each node to a taxonomy term? I need to copy the title of nodes to its taxonomy term.
I have the following content type

Title - text
Body - text
Taxonomy term - (currently empty)

I want to copy the "Title" ---> "Taxonomy term" for each node.How can I do this?

I understand that VBO with som php-snippet could solve this but I am no programmer. Any suggestions about a working snippet or other solution?

You could use a combination of the Rules module and the VBO module to create a custom rule component, which you then use as a custom VBO action.

For way more details on this combination, have a look at my answer to "How to bulk update select list fields?".

In your case, the custom Rules Component should look pretty similar to this:

{ "rules_set_an_initial_value_for_a_term_field" : {
    "LABEL" : "Set an initial value for a term field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_yourfield" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-yourfield" ], "value" : "HereGoesTheTitle" } }
    ]
  }
}

Some more details to further explain the above example:

adapt the machinename of field_yourfield to the machine name for your taxonomy term field.
replace the (hardcoded) HereGoesTheTitle value in the Rules Action by the token like node:title (which for sure wil be available).
I'm assuming your taxonomy term is a single value field, if it is a multi value field, then replace the action with a similar one to "Add an item to a list" (related to your multi value field).

PS: no need at all for any custom PHP code when using this approach.


Is it possible to configure read count from Statistics module? I am using Blogs in my website, so I want to display the read count of each blog when user viewed the blog. For this I used core module called Statistics. But my requirement is differ from this available feature of Statistics module.

I want to Pre-set the read counter, So that I can manually enter the number of read counter. For example if I enter 100, next count should start 100 onward like 101,102... So how can I achieve this, Please suggest any module or programmatic way to achieve this.

You can add a count field to your blog content type, ban access of editing or creating this field using Field Permissions for other users (they just can read) now you can set its starting value.

Then using Rules module you can create an action in a way that with each viewing of blog posts this fields value increase by one.


Insert a Views Block into a node in Drupal 7 [Drupal 7]

I have a block I created in Views called "handy_tips-block_1".

Now I want to insert it into the body field of my node.

How do I do this?

I found a guide on here, which suggests to use the following code:

<?php
print $block = module_invoke('views', 'block_view', 'handy_tips-block_1');
print render($block['content']['#content']);
?>

However, all what is printed out are the words "Array".
(I have enabled the PHP input filter for the body field).

Note: in the posted code, I have also tried substituting 'views' with various items such as "block". I have used 'handy_tips-block_1' as the ID, because that is what is displayed on the configuration link of the block administration page.

Output is "array" because indeed is an array, then I guess that you want to print your array to see what fields you can use:

print_r($block);
print_r($block['content']['#content']);
print_r(render($block['content']['#content']);

About display a View, you can use this line of code inside your template, to call a view:

echo views_embed_view('view-name', $display_id = 'display-name');

for example, inside my node.tl.php I want to insert a view called test view and I want to use his Block display with machine name block_test, then I can use:

echo views_embed_view('test_view', $display_id = 'block_test');

(Remember to use the machine name of your view and machine name of your display).

I hope this information will be useful.


safest way to redo aliases So a site in production wants certain aliases to be redone. If there's another way to do this other than Home » Administration » Configuration » Search and metadata » URL aliases > Delete aliases, please let me know. I dont want to run that if it's going to break the site since it is in production. I can always rebuild using Bulk Update > Content Paths after Delete aliases . Please advise. Thanks.

You'll find "Update URL alias" as one of the choices for bulk operations for nodes under admin/content

This way you can select which specific nodes that needs URL aliases rebuilt instead of deleting and rebuilding all.


Display field collection items by using twig I'm using the field collection module in Drupal 8 to encapsulate event informations so I've got a field collection with six sub fields (place, starting time, etc.).

In my twig template field--field-event.html.twig, I'd like to extract each item of the field collection and bring it separately to the view - but I can't figure it out. What's the right way to get the content of each field collection item and process it individually?

{% for item in items %}
  {{ kint(item) }}
{% endfor %}

Iterating through the field collection with above code gives me an impression that the field collection items have got a content (with #markup) and attributes but how do I get to the core/values of the field items?

That is not a good idea to use kint() to collect the values somewhere in #markupkeys or other render elements. You can get the values from the field object, which is in a field collection an entity which then refers to the children fields. But if you use field collection, you should try first to use the theming, that is provided by this module. That is configure the format of the field collection in ui and then look in twig debug for the templates that are used by doing this and modify them.


Twig cache won't disable I've set up my development setup and it works great but for some reason I can't get the twig cache to disable. I tried everything, but I have to run drush cr every time I change anything in twig templates, and it's driving me insane.

settings.php:

if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

settings.local.php AND setting.php:

$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

$settings['cache']['bins']['render'] = 'cache.backend.null';

$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

services.yml AND development.services.yml

parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    debug: true
    auto_reload: true
    cache: false
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

I am running Drupal 8.4

In Drupal 8.4 you have to set the null cache backend for an additional cache bin, so now there are three:

settings.local.php:

$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

This is because the cached pages for anonymous users moved to a separate cache bin, see the change record The internal page cache now has a dedicated cache bin.


Adding sub menu to Management menu I'm trying to add a sub-menu under administration, for example:

Management:

  ......
  Content
  Structure
  ......
  My test (sub menu under administration)

      My view 1 (a view that I created)
      My view 2 (another view that I created)

Under structure-> menu, I see that I can create a new menu and add link to existing menues, but I cannot understand how can I add a sub menu to Management.
Note: I'm using Drupal 7.

Edit:
I added a link (My test) under management (Like in @Clive's answer) with path admin/test
under My Test I created another link with path admin/test/form-view-test-3 and also gave that path to the view.

When I click on My menu I what to see a list of subcategories, in my case Some view.
Instead Test 3 (The View) appears as overlay tab and I see the list of admin menus.

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


How to implement a custom hook I have implemented a custom login module and I want to keep it on general purpose state.

This module have been developed because users can be authenticate against an internal LDAP Server (Sun Microsystems' LDAP directory server). So in this module I want to keep only the authentication and retrieve data from the LDAP directory. That's fine, I have it, within the PHP API (LDAPc) we have available.

There are situations where the link to log into the application comes with extra querystring parameters, and I have the thought to add a hook to my custom login module, so from other module I can implement that custom hook, retrieve these querystring and do whatever we need to do... add them in an extra table linked with the user table, for example.

I could do this inside the custom login module, but if so, my module will not be valid for other drupal sites with other needs.

My first thought, following this post: http://tylerfrankenstein.com/code/drupal-create-custom-hook-for-other-modules

has been to add the lines:

    $params = $_GET;
    drupal_alter('retrieve_login_extra_params', $params);

to my current development state

/**
 * Implements hook_menu().
 */
function psaldaplogin_menu()
{
    $items = array();
    // Login Page to authenticate against PSA Ldap directory
    $items['user/psaldaplogin'] = array(
            // Every user can access to this page
            'access callback' => TRUE,
            // Define the function where implement the generation of the page
            'page callback' => '_psaldaplogin_view',
    );
    return $items;
}

/**
 * Authentication procedure
 *
 * TODO:
 *     Allow other modules implement this process as a hook,
 *     so more complex process on login step
 *     could be implemented outside this module
 *
 */
function _psaldaplogin_view()
{
    // Clear messages queue
    drupal_get_messages();

    // Check if the user is already logged
    if (user_is_logged_in()) {
        drupal_goto('home');
    }

    // Allow other modules process the querystring parameters
    // --> DOESN'T WORK
    $params = $_GET;
    drupal_alter('retrieve_login_extra_params', $params);

    // Authorized the user
    if ($username = _getAuthorizedUser()) {
        // Get the user information from PSA Ldap directory
        $userData = _getLdapUserInformation($username);
        // Register the user into Drupal
        if (_registerExternalUser($userData)) {
            // Redirecto to home
            drupal_goto('home');
        } else {
            // If the registration failed show access denied message
            drupal_access_denied();
        }
    } else {
        // If the authentication failed show access denied message
        drupal_access_denied();
    }
}

Figuring out I will be able from other module implement something like:

function slider_retrieve_login_extra_params($params)
{
    // check $params since they are unsafe data

    // test if the querystring params could be retrieve here
    file_put_contents('/tmp/genius/genius.log',
        "\n" . print_r($params, true) . "\n",
        FILE_APPEND);
}

But this chunk of code is never executed, so it is clear I have a miss understanding on how to allow other modules to implement a custom hook.

I'll appreciate if someone could point me to the right direction to achieve this solution. Otherwise I will have the module as template since for each development the login needs could be different.

Thanks for the reading.

Regards.

Putting aside the general design of your application, you are right to use drupal_alter to provide a hook.

However, you are missing the correct hook implementation function name.

It should be:

drupal_alter('retrieve_login_extra_params', $params);
// ...
function MODULE_retrieve_login_extra_params_alter(&$params){
// ...
}

You may also be interested in:

LDAP Integration
user_external_login_register


How would I add a section header sub-image based on path in Drupal? A client has asked me to enter a graphic header (really a sub heading) on a site. This sub-heading graphic would fit nicely, side aligned into the header or leader region inside our subtheme based on Adaptive Theme.

I'm having a hard time figuring out how to best approach this.

1. Do I use Context based on Path?
That is should I detect the path in Context and use one reaction to place an image into the header or leader region. I'm assuming I'd have to code about 12 HTML blocks. Though this doesn't exactly sit right with me.

2. Use CSS logic
Since I insert the first path level into the body class, should I add a div to the header region called #sub-graphic and use the following CSS logic:

body.sub-section-alpha #sub-graphic {background-image: url('image-alpha.jpg');}
body.sub-section-beta #sub-graphic {background-image: url('image-beta.jpg');}

3. Other, better option
Am I not seeing a simpler way.

Caveat: I'd prefer a non-php solution but I am comfortable inside theme functions.

The simplest solution that Drupal provides.
You can create 2 blocks with images. Than set visability on different pages.
This is it.


How do I get the property of a node object? I am trying to get the moderation_state property from a node object in Drupal8 (see attached image); however, I cannot work out how to do this.  In Drupal7 it was pretty straight forward $node->moderation_state.

How can I get this value in Drupal8 where $node is an instance of Drupal\node\Entity\Node?

I have tried:
$node->moderation_state
$node->moderation_state->value

Firstly, some background.

When you type $node->something you're getting a FieldItemListInterface. How do you know what values you can use for something? Well you can ask the entity.
$node->getFieldDefinitions()

Now you have a FieldItemListInterface you can iterate over its values, or in the case of single-value field, just its first one. So even if you're using $node->title, title is a FieldItemListInterface even though you'd only expect one item in the list.

So lets get the first value in the list. $node->something->get(0). This gives you a FieldItemInterface. From here you can access the properties of the field item. E.g. $node->title->get(0)->get('value'). Each of these is an instance of TypedDataInterface. But how do you know what you can use for value. E.g. For an entity reference field $node->some_er_field->target_id is valid but $node->some_er_field->value is not. Well you can ask the FieldItemInterface like so $node->title->get(0)->getProperties(). Or alternatively, you can know the data-type of the field and inspect its propertyDefinitions method. E.g. in the case of moderation_state field, it uses an Entity Reference field to track the reference to the moderation state config entity. So that means each FieldItemInterface is actually an EntityReferenceItem and you can check its ::propertyDefinitions() method to see what properties it defines.

So now you have a TypedDataInterface object, how do you get it's value? Well you use its ::getValue() method.

But wait why does $node->title->value work - I don't have to write $node->title->get(0)->get('value')->getValue() - well thats because we're using PHP magic methods on FieldItemListInterface and FieldItemInterface such that $node->title->value calls $node->title->get(0)->get('value')->getValue() for you.

So in summary:

$node->moderation_state->get(0)->get('target_id')->getValue() will give you the moderation state config entity's ID.
$node->moderation_state->get(0)->get('entity')->getValue() will give you the ModerationState config entity, so you can use its methods direct - like ::isPublished() and ::label().
$node->moderation_state->target_id and $node->moderation_state->entity would achieve the same thing respectively.

I did a lightning talk for my colleagues on this, if you're interested the slides are here unfortunately the recording didn't work.


Is there a way to turn off the paypal checkout button in /cart view in drupal 7 commerce? After adding an item to the cart in drupal 7 commerce, the /cart page has a checkout with paypal button. Is there a way to remove this in the commerce payment configuration pages? It seems unnecessary and confusing. I know I can hide it via css, but was wondering if there was a option somewhere.

If found a simple way to disable the button through rules.

Edit the configuration of the Paypal EC payment method and add a condition to the rule:

Data Comparison / Commerce Order...state / Equal to 'Checkout'

In this way, when the order is still in Shopping Cart state the payment method is disabled.


How do I access a function provided by a service resource module? Just getting started with Services so this is probably an easy question.

I'm attempting to allow users to access their private messages from a web app using this sandbox module.  At this point, after referring to the documentation on testing resources, I can get a JSON collection of the messages when I visit http://example.com/drupalgap/privatemsg, and I can get a specific thread if I visit http://example.com/drupalgap/privatemsg/threadID.

I understand the basic syntax is example.com + endpoint (drupalgap) + resource (privatemsg) + query.

However, the sandbox module includes a function for getting the number of unread messages, which I would like to do.  Here's the code:

 /**
 * Get the number of unread private messages of the logged-in user.
 *
 * @param int $uid
 *      User ID.
 *
 * @return int
 *   The unread count.
 */
function _privatemsg_services_unread_count($uid = '') {
  global $user;

  if (!user_is_logged_in()) {
    return services_error(t('This user is not logged in.'), 403);
  }

  /*
   * If a user id other than the current user's ID is passed, validate that the
   * authenticated user has the correct permissions to read another user's
   * messages.
   */
  if (is_numeric($uid) && ($uid != $user->uid)) {
    if (user_access("read all private messages")) {
      $account = user_load($uid);
    }
    else {
      return services_error(
        t('This user does not have permissions to use this service.'),
        403
      );
    }
  }
  else {
    $account = $user;
  }

  // Return unread count.
  return privatemsg_unread_count($account);
}

My question is, how do I call this with services?  I've tried things like http://example.com/drupalgap/privatemsg/unread_count/ and http://example.com/drupalgap/privatemsg_unread_count but I get no results.

Functions are exposed via service resources, by a module implementing hook_services_resources().

You should take a look at whatever module your using to provide Services functionality for the private message module, specifically its implementation of hook_services_resources().

If you see an entry with a callback of _privatemsg_services_unread_count, then the function you want is available via a resource. If not, it currently isn't, and you can implement hook_services_resources() yourself to expose it.


Is there an API for this? I know about user_access API. I've written a module that should display some information only if the user has specific rights on the taxonomy.

To be more precise:

we've created a vocabulary, say books.
in this vocabulary books we have a lot of terms, say for example children and cooking
we've created roles according to the terms, i.e. roles like role for children and role for cooking => one role = one term.
now I've written a module that should diplay a link to 'edit' or 'create' only if the user is logged, and if he has the rights based on the role (which heavily relies on the taxonomy access rights).

In short: in my node_view hook:

I have to check if it's a node with books vocabulary.
if so, I have to read the associated term (there can be only one), let's take an example: children
if the user is logged in and has the permissions of editing nodes with the specific term (children here), the I display a text with a link like edit this book and another like like create a children's book.

This is only the last part that is a problem to me.

Does the user access API call works flawlessly, and takes in account those rights, or do I have some specific calls to do? No API seems available for the taxonomy access control (TAC).

Maybe you have an example somewhere (didn't find one actually)?

Are you actually having a problem with user_access or just asking before you're trying it? I'm not really following what exactly is your problem.

Taxonomy Access Control should influence what user_access returns. Or you could just set permissions for "Use contextual links" and let Drupal take care of it with contextual links instead of writing a custom module.


Image preview thumbnail does not display Drupal 7.

When adding a core image field to a content type to display an image, the preview thumbnail does not display on the edit page when uploading an image.

What appears after clicking on the "Upload" button is a placeholder for the image and an image icon. The placeholder then quickly disappears to leave the icon and the name of the file. It looks like the link is broken and the image cannot be found. However, the uploaded image and it's preview (thumbnail image style) are in the right folders. This is confirmed when the edit page is reloaded (browser refresh or a new visit to the page) because the preview image then displays properly on the edit page..

Clicking the Save button displays the image in the content.

However, if I do not click the Upload button and click on the Save button directly instead after selecting an image with the Browse button, the content image is not displayed either unless I click on the browser Refresh (or go to another page and come back.)

A few people have had this issue.

In this Youtube tutorial, the issue is reproduced (the thumbnail does not show up.) The instructor notices it but gives no solution: Drupal Tutorials #9 - Custom Content Types Part 2 Manage Display

Does anyone know what's going on and how to fix this?

Any and all help will be greatly appreciated. :)

Try removing any space, empty line before

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

Hope this helps.


How do I override the taxonomy default content? I'm coding a way to display the taxonomy terms, and I don't want some of the term pages to report "There is currently no content classified with this term." I need to remove that message form the term pages with no content, but let the content be listed like normal when there is content associated with that term.

This information is added in taxonomy_term_page(). As you can see there, the page callback returns a renderable array, which means that you can easily replace it in a custom module by implementing hook_page_alter().

In that hook, check that you are on a taxonomy term page, look if the 'no_content' block exists, and if yes, override the #markup.

I suggest to use dpm() from devel.module to print $page so that you can more easily figure out  where exactly the page content is in that huge render array. Somewhere in system_main, if I remember correctly.


Display content reference with another content I just starting using Drupal and I have few question.

Currently I have two Content Types: Project and Task.

Project's field is:

Project title
Body
Date

Task's field is:

Task title
Body
Project (field_project), Entity reference

And I create a view to display List of project.

The problem is, How to display List of task when a project detail is viewed

Create a view with title list in Task content type, in this create a Contextual filters with field_project. Take the filter value from url arguments.


Recaptcha dissappears after form submission I am using webform with ajax and for spam protection I am using recaptcha module. Everything works fine when form is submitted once with all fields filled and recaptcha is also appearing on it. But when some validation error comes or recaptcha is left i.e. not filled the form appears again with error but their is no recaptcha field. Kindle tell me how to solve this as I am new to Drupal world. I am sure this isthis issue has been discussed before but I am unable to understand their solutions. Kindly give me a solution to solve this. I am using drupal 8.5.4.

check the "Persistence" option in the CAPTCHA settings? You must choose "Always add a challenge".


How to display specific exposed filters of a view in a block I have a set of exposed filters in one of my views. I want display a few of them as normal exposed filters and the rest exposed filters in a block in the head region of the view. Is there a way by which I can split the exposed filters & specify the filters to be displayed in the block?

Thanks

It's very simple.

Create a new view as a block using the Add button on top of your view admin page (Add > Block).

In your new view Exposed Form section, click on "Exposed form in a block" and press yes. In this way a block of your exposed filters is created in your Blocks admin page (admin/structure/block).

Using the blocks admin page enable your block and place it to the region of your liking.

Doing the above steps, you will get one exposed filter group on top of your view and one exposed filters block wherever you like in your site.


node_delete() does not trigger the "deleting content" Rule? Due to certain requirements, we are developing a custom module to handle node creation and deletion, using node_save() and node_delete() respectively. However when we add a Rule with the Rules module to perform certain tasks with the events "After saving new content" and "After deleting content", the event "After saving new content" is triggered with node_save() without problem, but the event "After deleting content" is never triggered at all with node_delete(). Anyone has any idea what could be going wrong here?
Thanks.

Short inspection of rules code showed that it should be triggered after node delete:

function rules_entity_delete($entity, $type) {
  switch ($type) {
  ...
    case 'node':
      rules_invoke_event('node_delete--' . $entity->type, $entity);
      rules_invoke_event('node_delete', $entity);
      break;
  ...

(from events.inc)

Have you tried turning on rules debug to see what is happening? Go to admin/config/workflow/rules/settings and turn on Show debug information to Always.

Maybe the event is being invoked, but some of your condition is incorrect and it appears that nothing is happening.


Adding PHP function code to a node returns Eval error I activated the PHP filter and it works fine, except when I declare a function.
I keep getting the following error.

  Fatal error: Cannot redeclare test_function_test() (previously declared in /web/htdocs/www.example.org/home/modules/php/php.module(80) : eval()'d code:3) in /web/htdocs/www.example.org/home/modules/php/php.module(80) : eval()'d code on line 1034

First, I tried with the following code.

function test_function_test() {
  echo "test";
}

Then, I tried using function_exists().

if (!function_exists('test_function_test')) {
  function test_function_test() {
    echo "test";
  }
}

In both cases, I keep getting the same error message.

How can I use a define a function in the code passed to the PHP filter, without getting this error?

You can try adding declaration of the function in your module.
But call it using php filter.

Moreover, in this case you will be able to edit code of your function with less chance of break the site.


How to add only "Add to Cart" Button in a view I have a view with all my product. My view display is TABLE. I'll want add a column where insert only "Add to Cart" button.

How can i do it?

Thanks

If you are adding fields, just add Add to Cart Form field in the view.
Attaching my view image just for your reference.


How to access webform elements in webform.html.twig I'm trying to figure out a way to access webform elements from webform.html.twig.

I need to style the form; wrapping some elements and adding bunch of styles
all I have in the webform.html.twig is "children" variable which renders the whole form, whereas I need to access every element individually.

I found a link on the web for webform-form.html.twig which might do what I need, however I can't find it in webform template folder

http://cgit.drupalcode.org/webform/tree/templates/webform-form.html.twig?id=1135b65031cd6cd195c2e638300e5ef945a6f652

Any help with this matter is much appreciated.

I have figured out a solutions for this situation.

create a tempalte file for your form (ex. webform--newsletter.html.twig)
there is a variable (element) where you can access each field of the form like this:

  {{ element.elements.YOUR_FIELD_NAME }}

you need to output the form action (submit) at the end of the form link this:

  {{ element.actions }}

the trick with this solution is that you need to output a couple of hidden form elements that is required for the form to be submitted properly:

  {{ element.form_token }}

  {{ element.form_build_id }}

  {{ element.form_id }}

My final form template looks like this:

      {{ element.elements.form_description }}

      <form{{ attributes }}>
        {{ title_prefix }}

            {{ element.elements.name }}
            {{ element.elements.email }}
            {{ element.elements.phone }}

            {{ element.elements.message }}
            {{ element.form_token }}
            {{ element.form_build_id }}
            {{ element.form_id }}
            {{ element.actions }}

        {{ title_suffix }}
      </form>

Hope that helps anyone else

Update:
I forgot to mention that you also need to print out the following element:

  {{ element.form_token }}

Credit goes to maestrojed Webform twig template causes “the form has become outdated” error


CSS aggregates generating but not loading (core and AdvAgg), but JS aggregates load fine I'm trying to set up aggregation and compression on my site, but am having problems. When I enable aggregation, either through core or through AdvAgg, it seems that aggregates are being generated for both CSS/JS files when I check sites/default/files, but only the JS aggregates are actually being loaded. When I check my page sources, the browser is displaying all of the original CSS files as though an aggregate had not been generated/enabled. I'm running Omega and a sub-theme, if that's a possible issue. Any suggestions on what to try?

EDIT: As per my comment below, the only theme option I see relating to aggregation is "Rebuild CSS and JS aggregates on every page load", and checking/unchecking it doesn't seem to have any effect. I can't seem to find anything else relating to aggregation within the theme settings.

It turns out that there is a "Development Extension" that is a part of the Omega theme settings. I had it enabled for a couple of the features it provides, but unchecking it caused the aggregates to start loading like normal. Guess having that enabled is what broke the aggregation. Hopefully this ends up helping somebody else eventually.


Conditionally aggregate (count) views field I have a very simple view of content filtered by content type. Multiple content types are selected. For example, I am listing the latest contents of type Event, Forum topic, and Article. I am using Views Ticker display for this view.
Now I got a new request. Since there are so many articles being published (they are synced from an external publishers), the view should only show the amount of the articles, but it should still list other content types individually. An example output should look somewhat like that:

Forum topic: Lorem ipsum
Forum topic: Dolor amet
New 26 articles
Event: Meeting
Forum topic: XYZ

How can I aggregate only for one content type in views? Can I use some view hooks to achieve that? Like hook_views_pre_render(), etc?
Since I am using Views Ticker as display plugin, I cannot simply add them to footer or header.

I have a feeling there may be a solution using a separate view with aggregation and then using the Views Field View module to embed the aggregated view as a field.

Another option (which feels like a bit of a cop-out and cheating) would be to create a content type called "articles count".

Then each time you do a sync with the external publisher you update the "articles count" node title to be "New [count] articles", and set the body to be a list of links to each of the new articles. This is neat as you always have an index to your new articles.

Then simply include this as one of your content types in the original view. To be honest this is probably the easiest way.


How do I change the Views (Entity Reference) filter via AJAX? I have an entity form that allows an admin to select a content type (checkbox) and an autocomplete field that is tapped into a VIEWS Entity Reference (via the Reference Method).

Goal: What I would like is to have the views entity reference filter dynamically change based off the end-user selection.  Contextual Filters would have worked but I think Filters is better because of the multiple selection.

So far I have a view with entity reference and it is pulling the correct data for content 1-4.  When I use the autocomplete it does what it's supposed to. I think the next step is to use AJAX to change how the autocomplete pulls from the view by changing the FILTER.

Can you help me figure out how I can change the views filter via AJAX/JS?

I am going to answer my own question in hopes this ccan help someone.  However I am welcome to hear other options :)

What I ended up doing was attach a javascript that updates the autocomplete's path.  Meaning when a user clicks on the checkbox it updates the input box for the autocomplete's attribute. The attribute called data-autocomplete-path.  I appended a query string without messing with the functionality of it.  This extra value gets sent to hook_views_pre_view.

This worked for me


How to fix search result "Access denied You are not authorized to access this page" How to fix search result "Access denied You are not authorized to access this page"?
Have tried to change permissions and search module configuration, nothing helps...

In admin/people/permissions, make sure that the roles that should be allowed to search are checked. Under the Search heading, look for the Use search permission. If anonymous users need this permission, check the box next to Anonymous User.
Next, clear your Drupal cache.

If you use Drush, you can use the following command.

drush cc all

There are several other ways to clear your cache as well.

Lastly, you can try rebuilding your permissions at admin/reports/status/rebuild.


How do I change the HTML surrounding a particular node? I'm new to Drupal and have been tasked with fixing some HTML on a page.

There are 3 seperate sections on this page, one of which needs a couple of new classes. I've identified the section I need to change is Pane within a Node (I think). However, I cannot find what .tpl file actually influences the output of this.

How do I find out which .tpl file houses the HTML for a given Pane?

Enable theme_debug mode, once it is done you can find which .tpl file the particular section in the firebug. For enabling theme debug mode drush vset theme_debug 1

In the firebug, you can find which .tpl file the section is using.