How to set up permissions for the private files directory? I'm trying to set up the private files directory and I'm getting the following error.

  The backup file could not be saved to 'private://backup_migrate/'
  because the directory could not be created or cannot be written to.
  Please make sure your private files directory is writable by the web
  server.

Could someone help correct my misstep? I've scoured scads of pages of documentation, and oddly I don't seem to be able to find a reliable path to a solution. Lots of conflicting info and lots of missing details.

Here's my setup:

bitnami drupal image (centos)
path to Drupal /root/apps/drupal/htdocs
I've connected as root via ssh

Here are the exact steps I've followed, and which best reflect my understanding so far of what I should do:

# cd /root/apps/drupal/ to go to directory that contains the web root directory
# mkdir private-files
# drush dl file_permissions --destination=~/.drush to download the contributed file_permissions utility, which says it handles all necessary permissions changes
# nano sites/default/settings.php to tell Drupal where to find the directory, set $settings['file_private_path'] = '/root/apps/drupal/private-files';
# drush cr to clear Drupal and Drush caches
# drush fp to run the file_permissions utility; it responds:

  Your httpd user: daemon                                      [status]
  Your httpd group: daemon                                     [status]
  You will be prompted for admin password to be able to change [warning]
  permissions with sudo command.
  Security warning: Couldn't write .htaccess file. Please create a     [error]
  .htaccess file inyour private:// directory which contains the
  following lines:
# Deny all requests from Apache 2.4+.
  <IfModule mod_authz_core.c>
  Require all denied
  </IfModule>

  # Deny all requests from Apache 2.0-2.2.
  <IfModule !mod_authz_core.c>
  Deny from all
  </IfModule>
  # Turn off all options we don't need.
  Options -Indexes -ExecCGI -Includes -MultiViews

  # Set the catch-all handler to prevent scripts from being executed.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
  <Files*>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
  </Files>
  # If we know how to do it safely, disable the PHP engine entirely.
  <IfModule mod_php5.c>
    php_flag engine off
  </IfModule>

# drush cr to clear Drupal and Drush caches
# ls -al to see permissions; it shows:

  total 8628
  drwxr-xr-x  7 root   root       134 Jul 23 12:04 .
  drwxr-xr-x  5 root   root        53 Jun  7 13:52 ..
  lrwxrwxrwx  1 root   root        14 Jun  7 13:55 .bitnamimeta -> ../../var/meta
  -r-xr--r--  1 root   root   8826689 Jun  7 13:31 bnconfig
  drwxr-xr-x  4 root   root       146 Jun  7 13:51 conf
  drwxr-xr-x 12 root   root      4096 Jun  7 13:51 drush
  drwxr-x---  9 root   daemon    4096 Jul 18 13:46 htdocs
  drwxr-xr-x  2 root   root        25 Jun  7 13:51 licenses
  drwxrwsr-x  2 daemon daemon      23 Jul 23 13:45 private-files
  lrwxrwxrwx  1 root   root        33 Jun  7 13:54 updateip -> /opt/bitnami/apps/drupal/bnconfig

# ls -al private-files/ to see permissions; it shows:

  total 4
  drwxrwsr-x 2 daemon daemon  23 Jul 23 13:45 .
  drwxr-xr-x 7 root   root   134 Jul 23 12:04 ..
  -rw-r--r-- 1 root   daemon 687 Jul 23 13:47 .htaccess

Needless to say, pretty frustrating since I've spent at least 4 hrs on what I imagine must be simple for someone already familiar with all the components.

Since I am new to servers as well as to Drupal, please break out actual steps vs merely invoking (vague-to-me) concepts such as 'change user group' or the like.

I would not create the folder as root, let the site create its own folder. Just set the path in your settings.php and then go to 'File system' in the Drupal site (configuration). You can see your path reflected here. Then just save the form and Drupal will create the folders with right permissions.


Faceted search using fields from a related node, is it possible? Drupal 7
Modules:
Facet_api 7.x-1.3
Search_api 7.x-1.6
Relation 7.x-1.0-rc4

My site has two nodes, node one provides a description of various astronomical objects and node two are images and their composition details. I’ve built a many to many relationship between the two nodes and there is a node index (search_api) which contains all fields from the two content types with facets enabled on the primary fields.

I’ve created the faceted search page for the Astronomical objects which works fine and I now want to extend the Astronomical facets to gallery search page (. e.g. Show all images containing an astronomical object of type galaxy) which is where I have become stuck as I can’t see a way to create an index which joins relationships and nodes.

If this approach isn’t possible the only alternative I can think of is building out the relation type with extra fields duplicating the data that I want from either node and building the index on it, which just feels like a hack. Any suggestions?

At the bottom of the fields page you can see additional fields. This allows you to join nodes via relationships.

Search API > Default index > Fields > [Scroll to bottom} > Add related fields

Select your field that is an entity reference.
You'll have access to the fields of the reference too.
Then select the fields on the referenced node that you need and save.
And return to facets.

http://example.com/admin/config/search/search_api/index/default_node_index/fields#edit-additional


New link added in user page but not visible to non admin user in Drupal 7 I added this module in Drupal 7 for adding new tab in my site. This new tab is not visible to non admin  user. Only visible to admin. I also tried to set permission in this direction admin> People> permission but this there is no module by the name "New tab" is visible. Please help.

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

  $items['user/%user/new_tab'] = array(
    'title' => 'New tab title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('newtab_newtab_form', 1),
    'access arguments' => array('access new tab'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

function newtab_newtab_form($form, &$form_state, $account) {
  // ...
}

function newtab_permission() {
  return array(
    'access new tab' => array(
      'title' => t('The title of the permission'),
      'description' => t('The description of the permission'),
    ),
  );
}

You need to declare your permission with hook_permission().

function newtab_permission() {
  return array(
    'access new tab' = > array(
      'title' => t('Access new tab'),
    ),
  );
}


Feeds XPath Parser - Update existing content I have created a Feed Importer and used XPath Parser for mapping. I have problem with updating a existing content. For example I have this xml structure.

<node>
  <nid>1</nid>
  <title>Title 1</title>
</node>
<node>
  <nid>2</nid>
  <title>Title 2</title>
</node>

I started importer and everything is OK. I set NID as unique and check "Update existing content" in Node Process settings. So when I run importer again whit the same data this nodes have updated again.

Why have been updated ? The source is the same and don't any difference. Should It display, there is no new content to add if I start importer again and again with the same data ?

Thank you!

it doesn't recognized the nid field as unique,

What is  the field associated with the nid value?

If you have a custom field associated with the nid :

You should install https://www.drupal.org/project/field_validation

and add the validation of the field at
http://yourwebsite/admin/structure/field_validation

and set the validator with the value "Unique values".

Sometimes a space in the value of the feed can cause this in this case you can use tamper for trim spaces :
https://www.drupal.org/project/feeds_tamper


Some cck fields not turning into HTML This happens in my custom Zen-based theme where I made a custom node type 'events'. I put print_r($node) inside of my node-events.tpl.php which gave all the ckk fields including the ones that didn't turn into HTML i.e. not displayed.

When viewing this type of node in a stock drupal theme, this problem doesn't occur so everything gets displayed as desired.
This means my viewing permissions are in check and also under admin->content type-> 'events' -> display fields hidden is turned off (set to standard just the way it was when I didn't have the problem)

I still don't think I'm understanding the symptom.

If something shows up in one theme and not the other I would check if you have anything wierd in your template.php or if you have overridden any of the content-field.tpl.php files


how to refer to fields with multiple values in node--content-type template I currently have a template for the article content type.

node--article.tpl.php contains:

<?php
    print render($content['body']);
    print render($content['field_file']);
    print render($content['field_tags']);
?>

All of those fields are rendered just fine. All the values of field_tags are rendered. However I'd like to be able to refer to each individual value of the tags field.

For instance, I'd like to be able to do

    field_tag

and iterate i for each item the field spits out.

I've made some attempts with no luck. I tried

$i = 0;
while($content['field_tags']){
    print "";
    print render($content['field_tags']);
    print "";
    $i += 1;
}

However that just created an infinite loop. I attempted it with

while(render($content['field_tags']))

as well but that created an infinite loop as well. Is there a way to access the tags field as an array? rather than just one element in the $content array?

I managed to accomplish this by appending [value] to the end of the field_tag array. Then by using the 'count' function I created a for loop to iterate through each value like so

$j = count($content['field_tags']);
for( $i = 0; $i < $j; $j+= 1){
    if(render($content['field_tags'][$i]) != ''){
        print "";
        print render($content['field_tags'][$i]);
        print "";
    }
}

Note: For some reason I had to insert a check for if the tag was empty because the array ended up being a lot larger than the number of the tags.


How to process different URL page via Drush? I'm testing the following Drush 8 command (using --uri parameter):

drush --uri=https://www.example.com/custom/path ev 'var_dump(current_path());'

however when printing current_path(), it always returns the same, default page. To clarify, specified page exists.

According to this page, I think it should work this way.

How I can make Drush to parse an URL of my choice?

As the article says, the uri parameter just populates the request information. Drush only uses this to find the site settings information.  At this point, just like in a web request, the context is the index.php page.

On a web server, the code inside the index.php takes the URI and causes the requested page to be rendered.

Drush does not do this step.  So, when you do your ev of the current_path(), you get the default page.

The article points out that you need to call the menu_execute_active_handler() in D7 to render the page.  This take the URI and converts it to the requested page.

If you want information about the page, you will need to embed your print statements in the code for that page.

NOTE: an alternative to trying to do this via Drush is to look at using the devel module (I recommend adding the kint addon as well). This allows you to place debug statements in the code that will print out on the web page, e.g. kint($node).  Very useful in determining the structure of data so you can grab the right bit.


How do I tell hook_block() about placement I may have a disconnect and I'm just not sure if what I'm asking is possible. I'd like to tell Drupal where to place a block. So far I'm using a Context with a path condition to user/* and stream.

Can't I accomplish the similar thing with the following?

function hook_block($op = 'list', $delta = 0, $edit = array()) {

  if ($op == 'list')
  {
    $blocks[0] = array(
      'info'      => t('Social Login Block'),
      'region'    => 'sidebar_last',
      'pages'     => 'stream\nusers/*',
      );

Is this possible or is it better form to just let the maintainer set the block manually? Or a larger question, how might I translate this context rule into code?

You should use hook_block_info_alter() instead of hook_block(). For example:

function YOURMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  $blocks['MODULE']['BLOCK']['visibility'] = BLOCK_VISIBILITY_LISTED;
  $blocks['MODULE']['BLOCK']['pages'] = 'user/* \n stream';
}

Where YOURMODULE is the name of your module, MODULE is the module generating the block, and BLOCK is the name of the block. You should list all paths where the block should be visible separated by \n, \r or \n\r.


contact form in popup block I want to show the contact form in popup. How should I actually do it?
I tried to create a module and call the function in it.
But I am confused on how to implement *hook_block_view()*

Is there any other way to this?

This is my first drupal project.
And later do I realize that I am not having template.php in my theme folder.

This is what I have done.
 1. I had made a block in my page, named 'popup_this'.
 2. I made a module named 'popup' and made to display in this block.
 3. I had activate the module named 'contact' in the site.
    It is called in the link '?q=contact'.
 4. I am trying to call this form in my custom module.

I don't know how to implement the function popup_block_view().

Thanking you in advance

You don't need to write a custom module. You can use the popups api module. All you will have to do is assign the link a class called as "popups". Refer to the api if you want to do it the custom way as well using the popup api.

Summary of the module

  API for building modal ajax dialogs. Its focus is on putting forms
  inside of ajax popup dialogs. Current example can present pages as
  popups (of the lightbox type). This is amazingly useful for things
  like confirmation pages. And the best part is it can be applied
  retroactively to a page without needing to modify the generating
  module, and (of course) it degrades gracefully.


Unable to retrieve node content with drupalgap I've set up drupalgap on my website, followed all the instructions and got the Hello World example up and running via Ripple.  I've also been able to adapt that example to put a new logo and different menus on the front page.  However, when I try and view node content it just hangs, with "SyntaxError: Unexpected end of input" being reported via the console.  I've not written any code of my own to do this, I'm just trying to access nodes via the top-left menu provided in the tutorial example.

I've made sure the node entity type is enabled in the services.  I can view user entities (and if I disable these then I get a 404 so enabling nodes doesn't appear to be the issue.

So I've taken it back to basics and if I navigate to example.com/user/1/json I get the page I expect and likewise for example.com/node/1/json.  However when I use example.com/?q=drupalgap/node/1.json I get a blank screen, whereas for example.com/?q=drupalgap/user/1.json I get the JSON output for that user.  So I am concluding that for some reason nodes are not being output via drupalgap (returning null instead?) whereas users are.

Any clues?

David

Ok, so with thanks to the advice about it being another module interfering with the retrieval of JSON data, I've identified the culprit through a process of elimination.

When I disable the "Node Registration" module the problem goes away and I can view node content through the mobile app.

Of course, that gives me another problem with how to get the functionality Node Registration was giving me, but I'll save that one for now...


Inserting Block with Custom Input Filter Module via Shortcode Causing http 500 error I have a custom input filter module, and I am trying to figure out why it crashes when I attempt to insert a block into a post via a shortcode. The method works perfectly when I am inserting a string, but when I try to insert a block, it causes a http 500 error.

Any ideas? I am using Drupal 7.15. Also, I have tried the insert_block module, and it generates a similar error...

Here is the input filter process that works (with a string)

function _related_links_filter_related_block_process($text, $filter, $format) {
   $shortcode_regexp  = "/\[block\]/";
   $output = "Text string inserted in via shortcode";

   return preg_replace($shortcode_regexp, $output,$text);
}

Here is the input filter process that causes the error (with a block)

function _related_links_filter_related_block_process($text, $filter, $format) {
   $shortcode_regexp  = "/\[block\]/";
   $block = block_load('block', 3);
   $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));

   return preg_replace($shortcode_regexp, $output,$text);
}

Any help is appreciated!

A 500 error can be caused by lots of things. Your best bet is probably to use the Watchdog and/or Apache logs to narrow down the specific cause(s).


Show a term description when the search filter in a view is that term? I have a content type that has several vocabularies. Nodes can have 0, 1, 2 or all 3 terms selected.

Ive added a field to the terms so they all have a description as well as their name.

Color (vocabulary)

-Red (term)
  --This has red items (term description)

-Blue (term)
  --This has blue items (term description)

-Green (term)
  --This has green items (term description)

Pattern (vocabulary)

-Stripy (term)
--This has stripy items (term description)

-Spotted (term)
--This has spotty items (term description)

-Pinstripe (term)
--This has pinstriped items (term description)

I have a View of nodes of the content type. I'm using Better Exposed Filters so you can filter by the different terms. I need it so when you have selected a single term its description is shown at the top of the view.

So if you checked 'Red' and 'Stripy', or 'Blue' 'Spotted' and 'Pinstripe', then no description would be shown. But if you just checked 'Blue' then 'This has blue items' would be printed at the top of the view before the nodes tagged with 'Blue' were listed.

Create a template for the view.

Edit the view. Under "Advanced" find "Theme: Information". Click on it to find the names of the templates that are applied in your theme. I think "Display output" is what you want to use. It will show you the contents of the template.

In your custom theme, create a template with the same name as the template you copied. Paste in the contents of the template you copied.

Now you can use PHP to get the information you want (available variables are listed in the comments of the templates), manipulate it as needed, and add it to the $header or wherever you want it, without any PHP in the database.


Difficulty running tests, --group option not being respected I am trying to run a BrowserTestBase based test in my own module, following the documentation on drupal.org.

No matter if I run the test from PHPStorm or command line, I get the same error:

vagrant@local:/var/www/mysite/docroot$ ../vendor/bin/phpunit -c core/phpunit.xml --group mymodule
PHP Fatal error:  Trait 'Drupal\Tests\facets\Functional\BlockTestTrait' not found in /var/www/mysite/docroot/modules/contrib/search_api_solr/tests/src/Functional/FacetsTest.php on line 20
PHP Stack trace:
PHP   1. {main}() /var/www/mysite/vendor/phpunit/phpunit/phpunit:0
PHP   2. PHPUnit_TextUI_Command::main() /var/www/mysite/vendor/phpunit/phpunit/phpunit:52
PHP   3. PHPUnit_TextUI_Command->run() /var/www/mysite/vendor/phpunit/phpunit/src/TextUI/Command.php:100
PHP   4. PHPUnit_TextUI_Command->handleArguments() /var/www/mysite/vendor/phpunit/phpunit/src/TextUI/Command.php:111
PHP   5. PHPUnit_Util_Configuration->getTestSuiteConfiguration() /var/www/mysite/vendor/phpunit/phpunit/src/TextUI/Command.php:649
PHP   6. PHPUnit_Util_Configuration->getTestSuite() /var/www/mysite/vendor/phpunit/phpunit/src/Util/Configuration.php:878
PHP   7. PHPUnit_Framework_TestSuite->addTestFile() /var/www/mysite/vendor/phpunit/phpunit/src/Util/Configuration.php:1000
PHP   8. ReflectionMethod->invoke() /var/www/mysite/vendor/phpunit/phpunit/src/Framework/TestSuite.php:353
PHP   9. Drupal\Tests\TestSuites\FunctionalTestSuite::suite() /var/www/mysite/vendor/phpunit/phpunit/src/Framework/TestSuite.php:353
PHP  10. Drupal\Tests\TestSuites\TestSuiteBase->addTestsBySuiteNamespace() /var/www/mysite/docroot/core/tests/TestSuites/FunctionalTestSuite.php:22
PHP  11. PHPUnit_Framework_TestSuite->addTestFiles() /var/www/mysite/docroot/core/tests/TestSuites/TestSuiteBase.php:55
PHP  12. PHPUnit_Framework_TestSuite->addTestFile() /var/www/mysite/vendor/phpunit/phpunit/src/Framework/TestSuite.php:384
PHP  13. PHPUnit_Util_Fileloader::checkAndLoad() /var/www/mysite/vendor/phpunit/phpunit/src/Framework/TestSuite.php:310
PHP  14. PHPUnit_Util_Fileloader::load() /var/www/mysite/vendor/phpunit/phpunit/src/Util/Fileloader.php:38
PHP  15. include_once() /var/www/mysite/vendor/phpunit/phpunit/src/Util/Fileloader.php:56

Fatal error: Trait 'Drupal\Tests\facets\Functional\BlockTestTrait' not found in /var/www/mysite/docroot/modules/contrib/search_api_solr/tests/src/Functional/FacetsTest.php on line 20

I am not requiring Search API Solr in my test, nor do I have a clue why it is running it. Even if I specify --testsuite unit, I get the same error.

Here is the test I am trying to run, with a basic test step:

namespace Drupal\Tests\mymodule\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Class AuthenticationTest.
 *
 * @group mymodule
 */
class AuthenticationTest extends BrowserTestBase {

  /**
   * Required modules.
   *
   * @var array
   */
  protected static $modules = ['user', 'node'];

  public function setUp() {
    parent::setUp();

    // set config for netforum
  }

  /**
   * The superuser should not authenticate to Netforum.
   */
  public function testAdminUserUsesDrupalAuthentication() {
    $account = $this->drupalCreateUser(['administer site configuration']);
    $this->drupalLogin($account);
  }

}

I am not sure why it is even looking at the Search API Solr module, but the test in question does try to use several files that do not exist:

use Drupal\Tests\facets\Functional\BlockTestTrait;
use Drupal\Tests\facets\Functional\ExampleContentTrait;
use Drupal\Tests\facets\Functional\TestHelperTrait;

I assume these are a part of the Facets module, which I do not have.

edit: This might be my issue.

edit: This might be my issue.

Yes.

The error happens during test discovery, first it has to find all tests and then limit it based on the group.

The easiest workaround is simply to specifiy your module, then you don't even need the group. phpunit will only discover test in that folder, which will not just avoid this problem it will also be much faster.

$ ../vendor/bin/phpunit -c core/phpunit.xml modules/custom/mymodule


How to upload pdf files and link to them? I look for a comfortable solution to upload files (pdf) in drupal 8 and link to them (open the link in a new tab).
The link I like to embed in a paragraph or apply to lists.
Something like entity embed (embedded file). But I do not like the output of this solution.

e.g. I can't open the file new window
e.g. I can't change the title of the link

I think the solution could be IMCE module which allows you to upload file/images... through CKeditor interface.

  Features

  Basic file operations: upload, delete
  Image(jpg, png, gif) operations: resize, create thumbnails, preview
  Support for private file system
  Configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions
  Personal or shared folders for users
  Permissions per directory
  Ftp-like directory navigation
  File sorting by name, size, dimensions, date
  Tabbed interface for file operations
  Keyboard shortcuts(up, down, insert(or enter), delete, home, end, ctrl+A, R(esize), T(humbnails), U(pload)).
  Built-in support for inline image/file insertion into textareas
  Multiple file selection(using ctrl or shift)
  Ajax file operations
  Themable layout using tpl files


Getting form submitted date I have a date picker in my form, when user hits submit button, the date which entered in date field is displaying in list view. But I want to display the date the form submitted also.

Any help appreciated.

In the Views module you can add this field:

Content: Updated date, The date the content was last updated.


Undefined index: und in mytheme_preprocess_page() I created a custom image field for a banner in one of my content type. I wish to display this banner in the page.tpl.php instead of node template. Here's my code in template.php:

function mytheme_preprocess_page(&$vars, $hook) {

     $vars['banner'] = '';
    if (!empty($vars['node'])) {
        $node = $vars['node'];

        if (isset($node->field_banner)) {
                // Render the image as a variable in the page template
           $vars['banner'] = theme_image_style(array('path' => $node->field_banner['und']['0']['uri'], 'style_name' => 'mybannerstyle', 'height' => '200', 'width' => '700'));
        }
    }

.....

and in the page.tpl.php, i coded:

    <?php if(!empty($banner)){print $banner;} ?>

. This work perfectly in the node that has banner uploaded. But for nodes which have no banner, the following undefined messaged turn up:

Notice: Undefined index: und in mytheme_preprocess_page() (line 33 of /home/xxxxx/themes/mytheme/template.php).

I wonder how to solve this. Please advise. Thanks.

For a field, $entity->$field_name['und'] is not always defined. Instead of the code you are using, you should use the following code.

if (isset($node->field_banner)) {
  // Render the image as a variable in the page template.
  $field = field_get_items('node', $node, 'field_banner');
  $vars['banner'] = theme_image_style(array('path' => $field[0]['uri'], 'style_name' => 'mybannerstyle', 'height' => '200', 'width' => '700'));
}

I would also consider using field_view_value(), instead of fields_get_items(), but the first function doesn't allow to customize the output, if not through the $display parameter. (See field_view_field() for a description of that parameter.)

field_get_items() and field_view_value() get the language ID from field_get_name(), which returns the correct value for the language to use for the field.


How do I handle exceptions in a service class? I have implemented a Service which does stuff with a RESTful API:
services:
  api.clientname:
    class: Drupal\my_custom_module\Api\Clientname
    arguments: ['@http_client', '@messenger', '@logger.factory', '@uuid']

I'm injecting dependencies for ['@http_client', '@messenger', '@logger.factory', '@uuid']:

Guzzle HTTP Client
messenger service to call $this->messenger->addMessage(),
logger factory to call $this->loggerFactory->get('my_custom_module')->debug($message, $variables),
UUID service to generate UUID v4, per API specification.

I'm also using the StringTranslationTrait to get $this->t() working in my class.
All this is great so far. When it works, it works, and it logs success to the dblog. But it also needs to log failures. I'm having a problem with exception handling.
I'm trying to do something like this:
    while ($apiCallAttempts < API_CALL_LIMIT && $apiSuccess === FALSE) {
      $apiCallAttempts++;
      try {
        $accessToken = $this->obtainAccessToken($url, $postFields);
        $message = "Step 1: Access Token obtained from API endpoint";
        $this->loggerFactory->get('my_custom_module')->debug($message, []);
        $apiSuccess = TRUE;
      }
      catch (Exception $e) {
        // TODO: "watchdog_exception('my_custom_module', $e);".
        $variables = Error::decodeException($e);
        $this->loggerFactory->get('my_custom_module')->error('%type: @message in %function (line %line of %file).', $variables);
        if ($apiCallAttempts === API_CALL_LIMIT && $apiSuccess === FALSE) {
          // Set errorMessage for messenger service.
          $errorMessage = 'Error CLIENTNAME-01: Authentication API call failed';
          $message = 'Failed to sync %label with API. <br> @error after @limit attempts.';
          $variables = [
            '%label' => $form_id,
            '@error' => $errorMessage,
            '@limit' => strval($apiCallAttempts),
          ];
          $this->messenger->addMessage($errorMessage, 'error');
          $this->loggerFactory->get('dex_provider_hcp_forms')->error($message, $variables);
          return $accessToken;
        }
      }

but it doesn't work because:

Fatal error: Trait 'Drupal\my_custom_module\Api\Exception' not found in /app/docroot/modules/custom/my_custom_module/src/Api/Clientname.php on line 66

After some Googling, I am very confused about how to add the global PHP Exception to my Service class namespace.
Removing a use declaration inside the class removed the "Trait not found" error.
The new error message was:

Error: Class 'Drupal\my_custom_module\Api\Error' not found

EDIT:
Both of these things were happening for the same reason. I was using Exception and Error inside my class without prepending them with a backward slash, causing PHP to assume that Exception was in the same namespace as the one I declared for the file. Using \Exception and \Error instead resolved the issue.
The new error message is:

Error: Call to undefined method Error::decodeException()

When using unqualified class names like Exception and Error, and in the absence of a use statement to qualify the names, PHP assumes those classes are in the "current" namespace. The namespace of your service class appears to be Drupal\my_custom_module\Api, so that is where PHP will look for Exception and Error. When PHP does not find those classes, you will get an error.
To avoid this error, add a backslash before the class name for classes that are in the global namespace. So use \Exception and \Error instead. You do not need a use statement for either of these.
The error Fatal error: Trait 'Drupal\my_custom_module\Api\Exception' not found in /app/docroot/modules/custom/my_custom_module/src/Api/Clientname.php on line 66. is because you probably said use Exception; within the body of your class. The error Error: Class 'Drupal\my_custom_module\Api\Error' not found is because you referred to Error and not \Error.
Note that all these problems are just basic PHP issues - they are not caused by Drupal and do not involve Drupal at all. Specifically, it does not matter that you're in a service class, or that you're doing exception handling, etc.


Querying a custom table does not return latest results for anonymous user I have a custom module and a simple custom table in the database. When I try to query the table to get the row, it seems Drupal 8, or maybe mysql, is caching the results.

$connection = \Drupal::database();

$result = $connection->query("SELECT SQL_NO_CACHE * FROM {mytable} WHERE id = (:id)", [':id' => $key]);

$result->fetch()

We get the latest data if a I am  logged in to Drupal, but the data is cached if we are not logged in.

Try to user drupal select instead of normal query something like following:

  // Add this use at the top of the file
  use Drupal\Core\Database\Database;

  $connection = Database::getConnection();
  $query = $connection->select('mytable', 'my_table')
    ->condition('id', $key, '=');
  $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);


Display referenced user's email address instead of username I have a user reference field as a select list in my content type. When adding node I got a list of usernames. What I want is to display E-mails/ (or other user fields) instead of username. I tried to create entity reference view but it does not show the selected fields in the view either.

You are on the good track with solving your problem using Entity Reference Views Display. Once you have that Display type ready, you can edit your Entity reference field to use that Views display.

Your question seems to have two parts, one is displaying user information in Views, and the other is making the Entity reference field use the Entity Reference Views instead of a Select list.

Entity Reference Views in Drupal Core—Needs work

There are efforts to make using Views as Widgets on Entity reference field forms in Drupal Core: View output is not used for entityreference options. You can patch your installation using the patch from that Issue.

Or you can use the already suggested module Entity Reference Views Select until it's all sorted out in core: Similar support to be ported to core. Follow the instructions from the module about how to configure your Entity reference field.

Showing user information in Views

Since your Entity reference field is referencing Users, it makes the most sense to create a View of type User.

Show Users, but don't create a Page or a Block. When you Save the View create a new Display of type Entity Reference.

Add Email and other fields you want to show on the Create node form when selecting users.

Whatever fields you see in this Display, you will see when selecting users on the create/edit node form.


Print taxonomy term for theming nodes I'm not a PHP developer, so I have a problem with customizing a theme.

I create a vocabulary "City" and a term "Shiraz", then a field "field_city" as a taxonomy term in my content type.

Now I want to print this field, so in the tpl file I write the following code:

<?php print render($content['field_city']); ?>

but nothing happens.
What am I missing?

Try this out :

Make sure you set the right display of the field, like the following picture.
loop through Items and render vocab fields.

<?php foreach ($content['field_city']['#items'] as $item): ?>
   <?php print render($item['taxonomy_term']->name); ?>
<?php endforeach; ?>

Note : print only name field, if you have another fields in your vocabulary add them, like $item['taxonomy_term']->some_field


Why do all auto created urls in my multilingual site cause a Page not found? I have a multilingual site, using Drupal core 7.43 and the Redirect module, and the Pathauto module (and aliases are auto created without any problems).

Creating content translation I've got such problem: all auto created url aliases don't work.

When I change site language (as visitor) all seems Ok, I see all content has been translated. But if I (as a logged in user which is also an        administrator) try to open an article (for example), or any other translated content, I am always getting "Page Not Found". Auto created url leads nowhere.

What is wrong?

Note: When I am manually adding redirect (eg. from mysite/content/myarticle_1 to node/122), I am getting error "You are attempting to redirect the page to itself. This will result in an infinite loop." When I change article language from native to "All languages" then redirect could be saved and works as it should be.

Check your configuration at Configuration -> Languages -> detection and selection: the order specified there could be what explains the current behaviour in your site.

You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. It could well be that that is all that's needed here ... So try to experiment a bit with the various combinations in this order to see if it helps.

Note: Debugging is the art of taking away all possible causes of a problem. So sorry upfront if this answer turns out to not be the solution.


How do you position a custom search box in the main menu? I'm using the Drupal 7 Mayo theme for my site. The theme comes with a search box that you can place in the header but no where else, so I made a custom search box block, which I would like to place to the right of the main menu bar, which has a horizontal list of dropdown menu links. When I try to move the search block to the main menu, however, it either pushes the links to a line below or appears on a line below the links depending on how I set the weight. I can't get them to match up. Is there a way to fix this?

Menu Inject Block module was built exactly for the same purpose.

  This module allows you to inject blocks as menu items. It facilitates easier use of JavaScript based dropdowns and panel like navigation. Most users employ this module to create dropdown panels using other modules to handle the dropdowns and this module to inject the blocks as needed.

To use this module:

Enable the module
Create or Edit your menu item (/admin/build/menu)
Enter in  for the Path
Give your menu item a Title
Select a Block from the "BLOCK TO INJECT:" drop down (in your case the search block).
Save your menu item

You don't need to create a separate search block in case you use the module. You can place the default search block that Drupal provides, into step 5 mentioned above.


How do I redirect the "No Result" search page to Add node? I would like to redirect the "No result found" page of the drupal search to Add node. Basically I want when users search for an item using the search text box they get redirected to the Add node page when the item is not found.

I was really hoping that _preprocess_search_results(&$vars) would work, but it only gets called when there are results, so, here are two really really I can't believe I am suggesting these but they should work ways:

Drupal 6:

In your theme's template.php file, you can retheme box, which is how drupal 6 creates the 'no results found' info:

function YOURTHEMENAME_box($title, $content, $region = 'main') {

  if ($title==t('Your search yielded no results')) {
    drupal_goto('node/add');
  } else {
    $output = '
'. $title .'

'. $content .'
';
    return $output;
  }
}

If Drupal 7:

Copy search-results.tpl.php from the search module's directory to your theme directory and change it:

<?php if ($search_results): ?>

<?php print t('Search results');?>

  <ol class="search-results <?php print $module; ?>-results">
    <?php print $search_results; ?>

  <?php print $pager; ?>
<?php else: ?>
  <?php drupal_goto('node/add'); ?>
<?php endif; ?>


Get referenced node fields in twig In Drupal 8, I have a content type, that has an "entity_reference" field and I wish to access the referenced node's fields in twig template.
the kint() output for the field is:

In this list I can't find the referenced node's field values. How can I (if at all possible) load the node or node fields/values in twig?

Best,

Alari

The referenced nodes are inside the list and you can get the first list item with .0, the referenced node with .entity and then the first field value:

For example if you are in a page or node template:

{{ node.field_reference.0.entity.field_in_referenced_node.0.value }}

You can ommit .0 in both cases, when you only want to get the first value.

Other examples could look like this, but your question is unclear exactly where you are:

{{ item.content['#item'].entity.field_in_referenced_node.value }}
{{ elements['#items'].0.entity.field_in_referenced_node.value }}

Edit: Counting the items in multivalue fields

{{ node.field_reference.getvalue|length }}

You can't use count() in twig, because this is not on the whitelist for allowed methods. This uses getvalue() to get the array of the field and then counts the array keys.


Exporting Custom Display Suite View Modes With Configuration I'm using display suite with custom display settings for several view modes.  I am also using the configuration management module for D7.

When I go to import my config on the staging server, the content types and settings and even the 'ds' field format settings come through, but it does not remember what view modes I've checked to have custom display settings.  If I manually go back in and recheck the view modes, everything displays fine again.

Any idea where to track those changes?

Found the answer.  It is under the strongarm variables.  The setting you have to click is field_bundle_settings for that particular content type.  You must have the strongarm module enabled for this to work.


Get Absolute url using hook_preprocess_node We are attempting to change the $variables['url'] from a relative to absolute URL within the mymodule_preprocess_node() hook. The $variables['url'] is displayed as a <a> element within our node--page.html.twig template.

How can we set the $variable['url'] so that it uses the absolute URL?

node--page.html.twig

<a href="{{ url }}">
  {{ label }}
  {{ content.field_text }} {# custom text field #}
</a>

What we tried within mymodule_preprocess_node().

use Drupal\Core\Url;

function mymodule_preprocess_node($variables) {
  $options = [
    'absolute' => true,
  ];
  $variables['url'] = URL::fromUri($variables['url'], $options);
}

This results in the following error message:

  The URI '' is invalid. You must use a valid URI scheme. in Drupal\Core\Url::fromUri() (line 281 of core\lib\Drupal\Core\Url.php).

In order to get this to work, I did the following. This assume you have access to the $node object, which you would if you are performing this within the hook_preprocess_node() hook.

$variables['url'] = $node->toUrl()->setAbsolute()->toString();


Add Font Awesome to Webform Placeholder I am currently using Webform 7.x-4.2 and am looking to add a Font Awesome icon inside the placeholder. I did try modifying the settings.php with the following line:

$conf['webform_allowed_tags'] = array('a', 'em', 'strong', 'code', 'img', 'i');

My understanding was that this would allow me to use an 'i' tag on my webforms but it is not working for a placeholder. It does work if I use the tag in place of my label but then when a user gets a confirmation email with a submission summary the label shows the 'i' tag (ex. )

Is there a way to use Font Awesome in a placeholder?

Thanks for any assistance.

After reading question again I was way off. I am not sure if there is an easy cut and dry way to do this but I did find a workaround with hook_preprocess_webform_element. The code is pretty rough but should point the way to suit your needs.

Example:

function MY_MODULE_preprocess_webform_element(&$variables) {
 $icons = array(
  'fa-adn' => '&#xf170;',
  'fa-align-right' => '&#xf209;',
 );
 if (isset($variables['element']['#attributes']['placeholder']) && array_search($variables['element']['#attributes']['placeholder'], array_keys($icons)) !== FALSE) {
  $icon = $variables['element']['#attributes']['placeholder'];
  $search_string = implode('|', array_keys($icons));
  $variables['element']['#children'] = preg_replace('/^(<input .*placeholder=")(' . $search_string . ')(".*\/>)$/', '$1' . $icons[$icon] . '$3', $variables['element']['#children']);
 }
}

This will allow the editor to put the fa icon name in the placeholder text field on the edit form.

You can find the codes for the fa icons here.

EDIT: I forgot to add that you would have to change the font-family for the element and then remove it when the placeholder disappears if you are not using FA for your sites font.

Edit2: Per comment you can add a wrapper class to the textfield when editing the component then use CSS to have an icon permanently in front of the textfield.

.textfield-wrapper::before {
  position: relative;
  font-family: FontAwesome;
  margin-left: 5px;
  content: '\f061';
 }

Note: If you want the icon 'inside' the text field you can add the appropriate top, left positioning and z-index to this CSS.


How can I use the UUID API? I am aware that the question is (almost) a duplicate of the following question #21991, which has been posted back in 2012. But that question is NOT related to Drupal 8, where UUID is in core.

References:

Drupal 8 Core API
Drupal 8 Core Module Documentation

The Drupal 8 Core Module Documentation does not list UUID.

I wonder if I could leverage Drupal 8's core UUID module to migrate and map relational data imported from a different environment, which has unique keys generated by Firebase.

Update:

It has been kindly pointed out that UUID is not a module.

It seems to make UUID records per default for entities (aka nodes) and apparently can be used to map entity references.

Can I make use of this when I introduce external data, that already has unique IDs?
So I have the "node" IDs and can map with the UUIDs?

Update based on further comments:

The goal is to use UUID with entities and the REST module.
Respectively, it seems sensible to do so when importing external relational data, that already has unique IDs.

I just try to understand how UUID works, what it can do and what not, how I can generate and validate UUID's, what I need to be aware of, if I introduce external ID's.

I assume what you want to know is how to generate a UUID in Drupal 8, because there's really not much else that you can do ;)

Entities all have an UUID automatically, so if you store your data as a config or content entity, you just have to define the uuid entity key.

To generate a UUID yourself, you need the uuid service:

$uuid = \Drupal::service('uuid');
$uuid->generate();
$uuid->isValid($uuid_to_validate);


Relate Content to a Group feature when creating a node outside a group In my drupal site, I'm using the Group module.

My problem:

  I created a regular Drupal node type, let's call it userpost
  I created a group type called "usergroup"
  The content type "userpost" is also installed as a group node of group type "usergroup"

Is there a way to put a reference field or something similar into my "regular" node form for my content type called userpost? So that it's possible to (optional) relate a node during creation, to one (or more) group(s) at the same time?

In the admin interface of a group it's possible to relate existing content to a group. This kind of reference field I would like to place into my node creation form :)

Thanks for any hint in advance.

Best regards
Phil

P.S. I opened for this problem an issue at Drupal.org too.

Well, if I understand your problem correctly, you could just add an entity_reference field to your node type 'userpost' via admin toolbar. Go to Structure->Content types->userpost->Manage fields->Add field->Choose Reference (other)->Select Group and set cardinality to whatever you want.

This would allow you to add group references when you create a new node of content type userpost

Update
What I described adds a reference from a node to one or multiple group(s) via a new field, it does NOT add this node as a group-content to your group(s). It depends what you are trying to achieve? If you want to add your node as a group-content and you want to do this via the node creation form, you need one more extra step. You can implement a hook_ENTITY_TYPE_insert(). From there get the group(s) that you entered to your node field (from $node), $groups = $node->get('field_groups') and add the $node as group_content to each group, similar as done in the answer you linked.


Should a module implementing a filter delete the Drupal variables it uses, when uninstalled? I checked some modules implementing an input filter, and (if not in few occasions) I have never seen the modules removing the Drupal variables, whose names are in the format "module_name_$format," when they are uninstalled.

Since a module should normally delete its Drupal variables when it is uninstalled, is there a reason why an input filter module doesn't normally delete its own Drupal variables (e.g. this is already done by Drupal)?

A module should be responsible for cleaning up after itself when it is uninstalled. There is no reason not to do this, unless some other modules depend on those variables but I very much doubt this is a case. If they depend on a module they probably depend on the entire module, not just some variables defined by it.

I, for example, use htmLawed and out of curiosity checked the .install file; it does clean the variables defined in the format "module_name_format_%".

As a best practice you should drop all the tables and delete the variables defined by your module, doing this by implementing hook_uninstall in your .install file.

Writing .install files (Drupal 6.x)


How to show or hide some content on a node view using Page Manager based on the url destination? After certain fields have been set on the edit node form and saved, I don't want the node author to change these anymore and therefore I have created a new variant with a response code "301 permanent redirect" in Page Manager.

My redirect destination is set to %node:url?destination=no-edit-permission
And it does redirect the author to the intended node view (node_view in Page Manager).
But the reason I set this url destination is to be able to inform the user by showing a message at the top of that redirected page that says "You cannot edit this page any longer".
So how do I set such a message based on the destination in the URL?

It appears that there is a visibility rule that you can set on a particular content using the String: URL path.

Step 1:

take only the destination parameter: e.g. *?destination=no-edit-permission where the (*) asterisk is the wild card and represents whatever comes in front of that string.

Step 2:

In the Configure visibility rule for New custom content

set the option to:

  Allow access on the following pages

and tick the box:

  Reverse (NOT)

That should hide that content block based on the destination parameter. Yay!


update user's profile field from another form Here is what I need to achieve:

There is field "linkedIn url" in user's profile entity.
There is Event registration form on the website.
In the Event Registration form I would like to render field "linkedIn url" with value from the user's profile entity.
When user submits the Event Registration I want to save a value of the field to the database (to user profile entity of course).

Any suggestions? thx!

EDIT:
I implemented this functionality.
For those interested, complete source code is below:
(Note that I'm saving data to profile2!)

/**
*
* Implements hook_form_alter
*
*/
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form_id == 'registration_form') {
            $profile = profile2_load_by_user($user->uid); // Load profile2 data
            if ($profile['main']->field_linkedin_url) {
                $linkedin_url = $profile['main']->field_linkedin_url['und'][0]['value'];
            }
            $form['linkedin_url'] = array( // Add field to form
                '#type' => 'textfield',
                '#title' => t('Your LinkedIn profile'),
                '#default_value' => isset($linkedin_url) ? $linkedin_url : '',
                '#maxlength' => 255,
                '#size' => 60,
                '#description' => t('Please enter your LinkedIn profile URL'),
                '#weight' => 10,
            );
            $form['#submit'][] = 'entity_registration_custom_registration_form_submit'; // Call custom submit handler

    }
}

/**
*
* Custom Form Submit Handler
*
*/
function  MYMODULE_MYFORM_submit($form, &$form_state){
    global $user;
    $profile = profile2_load_by_user($user->uid); // Load profile2 data
    $profile['main']->field_linkedin_url['und'][0]['value'] =  $form_state['values']['linkedin_url']; // Set new value for Profile2 field
    profile2_save($profile['main']);
    drupal_set_message(t('Submit handler works!'));
}

You have to modify your form in a hook_form_alter : and the linked_in url will appear in the event registration form

function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'eventregistration_node_form'){

      // Find the user obj
      global $user;
      // Load all profile fields
      $account = user_load($user->uid);
      // Add the linked_in url in the event registration form
      // Supposing your field madhine name is ; linkedin_url
      // Supposing you use the link module for this field (if not, change ['url'] to ['value']
      $form['linkedin_url']['und'][0]['url']['#default_value'] = $user->linkedin_url['und'][0]['url'];
   }
}

If you don't want to expose the linked_in field during the form do this :

function mymodule_form_alter(&$form, &$form_state, $form_id){
   if ($form_id == 'eventregistration_node_form'){
     // Hide your field
     $form['linkedin_url'][und]['#access']  = false;
     //Add another submit function
      $form['actions']['submit']['#validate'][] = 'mymodule_eventregistration_validate_form_alter';
   }
}

// Your submit function
function mymodule_eventregistration_validate_form_alter($form, $form_alter){

     // Find the user obj
      global $user;
      // Load all profile fields
      $account = user_load($user->uid);
      // Add the linked_in url in the event registration form
      // Supposing your field madhine name is ; linkedin_url
      // Supposing you use the link module for this field (if not, change ['url'] to ['value']
      $linkedin_url = $user->linkedin_url['und'][0]['url'];

    form_set_value($form['linkedin_url'], array('und' => array(0 => array('url' => $linkedin_url))), $form_state);
}


Remove 'Your Name' field from comments display I want to hide/remove the "Your Name" field from the comments on a Drupal 7 site.

I am using the bamboo theme and Drupal 7.

I have seen a few threads for the but most are about removing the subject line, or are about Drupal 6 etc. I have tried a few different methods I have seen, but have not succeeded in getting this to work on Drupal 7 as of yet. Any advice?

The name input is not a required field,  so the easiest thing would be to hide it using CSS.

Try the following:

.comment-wrapper .form-item-name { display: none; }

You could also use hook_form_alter().  Check for the $form_id  for the comment form,  then set:
$form['FIELD NAME GOES HERE']['#access'] = FALSE;


How to theme one tab of a node I have hook_menu() configured to show a tab for every node at node/%node/summary.  The callback for that page returns the correct content, but I'd like to add a bunch of HTML to the page.

I believe I need to create a .tpl.php file in my custom theme.  How do I know what to name the file and make sure that the template is used only on the correct pages?

In Drupal 6, this would be:

 page-node-summary.tpl.php

More information on Drupal 6 template suggestions can be found at http://drupal.org/node/1089642

In Drupal 7, this would be:

 page--node--summary.tpl.php

More information on Drupal 7 template suggestions can be found at http://drupal.org/node/1089656

In either case, I'd grab the default page.tpl.php of your theme as a basis for it.


How can I override with my module the existing commerce_file_field_access function? I am trying to alter the way commerce_file module shows the product file in the Product display. Actually it is shown to all users owning sort of administrative permissions (such as administer commerce_file or administer commerce_field type).
Its format is:

label: file.pdf

This code is driven by the

commerce_file_field_access($op, $field, $entity_type, $entity = NULL, $account = NULL)

function in commerce_file module itself, it seems.

I would like with my_module to override this behavior to make the file visible to users that doesn't own those permissions but that have already bought the digital product and had license granted for that, but really don't know how to. (I already succeeded in disabling the add to chart button)

I am able to define if the user/buyer already bought it, but just cannot override the module access conditions to apply my rules.
I already tried defining another function like my_module_field_access(), but it doesn't seem to work...

How is it possible to override the hook_field_access() function already defined in commerce_file module?

As an alternative I was minding to replicate/copy that field and render it again without that access control, just in the defined conditions I define in my module.
To do that I tried with a my_module_preprocess_node() function, but didn't succeeded. The new $vars['elements'] is not rendered ...

I hope have been sufficiently clear. really any advice (on the best approach & way) would be very welcome. Wasted so many hours on this ... yet.
Thanks so much

hook_field_access() implementations are invoked by field_access() using the following code:

  foreach (module_implements('field_access') as $module) {
    $function = $module . '_field_access';
    $access = $function($op, $field, $entity_type, $entity, $account);
    if ($access === FALSE) {
      return FALSE;
    }
  }

The hook is not invoked for the module implementing that field, but for any module implementing the hook.

If you want to override what done by commerce_file_field_access(), you just implement hook_field_access() in your own module.
As field_access() immediately returns FALSE when a hook_field_access() implementation returns FALSE, you can only override what returned from commerce_file_field_access() if your hook is executed before commerce_file_field_access(). This means that your module, when it is installed, should alter the weight associated with it, and assign it a lower value than the value assigned to the Commerce File module. The following is an example of hook_install() implementation for achieving that; it is similar to the code executed in block_install().

function mymodule_install() {
  db_update('system')
    ->fields(array('weight' => -5))
    ->condition('name', 'mymodule')
    ->execute();
}

The same can be done in hook_update_N().

Any value lower than 5 actually works, as the Commerce File module uses the following code:

/**
 * Implements hook_install().
 */
function commerce_file_install() {
  // Make module weight heavier than field module
  db_query("UPDATE {system} SET weight = 5 WHERE name = 'commerce_file'");
}

The alternative of changing the weight of your module, which would influence when every hook in your module is executed, is to alter the order used for that specific hook implementations, using code similar to the following one.

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'field_access') {
    // Move mymodule_field_access() to the top of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations = array('mymodule' => $group) + $implementations;
  }
}


Trying to Conditionally Add JS File to page if in a paragraph block reference on that page I am not sure how to accomplish this...

I want to have a custom block that I have created and referenced via paragraphs to implement code in that block and push it into the header of the page. The idea is that we want to have single pages that run specific JS files and this is the way for the content author to place these files on the pages that they want. If there is a better way to do it, I am open to suggestions.

Here is where I am now:

I have a custom block that I am referencing via paragraphs in pages that will house the JS files. I believe I need a preprocessor script for this, but I am having a lot of issues with figuring out what kind of preprocessor I need.

Here is what I have but I think it is totally wrong and definitely incomplete:

if ( isset($vars['content']['#block_content']) ) { // check for custom content
    if ($vars['content']['#block_content']->type[0]->getValue()['target_id'] == 'js_file_block') { // only run on js_file_block types

      $vars['foobar'] = $js_files_page; // export var to twig
    }
  }

I need to be able to make more than one file load if added to the block, and I need it to attach to the header of the page that the block is referenced from. Can anyone point me in the right direction?

I am sure I need to add a $routematch and other things but I am not sure.

In Drupal 8 drupal_add_js() as well as drupal_add_library() and drupal_add_css() were removed in favor of #attached. Means you now can use the #attached key in any render array or preprocess or build function to attach your library only where you need it. Please read the following articles on DO:

[Docs] Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

[Docs] Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module

[Forum] Adding js to the block through module Drupal 8


How to block the user after a few failed logins modules like login security deny the user IP after afew failed logins. there are softwares that randomly generate new IP for user so it makes such modules useless. sending cookie to the user browser is also unreliable because the user can disable accepting cookie. What is the most reliable solution to block some users?

Rules is what comes to mind. You can react to the user logging in I guess.


Is there any away to randomize a display message in rules? I would like to disable drupal's standard message when a new node has been saved and then via Rules (or any other recommendations) provide a pool of random messages to be displayed to the end user when a node is then saved. They will essentially say the same thing, but just in a different way.

The display message can be customized by following this procedure. You might also want to write a custom module, which may enable you to control your message display by user role.

If you want to display the status message in a different way, (there is a module for that ;-) too) try Better Messages module.

  Better Messages is a very simple module that provides "Popup-like" Drupal messages.


Custom View Filtered by Taxonomy Term I've been reading sites all day trying to figure out what I'm doing wrong or missing, perhaps you can help me. I can't seem to find the right explanation or tutorial.

Situation:

I have a custom View (Content Pane) that generates a Grid of nodes from my Video content type (we'll call it Video Gallery). I created a Page at /videos which includes that Video Gallery content pane in one of the Panels. This is all working very nicely.

I want to be able to filter the results though based on the url, so if they browse to /videos/foo then I'd like to show only the Video nodes which are tagged with the term "foo". This seems to work just fine when I preview the results on the View screen. I've added a Relationship to the Term and added a Contextual Filter on the term id (converted from name). When I type "foo" in the Preview with Contextual Filters box and click Update, then the preview grid below shows exactly what I'd expect (only the Videos tagged with "foo").

My problem:

The view seems to work just fine, but I can't seem to get it to work when actually viewing the page. How do I get my Page configuration to pass along the term argument to the View so that the View can properly filter the results?

I set the path on my custom Page to be /videos/!videotype, I've set the %videotype argument so the Context is "Taxonomy term: ID" (with Argument Type = "Term name").. but I can't seem to figure out the rest of the settings.

In my view, I've named my contextual filter "Video Tag Filter" and in my Page configuration, when I edit the Settings on the above View Content Pane, it gives me a dropdown labeled "Video Term Filter" (which is different from Video Tag Filter, I'm not sure where the Video Term Filter name comes from, I've looked through all the menus I can).

It doesn't seem to work though. Can you help me out?

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

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


Assigning content from one user to another user automatically after a payment I am evaluating Drupal for a new project but I am not very experienced with Drupal so far.

The project is based around a custom content type created by role-A user and then re-assigned to role-B user once role-A has accepted the re-assignment and role-B user has made a payment. When the node is re-asssigned to role-B user, role-B user will only be able to modify one of the fields of the node.

Does anybody have any ideas of how to do this without the need for the admin to manually re-assign each node to a different user and change the permissions for the fields?

Use the Node access user reference module for this purpose. About this module (quote from its project page):

Gives content access permissions to users for content that references the users with User reference or Entity reference.
This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

And use the Entity reference module to implement your "assignments".
To actually "use" (configure) these settings, refer to the module's README.txt, which includes these instructions:

Create a field to reference users in a content type using the Field UI.  The field's configuration page will contain the settings for Node access user reference. For detailed instructions on using the Field UI see:
https://www.drupal.org/documentation/modules/field-ui

Possibly you also might want to use the Field Permissions module.


Where do pending drush database updates live? I'm using drush to update the modules on our drupal site. I updated the video_embed_field module to the latest version.

This update required 3 database updates to occur, 7006, 7007, and 7008. For some reason 7006 failed as documented here. That link includes a patch which should fix the problem, the only issue is I have no idea where the patch needs to be applied. i've applied patches to drupal modules before, but video_embed_field does not appear to have a directory in sites/all/modules which is where I think the patch ought to go.

When I run drush updb it wants to apply those three database updates, but I can't find them stored anywhere in the file system (or any references to video_embed_field at all). Are these database updates stored in a table in the database, is their a folder somewhere I'm not looking at? Is there another folder where modules get placed?

Drupal will look in /modules and /sites/*/modules if the site was installed on top of the default profile. If you're using a distribution or other contrib/custom profile then it'll also look under /profiles/[name-of-profile].

SELECT filename FROM system WHERE name = 'video_embed_field'

will tell you exactly where Drupal is looking for the module you're trying to find.

  Are these database updates stored in a table in the database[?]

I haven't looked at Drush, but as far as core's update.php goes, no. The .install file of each enabled module is checked to see if it has any update functions with a schema greater than the currently installed schema. I'd imagine Drush does the same thing, no real reason for it to do things differently.

If that assumption holds, then you basically couldn't be seeing those updates as options unless the module is somewhere in the file system (or at least a PHP file that will be included in a normal bootstrap containing a function called video_embed_field_update_7123() or similar).

So keep looking, it's likely to be there somewhere!


Can't connect to remote DigitalOcean database I am attempting to connect an existing Drupal 8 site to a DigitalOcean managed Database.

The connection info I've received from DigitalOcean:

username = digitaloceanadmin
password = password
host = nameofmydbcluster.db.ondigitalocean.com
port = 25060
sslmode = REQUIRED

I've made the adjustments to settings.php:

$databases['default']['default'] = array (
  'database' => 'dbname',
  'username' => '...',
  'password' => '...',
  'prefix' => '',
  'host' => 'dbclustername.db.ondigitalocean.com',
  'port' => '25060',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

However, I'm getting the following error:

PDOException: SQLSTATE[HY000] [2054] The server requested authentication method
unknown to the client in ...

More errors when I drush cr:

In Connection.php line 416:

  SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client

In Connection.php line 416:

  PDO::__construct(): The server requested authentication method unknown to the client [caching_sha2_password]

I am running Drupal 8.8.1 with php7.2. The DB version on remote is MySQL 8.

Any help would be greatly appreciated.

I was able to resolve this from the info found here:

https://skoop.dev/blog/2019/10/04/PHP-and-the-DigitalOcean-MySQL-cluster/

The problem stemmed from the default authentication method for MySQL v8 is caching_sha2_password, which the article above suggests is not supported by php yet.

As the article suggests, we can switch back to the old authentication method with the following query:

ALTER USER 'myuser'@'%' IDENTIFIED WITH mysql_native_password BY 'thepasswordyouwant';

After making this alteration to the dbuser, I was able to connect to the digitalocean database without issue.


Kanban-style view : Group nodes in a view into columns based on a field value I have a custom node type in Drupal - Order - which has a status field. The status can have three values.

What I would like to do is create a view in which orders are grouped into columns based on their status - essentially a primitive Kanban board - and the columns are ordered in a particular way.

Is this possible and if so, how?

I don't think it is possible right now without custom programming (either within a theme or custom module)

You can probably get started with grouping your view based on the status field and than using CSS in your theme (display:inline or float: left) you can get all groups next to each other.

There could be more sorting criteria for each column within the view.

For extra functionality like dragging/dropping within status areas (changing status) you will need to create your your own module to handle drag drop events and do ajax calls to the backend.

There was some work done for openlucius (drupal 7) that you can look at https://www.drupal.org/project/openlucius_board


Why is Drupal urlencoding in tpl output? In Drupal 7, I have

<?php print $some_content; ?>

in page.tpl.php and when the string $some_content contains a URL (i.e., <a href="some-url?parameters=1|2|3|5"> ... )

the URL gets urlencoded and parameters is shown as:

parameters=1%7C%7C2%7C3%7C5

where | is substituted by %7C. For aesthetic reasons I want Drupal to stop this conversion, but even if I try with urldecode(), it does not work, as it seems to be hard-coded on Drupal core itself.

How can I override this which is just a simple line in pure PHP?

Drupal is not URL encoding in the template output, it doesn't try to make that sort of blind string replace anywhere.

If the URL was prepared using any of Drupal's url() function, which is likely if you're using well written modules, then you should expect the query parameters to be properly encoded.

Drupal tries hard to conform to standards, you're probably going to find it more trouble than it's worth to get it to produce an invalid URL (which your desired result would be); it would be easier to simply write your own invalid version of url() and use that to prepare the content.


How to show only updated nodes in VIEWS I am creating a View in Drupal 7 for a particular content type.
I want to add filter to show nodes which are updated. When I am adding Node Update Date field, it is asking for operator and Value to compare with. But I can not provide Updated date of each node.

Then I also tried hook_views_query_alter to alter the query. When I am adding Query Value to node.created field it take it as a string or you can say Value.

Can someone help me to achieve this?

You may be able to use hook_views_query_alter to load only nodes which have node.updated value equal to NULL or ''.


Find all aliases for a given node I'm currently working with a client and running some scripts to generate reports (orphaned pages, etc). Right now, I need a way to get all possible registered aliases for a node. Right now, I'm using

$node = node_load($nid, NULL, TRUE);
$nurl = 'node/' . $nid;
$alias = drupal_get_path_alias($nurl);

I'm realizing, though, that the client has more than several pages where multiple aliases lead to the same node. Is there a function to retrieve an array of possible aliases?

Thanks!

You can do it with a database query

$aliases = db_query('
  SELECT alias
  FROM {url_alias}
  WHERE source = :source
', array(':source' => 'node/' . $nid))->fetchAll();

You may need to modify things a little if you have a multilingual site to take the language column into account.


Custom action context for order I'm trying to write a custom RulesAction to perform an operation after an order status is updated. Basically, I want to perform this operation after checkout is complete (but this event doesn't exist anymore in D8).

namespace Drupal\my_module\Plugin\RulesAction;

use Drupal\uc_order\OrderInterface;
use Drupal\uc_order\OrderStatusInterface;
use Drupal\rules\Core\RulesActionBase;

/**
 * Definition of the action performed.
 *
 * @RulesAction(
 *   id = "my_action_id",
 *   label = @Translation("My action label"),
 *   category = @Translation("My module"),
 *   context = {
 *     "entity" = @ContextDefinition("entity",
 *       label = @Translation("Entity"),
 *       description = @Translation("Specifies the entity, which should be saved permanently.")
 *     )
 *   }
 * )
 */
class MyActionClass extends RulesActionBase {

  /**
   * Def.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *    The order update triggered by rules.
   */
  protected function doExecute(OrderInterface $order) {
    // @TODO.

  }

}

My action do come in rules, I have set it up after the event: After updating order (rules_entity_update:uc_order)

When triggering it I get the error :
If I set the context to entity (I've looked and no context is defined by ubercart for order):

  The website encountered an unexpected error. Please try again
  later.Drupal\Core\Entity\EntityStorageException:
  Required context entity is missing for plugin my_action_id. in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save()
  (line 783 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

If no context is set :

  The website encountered an unexpected error. Please try again later.
  TypeError: Argument 1 passed to
  Drupal\my_module\Plugin\RulesAction\MyActionClass::doExecute()
  must implement interface Drupal\uc_order\OrderInterface, none given in
  Drupal\my_module\Plugin\RulesAction\MyActionClass->doExecute()

So my questions are :

Do I need a context for rules action to work ?
If yes, how can I find it and get it working ?

Here are the documentations I find (but rules is unfornately not very well documented for now):

Rules documentation for dev |
RulesAction examples |
Context documentation

So the context is mandatory and it is actually important because it sets the data you want to fetch when the rule is triggered.

I just needed to set the context to the good entity as follow.

"entity" = @ContextDefinition("entity:uc_order",

The working annotation is the following.

/**
 * Definition of the action performed.
 *
 * @RulesAction(
 *   id = "my_action_id",
 *   label = @Translation("My action label"),
 *   category = @Translation("My module"),
 *   context = {
 *     "entity" = @ContextDefinition("entity:uc_order",
 *       label = @Translation("Entity"),
 *       description = @Translation("Specifies the entity, which should be saved permanently.")
 *     )
 *   }
 * )
 */

Then you are able to fetch the current uc_order in the administrative page.


How to remove nodes with the same title from views listing? Just this, how to remove nodes with the same tilte from views listing?

These nodes are NOT duplicated node, they only have the same title.

You can achieve this goal via using Views Distinct Module.

For more information go through the project documentation.


Conditionally show fields viewing a node (not in the node add form) I know conditional fields can be use to create CCK optional fields, but I need something similar to display part of a node, according to user decisions.

I will have a question "do you like cats?", then the user will be shown another question according to what they answer to the first one, and so on.

I was thinking to create this all in one node

field1 -> answer 'yes' -> show field2,
field1 -> answer 'no' -> show field3),

but I guess this could be done the same with multiple nodes

node1 -> answer 'yes' -> show node2,
node1 -> answer 'no' -> show node3.

Do you have any module to suggest me to reach my goal?

If you haven't solved this yet, the Webform Conditional module might help.

  This modules enhances the existing Conditional Rules of the Webform Module. It adds the ability to make components dependent on select components(i.e. listboxes, radio buttons, and checkboxes) that appear on the same page.


Views and joining content types on specific field in Drupal 7 How can I 'LEFT OUTER JOIN' or 'LEFT JOIN' using Views in Drupal 7.

Here is what I'm trying to do, using an example from Wikipedia:

I have 2 content types: Employee's and Department's (tables below)

The "DepartmentID" noted in the Employee Table below in my case would be the NodeID of the department from the "Department" custom content type.

How can I use Drupal 7's Views module to Display a list of employees with the department name pulled from another content type as noted in the graphic below?

(The SQL statement below is really what I'm hoping to be able to do with the Views module, the table is the output I'm hoping to achieve.)

In views 3 you have the relationships which manage JOINS between tables.
First you add your relation with the table and then in the next screen you can select Require this relationship.

If you check this checkbox, a LEFT JOIN will be made between the tables, if you uncheck it, it will generate a LEFT OUTER JOIN.


Why are there so many different ways to translate menus? I'm very confused about the way Drupal 7 translates menu items. I have many modules installed, so I'm not sure which would be relevant to state; in fact, I don't have my head fully wrapped around which modules do what and what they are dependent on.
I'm working on a bi-lingual website, in English and French. I noticed two different ways to create menues with translation. Let me outline the steps and results for both, and you can explain to me why these differences exist and how to effectively apply these differences.
Method 1

Go to Structure>Menu>(select the menu you want)
Click Add Link
Provide a "Menu link title" and "Path"
Under language, select English
Save
Translate this menu item into french

Result of Method 1

There are TWO menu items under Structure>Menu>(select the menu you want), one for each language item.  Additionally, I can no longer convert a menu's languge from English or French back to Language Neutral...what's up with that?

Method 2

Go to Structure>Menu>(select the menu you want)
Click Add Link
Provide a "Menu link title" and "Path"
Under language, select Language Neutral
Save
Go back to the edit form of the menu link you just saved, change language to English and save
Translate this menu item into french

Result of Method 2

There is ONE menu item for the link you added under Structure>Menu>(select the menu you want).  But when you edit that menu item, you will see the french translation under the translate tab.

Why is the Result of Method 1 different from the Result of Method 2?  Why is it that in Method 1, each translation is a new menu item, but in Method 2, translations are grouped together?
It is so easy for a user to forget to select a language when creating a menu item, which unintentionally creates a parallel track of information in the site (it's almost like a duplicate site where we lose the correlation between english and french pages ).  Fixing this after the fact would be so troublesome!

Method 1 points to the node translation. Method 2 is a translation of the link but goes to the same path. For most people method 1 is the way to go. But method 2 could be handy as well.

Maybe life would be easier if you just build it in one language and use Google Translate Elements JS addon. It really depends on the needs of your users. For my client I had to use method 1.


Update url query upon form submission I am trying to append a variable on the URL through a custom submit function. Is that possible?

My issue is that I am coming to the node/%/delete from different pages. I want to modify the delete form if the user comes to it from the node/%/edit. How can I detect this?

As @Clive suggested I'll try to add a query param in the following structure:

actions (Array, 5 elements)
  #type (String, 7 characters ) actions
  submit (Array, 5 elements)
  preview (Array, 5 elements)
  delete (Array, 4 elements)
    #type (String, 6 characters ) submit
    #value (String, 6 characters ) Delete
    #weight (Integer) 15

You should use the hook_node_access in your custom module.

For Example -

/**
 * Implements hook_node_access().
 */
function MODULE_node_access($node, $op, $account) {

  if ($op == "delete") {
    // If no user object is supplied, the access check is for the current user.
    if (empty($account)) {
      $account = $GLOBALS['user'];
    }
    // You can add your own condition check here...
    return user_access("delete content", $account) ? NODE_ACCESS_ALLOW : NODE_ACCESS_DENY;
  }

  return NODE_ACCESS_IGNORE;

}


What is the best way to make sure Array in PHP are closed correctly I wonder how to determine when to close an array. I edited a aliases.drush.php and added a database array but now, while I have multiple array I got a syntax error. Is there a easy rule to remember how to close an array without getting syntax errors when a file has about 300 lines?

It is no longer necessary to put databases into your Drush alias file. In older versions of Drush, a databases record in an alias file could be used to allow Drush to do an sql-sync to or from a remote system that did not have Drush installed.  This feature is no longer supported, and the databases record is no longer necessary.

To answer your specific question, though, any php nested array must have balanced parenthesis.  Make sure that you have one ( for every ). Folks usually keep track of their parenthesis via indentation -- add a level of indentation for each (, and remove it for each ).


Ubercart - how to get order information from order ID? How to get an object of Order (or something similar - details of an order!) by providing order id? Perhaps, some kind of code like: $order = order_load($orderId);

I'm new to Ubercart (3.x)/Drupal (7.x) and searched the title but found no solutions.

I need to create a view/page by custom module which displays "My Purchases" or "My Sells"

I need to get complete Order details, by providing order-id. Also need the creator/seller and buyer info of the order.

Can someone give me some PHP example/other ways possibly using a View?

Using the Ubercart API at api.ubercart.me, it is

$orders = uc_order_load($orderId);

$orders is an array, so $order = $orders[0];

See:
http://api.ubercart.me/api/drupal/ubercart!uc_order!uc_order.module/function/uc_order_load/7


Adding WYSIWYG to webform email template field I want to enable the WYSIWYG editor so I can create HTML mail from webform email templates. (Yes, I know some people don't like HTML in emails.)
I have created a module, and I'm using this code:

function mymodulename_form_alter(&$element, &$form_state, $context) {
  if (isset($element['template']['template'])) {
    $element['template']['template']['#wysiwyg'] = true;
    $element['template']['template']['#type'] = 'text_format';
  }
}

This is great, and the WYSIWYG is enabled. Unfortunately it changes the values from a string to an array, and I can't figure out how to convert them back again. I was hoping this would help, but hook_field_attach_presave() doesn't seem to fire for that form. In fact, I can't find any hooks that fire for that form.

Any suggestions?

HTML emails have a different standard than WYSIWYG editors. For example HTML emails use tables instead of divs, you can't use paddings etc.

So I don't think that HMLT email creating with WYSIWYG editor is a good idea...


How to remove malicious scripts from admin pages after being hacked? The site running Drupal 7 was hacked and every administration page, e.g.

http://www.anysite.com/en/admin/dashboard

contains script tag in head section with malicious src attribute, e.g.

<head>
    ...
    <script src="..."></script>
</head>

Those three dots in the src attribute was only for example same as the three dots line above :) In real code there is link to malicious web gymweb.it.

How can I remove this script tag? How the head section of admin pages is constructed?

If you suspect that your code has been altered, you should track any malicious code which could infect your webroot.

If you've access to the server terminal, try the following suggestions, otherwise sync the files into your local machine in order to run below commands.

Here are few general solution to get rid of the attacker:

Use some tools to scan for malicious PHP files (e.g. php-malware-finder, php-malware-scanner, phpscanner).
Look for your webroot for any suspicious files consisting base64_decode/eval which most commonly are used for obfuscation, e.g.

grep -R return.*base64_decode  .

If you found one, probably you've multiple of them. If so, please check: How to get rid of eval-base64_decode like PHP virus files thread for further suggestions.
If you know some specific pattern of the malware appearing in your source code (which you do), try scanning your code base for this name, e.g.

grep -R gymweb .

And depending on where these URLs were added, remove extra code or restore to the original version (either from VCS history or your recent backup before the infection).

If above won't help, try these suggestions which are more Drupal oriented:

When using code under version control (like Git), find the files which are not suppose to be there (git status) and remove them (git clean -f .).
Upgrade your Drupal core, to replace any modified files (drush up drupal).
Upgrade contrib modules using drush (drush upc --no-core).
Also scan your entire database for this name:

drush sql-dump --ordered-dump | grep gymweb

If this still won't help, compare the code base from the backup before the infection with the current one (either by diff -r, using some diff GUI tool or use Git).

Check also:

How to get rid of eval-base64_decode like PHP virus files?
What does this malicious PHP script do?


Redirect to a specific page when user update their profile Is there any way to redirect the user after save their profile information.

I would like to redirect them to a specific page.

To be clear, here is the Flow:

User go in his profile
He change his password information
The user click on Save Button
The information is save and I want to redirect him on a specific page (node/xxx)

You can add a custom submit handler to the user edit form and then do the redirect there:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'user_profile_form') {
    $form['#submit'][] = 'custom_submit_function';
  }
}

function custom_submit_function($form, &$form_state) {
  drupal_goto('node/xxx');
}


Can a content entity type have a bundle which is a configuration entity type as with the contact form? What is bundle_entity_type for @ContentEntityType when id = contact_message and where contact_message is @ConfigEntityType?
Can a configuration entity Type be a bundle of a content entity type?

core/modules/contact/src/Entity/Message.php

/**
 * Defines the contact message entity.
 *
 * @ContentEntityType(
 *   id = "contact_message",
 *   label = @Translation("Contact message"),
 *   label_collection = @Translation("Contact messages"),
 *   label_singular = @Translation("contact message"),
 *   label_plural = @Translation("contact messages"),
 *   label_count = @PluralTranslation(
 *     singular = "@count contact message",
 *     plural = "@count contact messages",
 *   ),
 *   bundle_label = @Translation("Contact form"),
 *   handlers = {
 *     "access" = "Drupal\contact\ContactMessageAccessControlHandler",
 *     "storage" = "Drupal\Core\Entity\ContentEntityNullStorage",
 *     "view_builder" = "Drupal\contact\MessageViewBuilder",
 *     "form" = {
 *       "default" = "Drupal\contact\MessageForm"
 *     }
 *   },
 *   admin_permission = "administer contact forms",
 *   entity_keys = {
 *     "bundle" = "contact_form",
 *     "uuid" = "uuid",
 *     "langcode" = "langcode"
 *   },
 *   bundle_entity_type = "contact_form",
 *   field_ui_base_route = "entity.contact_form.edit_form",
 * )
 */
class Message extends ContentEntityBase implements MessageInterface {

core/modules/contact/src/Entity/ContactForm.php
which says bundle_of ==> contact_message

/**
 * Defines the contact form entity.
 *
 * @ConfigEntityType(
 *   id = "contact_form",
 *   label = @Translation("Contact form"),
 *   label_collection = @Translation("Contact forms"),
 *   label_singular = @Translation("contact form"),
 *   label_plural = @Translation("contact forms"),
 *   label_count = @PluralTranslation(
 *     singular = "@count contact form",
 *     plural = "@count contact forms",
 *   ),
 *   handlers = {
 *     "access" = "Drupal\contact\ContactFormAccessControlHandler",
 *     "list_builder" = "Drupal\contact\ContactFormListBuilder",
 *     "form" = {
 *       "add" = "Drupal\contact\ContactFormEditForm",
 *       "edit" = "Drupal\contact\ContactFormEditForm",
 *       "delete" = "Drupal\Core\Entity\EntityDeleteForm"
 *     }
 *   },
 *   config_prefix = "form",
 *   admin_permission = "administer contact forms",
 *   bundle_of = "contact_message",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label"
 *   },
 *   links = {
 *     "delete-form" = "/admin/structure/contact/manage/{contact_form}/delete",
 *     "edit-form" = "/admin/structure/contact/manage/{contact_form}",
 *     "collection" = "/admin/structure/contact",
 *     "canonical" = "/contact/{contact_form}",
 *   },
 *   config_export = {
 *     "id",
 *     "label",
 *     "recipients",
 *     "reply",
 *     "weight",
 *     "message",
 *     "redirect",
 *   }
 * )
 */
class ContactForm extends ConfigEntityBundleBase implements ContactFormInterface {

This may be easier to understand with Nodes, since Nodes have been used by almost every Drupal site builder.

Nodes are a Content Entity. Nodes have bundles (aka content types). For example, a blog. Now, to define the blog type, a new Config Entity is created - the Node Type entity. Config entities have keys. The key for the blog Node type is 'blog'. This key identifies the node type. But the blog bundle is still a Node entity, and therefore is a Content Entity.

The contact form works the same way.

So to answer your question, no, bundles of Content entities cannot be config entities, as bundles are just a subset of the original entity, which is a Content entity. But a Config entity is used to define the bundle (allowing the types to be exported as configuration).

You could almost compare it to the 'type' field on a Content Entity being an Entity Reference to a Config entity that defines the type.


How to update Drupal custom module after changing .install file I am working on a pre-created Drupal 8 project that has a custom module called CCA(named out of project title). I have done the below update in the .install file to add a new column to the backend via Drupal.
function cca_update_8902 (&$sandbox) {
  db_add_field('cca_findings', 'cca_topic_id', array(
    'type' => 'float',
    'not null' => FALSE,
    'description' => 'interim fields addition',
  ));

How do I update the module in Drupal after this change has been made? Can someone guide on next steps to update my custom module in Drupal so that this change will be implemented? Thanks!

Visit /update.php on your site when logged in as admin, or use drush updatedb
Note that in addition to changing the table in the hook_update_N(), you must also change the schema of the cca_findings table in hook_schema() so that new installs of your module will have the proper table structure. Update functions are not used on new installs of your module.


How do I change the permalinks to #1, #2, #3? I would like to change the comment/forum links to something like:

TOPIC:

#1

#2

#3

Do you have any idea on how should I do this?

Advanced forum provides what you are looking for out of the box (a #number permalink in the upper left corner of the post) among tons of other useful features for a forum.

You could either simply use that module, or you could look at it's template files to see how it's done. The relevant code seems to be in includes/advanced_forum_preprocess_comment.inc and looks like this.

  /* Linked post number */
  if (!isset($post_number)) {
    static $post_number = 1;
  }

  $posts_per_page = variable_get('comment_default_per_page_' . $node->type, 50);

  $page_number = !empty($_GET['page']) ? $_GET['page'] : 0;
  if (!$page_number) {
    $page_number = 0;
  }

  $post_number++;

  $linktext = '#' . (($page_number * $posts_per_page) + $post_number);

  // Permalink
  //  You can erase next 3 lines if you wish to use built-in Permalink.
  //  Template adjusted: $post_link -> $permalink
      $uri = entity_uri('comment', $comment);
  $uri['options'] += array('attributes' => array('class' => 'permalink', 'rel' => 'bookmark'));
  $variables['permalink'] = l($linktext, $uri['path'], $uri['options']);


How can I translate the  option for a grouped exposed filter in Views? I have an exposed filter in Views that uses the Grouped filters option to present choices to users.  By default, an <Any> option is provided.  My site is multilingual, so I want to translate this:

I am using the i18n suite of modules as well as i18nviews.  I first searched using the Translate interface screen at admin/config/regional/translate/translate and I translated <Any>; however, when viewing the page, <Any> is still displayed, not the translated value.

There appears to be no option to customize the <Any> text within the Views UI.

I am able to translate the (user-defined) grouped filter options using i18n and i18nviews through the Translate Interface screen.

What do I need to do to translate <Any>?

It turns out that there is a bug in Views at the moment, so I wrote a patch.

Once you apply the patch (or once the patch is committed to Views), you can translate  as part of the built-in interface through the Translate Interface screen.


Is there a module that provides a drop-down select box on anode/add form to select a page template to be applied to a node? Basically you have a bunch of different page templates in your theme directory.

page.tpl.php (default)
page-myTemplate1.tpl.php
page-myTempalte2.tpl.php

When you create a new node, I want a drop down list that lets you choose which template will be used to wrap around this node so that when the node is viewed, it uses the corresponding page template file. Does this module exist? :)

This can be done using Display Suite Extras - View Mode Switcher (and very nicely it works too) but only works for nodes at present. Basically you enable view mode switcher in the extras settings page, add the view mode switcher field to each of the displays you wish it to be available on (all of which are customisable template files through display suites layout template system). Now when you visit the node you will get a list of the display modes (which can be labelled as you like) to switch between inline using ajax.


Why hook_form_alter implementation is being called twice? I have a module where I implemented hook_form_alter:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  krumo($form_id);
}

And I always get each form_id displayed twice. Duplicate form_id for each form!! The problem is that if I add in hook_form_alter line like:

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

then this function is getting called twice, and this follows errors. I have no idea why Drupal calls hook_form_alter implementation twice, possibly you have. Thank you in advance!

I ran into the same problem today, a hook_form_alter() override in a custom module was being called twice on every form.

My custom module's name was "project_name" and my theme was also called "project_name" (folder/machine names). I uninstalled my custom module and renamed it to "project_name_different" and re-installed it. After that change, hook_form_alter() only gets called once.

Don't know the super technical explanation for this answer, but generally Drupal doesn't like duplicate names across modules and themes, so make sure machine names are unique across all modules and themes living within your site.