Adding extra fields to Site Contact Form This seems strangely difficult to me. What I thought would just be a case of adding extra fields a bit like adding fields to Content Types. But no. I can't locate any facility to add say a phone number field to the Contact form? Anyone out there know?

Expecting forms fields to be configured like content types is an over-generalization. Content types are for content (text, image, etc.) of the website, and more specifically, in Drupal, for nodes (the main piece of content in Drupal). Using the Field and Field UI module, one can easily adds fields to content type using a Web UI. Except for some specific cases, a form is not part of the content of a website but rather a way for users to add and edit information, sometimes content and sometimes not.

To customize (i.e. alter) a form in Drupal, the usual way is to create a custom module that implements the hook_form_FORM_ID_alter hook. This way, you can add form elements to existing forms provided by other modules. To use the information for fields added to the contact form this way, you will also need to alter the sent mail using an implementation of hook_mail_alter(). The following guide walks you through both steps in Drupal 7. (Note also this comment)

A non-code solution is to use the Webform module that provides a form content type and let you add forms as content to your website. These forms are configurable through a Web UI. Various processing steps can be configured for the information submitted through these forms. One of them is email sending. Using it for a custom contact form is a common use case. Webform comes with its own concepts and extension points. While it may prove to be a easier and faster solution for a one time simple forms, it may also reveal to be over-sized and complex to customize once a certain features threshold has been reached. The cost to add extra-features to a webform can then outperform the gain of avoiding writing a custom module in the first place.


How do I auto generate products via attribute? I have a shoe store, as you know, Drupal Commerce allow us to control each Attribute of Shoe like Color and Size.

This is my problem :

I have 2000 shoe styles, each style has sizes from 5-12 (6US to 12US)
It mean that everytime I add new style, I have to create 8 products for 8 sizes. Im using Clone Product Module, it's working very well, but how can I save my time :

It mean that when I create New Shoe Style (Node Products Display)
--> node/add/shoe-style
--> the system will auto generate 8 products (Size) for me, it depend on how many value in my attribute field (Size attribute has 8 value and system will create 8 new product), and now what we need to do is update something to each product.

Assuming you are using Drupal 7, you've got a couple of options:

Commerce Migrate will let you create products as part of a migration. It's a bit more time consuming but it's repeatable and is very powerful.
You can use Commerce Bulk Product Creation to create products based off of fields in the UI. This gives the ability to create those products once and isn't repeatable.


How do you create a custom Panels layout in an Omega sub-theme? I'd like to create a new custom Panels layout based on one of the Omega Panels layouts and put it in my Omega sub-theme, but I can't seem to find a way to do this.

So far I've added the following to my sub-theme .info file:

; PLUGINS
plugins[panels][layouts] = panels/layouts

I have then taken the layout I want to work from (omega_12_twocol_6_6_bricks) and renamed and copied this to sites/all/themes/mycustom/panels/layouts/omega_12/mycustom_12_twocol_6_6_bricks. I then renamed all the files within the mycustom_12_twocol_6_6_bricks directory replacing 'omega' with 'mycustom'. Then, within my mycustom_12_twocol_6_6_bricks.inc file I changed:

function omega_omega_12_twocol_6_6_bricks_panels_layouts() {
  $items['omega_12_twocol_6_6_bricks'] = array(
    'title' => t('Two Column 6-6 bricks'),
    'category' => t('Omega: 12 Column Grid'),
    'icon' => 'omega_12_twocol_6_6_bricks.png',
    'theme' => 'omega_12_twocol_6_6_bricks',
    'admin css' => '../omega_panels_admin_12.css',
    'regions' => array(
      'top' => t('Top'),
      'left_above' => t('Left above'),
      'right_above' => t('Right above'),
      'middle' => t('Middle'),
      'left_below' => t('Left below'),
      'right_below' => t('Right below'),
      'bottom' => t('Bottom'),
    ),
  );

  return $items;
}

to

function mycustom_omega_12_twocol_6_6_bricks_panels_layouts() {
  $items['mycustom_12_twocol_6_6_bricks'] = array(
    'title' => t('My Custom Two Column 6-6 bricks'),
    'category' => t('Omega: 12 Column Grid'),
    'icon' => 'mycustom_12_twocol_6_6_bricks.png',
    'theme' => 'mycustom_12_twocol_6_6_bricks',
    'admin css' => '../omega_panels_admin_12.css',
    'regions' => array(
      'top' => t('Top'),
      'left_above' => t('Left above'),
      'right_above' => t('Right above'),
      'middle' => t('Middle'),
      'left_below' => t('Left below'),
      'right_below' => t('Right below'),
      'bottom' => t('Bottom'),
    ),
  );

  return $items;
}

I also copied the admin css file into the relative directory as stated in the .inc file, cleared all cache and ran update.php, but I can't see my new layout when adding a new Panel.

The module versions I'm using are:

Drupal 7.22
Panels 3.3
Omega 3.1

Any help here appreciated.

Many thanks

The basic process is:

Edit the MYTHEME.info file:

; PLUGINS
plugins[panels][layouts] = panels/layouts

Create a directory in panels/layouts/mypanel

Create your include panels/layouts/mypanel/mypanel.inc

/**
 * Implements hook_panels_layouts().
 */
function mytheme_mypanel_panels_layouts() {
  $items['mypanel'] = array(
    'title' => t('My Panel'),
    'category' => t('My Site'),
    'icon' => 'mypanel.png',
    'theme' => 'mypanel',
    'regions' => array(
      'top' => t('Top'),
      'left' => t('Left column'),
      'right' => t('Right column')
    ),
  );

  return $items;
}

Create your 50x75 mypanel.png, and place it as panels/layouts/mypanel/mypanel.png

Create the template file as panels/layouts/mypanel/mypanel.tpl.php

<div class="panel-display mypanel" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>>

<?php print $content['top']; ?>

<?php print $content['left']; ?>

<?php print $content['right']; ?>

Upload, clear cache, and see if you can make a panel page.  Nine times out of ten, the problem with Panels picking up custom panel layouts has to do with a misnamed include or template file, which I suspect is your problem.


How to move Drupal 8 with composer, to another server We've recently got a few Drupal 8 sites, and needed to move them away from a plesk server. The plesk server is now shutdown for good, and we need to restore the sites on our cpanel server. The sites are using composer, which we don't have any experience with. On top of that, we are not very familier with the drupal structure or system.

We've tried to restore the sites by copying the files relatively with the composer "vendor" folder and replacing strings in the entire project, but it didn't seem to work, or maybe we missed something..

We've also tried to create a new composer project and copied the drupal project into the newly created composer project, but that gave an infinite loop that used up all the ressources and gave an 503 error in the end.

Does anyone know how to move/migrate a Drupal 8 site with composer, from one server to another?

As already said in the comments composer does not have a way to help with transfering a site.

With a site build with composer I usually zip the composer directory (which includes the drupal directory) and get a database dump.  On the receiving server just copy the files on a similar directory structure and import the database.

For going from plesk to cpanel you probably have to set the document root correctly.  In plesk its usually httpdocs/docroot but in cpanel it should probably be set to public_html/docroot

Also I don't suppose you will need but it does not hurt to run composer update

NOTE: this is a quick and dirty way of transferring from on host to the other assuming that php version and other parameters stay the same, this is by no means a best practice in transferring a site to a new host.

For best practice you should follow the advice in the comments and see the guide on Use Composer to manage drupal site dependencies and the section for Managing existing sites using Composer might come in handy.


What module lets you delete a node after a specific time if its unpublished? is there a module that can delete or prune nodes that does not get published after a certain amount of time has passed? Currently the node prune module doesnt work with the latest core release. Looking for alternatives if possible.

thanks

You could do this using the Rules module.  If you enable the built-in scheduler submodule, you could create a set of rules/components like this (rough code to give you an idea, not a step-by-step walkthrough):

Component to delete content (Action set)

Action: Delete content

Rule to schedule content deletion (Rule)

Event: Content is created
Action: Schedule the "Component to delete content" after the specified amount of time

Rule to clear deletion on publishing (Rule)

Event: Content is published
Action: Delete the scheduled event for that piece of content ("Component to delete content")


How to build a simple content approval workflow between an administrator and a user? I have the following requirement on a Drupal site.

User interface (Authenticated user):

A simple form with some text fields
Radio buttons to select the content type
A submit button to submit the form

An authenticated user has to submit a form which will have few text fields and a content type selection.

User interface (Administrator):

A grid to see all the submissions.
A column with two buttons beside every submission "Review" and "Send back".

Once submitted the form, admin will be able to the submission, they may either review the content or send back the content to the user.

When clicked on review button, the page has to take to "Add content" page with title, description, attachment and other fields pre-filled.

When sent back, user will be notified and they may review the content and resubmit the form.

I achieved this requirement using Webform module which captures the user submission and written a custom module to fetch the webform submission content and creates a node based on the submission. I have yet to work on the "sent back to the user" part.

I'm wondering, if there is any simple way of doing this workflow.

P.S: I have already tried Workbench but I'm looking for a simple workflow where a non-technical guy (administrator) could easily get it.

Have a look at my answer to "How to implement a multi step approval with webforms/entityforms based on form components?". It explains how you can implement a workflow that is pretty (though not exactly) similar to what you are looking for.

To do so, it "only" requires you to use these modules (and regular content types):

Rules.
Node Convert.
Flag.
Content Access.

Use such approach, it does not require modules like "Webform" or "Workbench".


How to hide path location in drupal 7? How to hide path file in drupal? Now it looks like this:

http://localhost/drupal/sites/default/files/document.pdf

I want to change to look something like this:

http://localhost/drupal/media/view.php?id=6445

It can be done by implementing custom menu callback

/**
 * Implementation of hook_menu()
 */
 function mymodule_menu() {
   $items['media/view/%file'] = array(
     'page callback' => 'mymodule_download_file',
     'page arguments' => array(2),
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );
   return $items;
}

/**
 * Page callback for a file to download
 */
 function mymodule_download_file($file) {
   if($file) {
    file_transfer($file->uri, array('Content-disposition', 'attachment; filename='.$file->filename));
   }
   else {
    return drupal_access_denied();
   }
 }


User picture not removed when deleting user in Drupal 7 After creating users with a picture programmatically, and deleting them afterwards, I found out that the pictures (files) were not removed.

I started digging into this problem and found out that this problem also occurs when just adding a user by the UI, uploading a picture and deleting the user.

The picture is not being removed. Also the file remains in the file_usage and in the file_managed tables. They're not marked for deletion, so I guess they will stay there forever. Is this a bug? Or am I missing something?

if you really like to delete user profile picture on user delete event use this code in hook_user_delete($account).

// Load user by using user id
$user = user_load($uid);
// Get file id of profile photo
$fid = $user->picture->fid;
// Load the file object
$file = file_load($fid);
// delete profile photo from.
file_delete($file);
// Unset the image object (my case it's 'picture')
unset($user->picture);
// Save the user
user_save($user);

hope works for you


Can't add menu items to new menu I get a message: your configuration has been saved, but when I look at list links it says no links have been added.

I found a similar question and tried the answers to no luck.

I added a new menu Login Menu which worked fine and shows up with the other default menus.
I created a page content to serve as my login page for the site. When I try to add a link to my new Login Menu it says it has been saved, but it does not show up.

My objective is to move the User login block to show only on it's own page. So I need a menu for anonymous users to go to for logging in.

The problem was with the hierarchical menu module 7.x-3.0-alpha5. Although no error is created when trying to add a new item to a menu, an error is generated when adding new content with a menu link. This error allowed me to search for a solution.

I disabled the module and was able to add a new menu item to my new menu.


How can I use the Mail System module to send one e-mail differently than others? Problem

I would like to configure Mail System to use a different mailing class (one that does not format e-mail with Mime Mail) for the "welcome (no approval required)" e-mail.  Mail System supports adding a New Setting, which takes a module and a key.  For module I selected Core: user module, but what should I select for the key?

Background

On my D7 site, I am using the Mail System module to manage e-mail.  By default, everything is formatted by the Mime Mail module and sent with the Smtp module.

This is great for every message except the "welcome (no approval required)" email.  The reason is that I am using Logintoboggan and that e-mail contains the link to validate the account; when it is formatted with HTML (processed by the Mime Mail module), then sometimes users on mobile phones are not able to click the validation link.

These are the keys uses by the core user module:

'register_admin_created': Welcome message for user created by the admin.
'register_no_approval_required': Welcome message when user self-registers.
'register_pending_approval': Welcome message, user pending admin
approval.
'password_reset': Password recovery request.
'status_activated': Account activated. 'status_blocked': Account blocked.
'cancel_confirm': Account cancellation request.
'status_canceled': Account canceled.


Login fails due to loop on localhost. Any ideas why? I have git cloned a site and used Backup and Migrate to bring the database over the the local host.

Working on the remote host the login works fine. Not locally. Well not anymore it worked for about an hour I'd say.

  Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

I've cleared all history, tried different browsers, and restarted apache a few times.

Any ideas?

EDIT:

I can install it and after installation I stay logged in for about 60 seconds after migrating the database. I'm then redirected in a loop.

The page isn't redirecting properly

Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

This problem can sometimes be caused by disabling or refusing to accept
cookies.

I've cleared the browsers cookies and cache
I've cleared drupals cache
restarted apache
tried different browsers

I'm beginning to think it may have something to do with how I'm setting up the site. I'm doing it in a very round-about way I think.

backup database from dev site
git clone site and point httpd.conf and hosts file at it
create database with same name, user and password from settings.php file
install site
go in an enable backup and migrate
import database from backup

site loads. drops after 60 seconds or so with the firefox message from above. I'm not 100% sure where to start troubleshooting.

You could find out for sure by adding some logging code in drupal_goto() to backtrace what function fired the redirect. Then inspect why that function fired the redirect and work back from there.

Or, some more "guesswork" approaches -

Check you don't have $base_url set in settings.php.
Clear your cache tables after installing to copy (or don't back up the cache table contents).

drush cc all

Disable modules which might be confused by relocation - securepages, canonical_url, logintoboggan (guessing here).

drush dis securepages canonical_url logintoboggan

Check your variables table for (and delete) any entries with values like '%http://your.old.domain%'.

drush vget | grep your.old.domain

drush vdel some_variable_name


How to print how many nodes of a specific type a user has created? I'm making a block to be displayed on a node page that I want to display some information about the author of the node. I need to be able to show the number nodes of different types that the author has created. Any suggestions? I found this which gets me halfway there, but I need to be able to filter it by only the node authors content.

The simplest way would be to extend the query from the other question you linked to and add the user id as an extra parameter:

function yourtheme_get_node_count($content_type) {
  $query = "
    SELECT COUNT(*)
    FROM {node} n
    WHERE n.type = :type
    AND n.uid = :uid";

  // Get the node object for the current page.
  $node = menu_get_object();

  $params = array(':type' => $content_type, ':uid' => $node->uid);
  $amount = db_query($query, $params)->fetchField();

  return $amount;
}

Be sure to only call this on a node page as menu_get_object() will only return a node object when you're on such a page.


How do I call a controller function in a module? I am trying to access a static method of a controller class from a module, but my code doesn't work.

This is the controller class.

namespace Drupal\content_statistics\Controller;

use Drupal\Core\Controller\ControllerBase;

class ContentStatisticsCount extends ControllerBase {

  public static contentStatisticsCount() {
    $value = $this->t('hi');
    return $value;
  }

}

This is the module code.

use Drupal\Core\Controller\ControllerBase;
use Drupal\content_statistics\Controller;

/**
 * Implements hook_node_view().
 */
function content_statistics_node_view($node, $display, $view_mode, $langcode) {
  $value = ContentStatisticsCount::contentStatisticsCount();
  print_r($value);
  die;
}

This is giving me the following PHP error:

  PHP Fatal error:  Class 'ContentStatisticsCount' not found in /home/qbuser/Projects/test/modules/custom/content_statistics/content_statistics.module on line 15

If you want to define a controller, then don't use a static method:

namespace Drupal\content_statistics\Controller;

use Drupal\Core\Controller\ControllerBase;

class ContentStatisticsController extends ControllerBase {

  public function count() {
    $value = $this->t('hi');
    return $value;
  }

}

The use statement should import the class, not the namespace. But this is not the only problem.

If you want to use a controller class in a hook, create an instance of the controller and use the method of that instance:

use Drupal\content_statistics\Controller\ContentStatisticsController

$statistics = new ContentStatisticsController;
$value = $statistics->count();

Your class and method had the same name, I split the name in a controller class name and the method count().


How can I add a special classes to all block of custom kind? Is there any hook_preprocess_block or any other way to I can add my custom classes to all blocks of a custom kind?Or in the other words:
How can I target all blocks of custom kind?

For example I want to add search class to all search blocks (or target all search blocks in my theme by using default auto-generated classes by Drupal core if it be available), or add user-login class to all user login blocks and so forth in my theme without any need to create a template for every block.

It's no problem to add classes in a block preprocess hook:

use Drupal\Component\Utility\Html;

  function mytheme_preprocess_block(&$variables) {
    $variables['attributes']['class'][] = Html::getClass('block-id-' . $variables['elements']['#id']);
    $variables['attributes']['class'][] = Html::getClass('block-plugin-' . $variables['elements']['#base_plugin_id']);
    $variables['attributes']['class'][] = Html::getClass('block-provider-' . $variables['elements']['#configuration']['provider']);
  }

This example simply adds the available information to all blocks. You can start with this and narrow it down to what you want.


What is the benefit of Panels Everywhere Several websites advocate the benefits of Panels Everywhere (I have put them at the end of this question).

However, I have tried the module out out and cannot see the benefits.

A regular Panel page gives you the option to Disable Blocks. It also lets you display things like Menu Links, Footers and User Log-ins.
So I'm not sure what Panels Everywhere brings.

I could never see the benefits of Panels, but Drupal Answers enlightened me and now I wouldn't dream of making a Druapl site without it, so I'm hoping it can shed some light on the benefits of Panels Everywhere).

Sites Advocating Panels Everywhere

AWebFactory
Druapl Answers Thread
Lullabot

My experience with PE (panels everywhere) was great.
I been working for 1 year with PE on a big project and i can say:

The first advantage of PE is the entire layout control. while panels only affect the "content" region, PE get full control of all page including header and footer (which is no possible only with panels).
Second big advantage its the possibility to select variants as layouts letting you decide wich layout (variant) to show on every page taking that decision with the access arguments like a normal panel.

as you can see there are similarities with Omega theme, and in the fact both modules resolves the same issue.


Manage photo default settings in Node gallery module I am using Node Gallery module to work with albums and photos uploaded by user. When a user views his album there is a tab called Manage Photos which displays table with headings Delete, Preview, Edit and Cover.

I want to  change the text of 'Cover' as 'Album Cover' and display 'Delete' column at the end.

How to do this??

There is a Theming Function inside the theme.inc (\node_gallery\theme\theme.inc) file:

theme_node_gallery_api_manage_items_form($variables)

In there is everything you need. Copy this whole function to your template.php, rename the function to YOURTHEMENAME_node_gallery_api_manage_items_form($variables) and change the desired text. I think this should to the trick.

Paste the below code inside your active theme template.php file and make sure to change to you theme name.

    /**
     * Theme function for Manage Items form.
     */
    function elegant_theme_node_gallery_api_manage_items_form($variables) {
        $form = $variables['form'];

        if (empty($form['items'])) {
            return t('This gallery is empty.');
        }
        // Pull in the multi-select functionality from core.
        drupal_add_js('misc/tableselect.js');
        // Get fieldname to retrieve the filepath for the thumbnail without
        // loading the node.
        $relationship_type = node_gallery_api_get_relationship_type($form['#gallery']->type);
        $enable_rotation = FALSE;
        if ($relationship_type->settings['manage_items']['enable_rotation'] && (image_get_toolkit() != 'gd' || function_exists("imagerotate"))) {
            $enable_rotation = TRUE;
            drupal_add_library('system', 'ui.dialog');
            drupal_add_library('system', 'ui.draggable');
            drupal_add_library('system', 'ui.resizable');
            drupal_add_js(drupal_get_path('module', 'node_gallery') . '/js/ng_manage_images.js');
        }
        $header = array(
            t('Album Cover'), //changed from Cover to Album Cover
            t('Preview'),
            t('Edit'),
            array(
                'data' => t('Delete'),
                'class' => 'select-all',
            ),
        );
        if ($enable_rotation) {
            $header = array(
                t('Album Cover'), //changed from Cover to Album Cover
                t('Preview'),
                t('Edit'),
                t('Rotation'),
                array(
                    'data' => t('Delete'),
                    'class' => 'select-all',
                ),
            );
        }
        $rows = array();
        foreach (element_children($form['items']) as $nid) {
            $element = &$form['items'][$nid];

            $row = array();
            //Cover checkbox
            if ($form['is_cover']) {
                $row[] = drupal_render($form['is_cover'][$nid]);
            }
            //preview
            $file = $element['item_file']['#value'];
            if (!empty($file)) {
                $file_object = (object) $file;
                $file_view = file_view($file_object, 'node_gallery_api_admin_thumbnail');
                $row[] = drupal_render($file_view);
            }
            else {
                $row[] = '';
            }
            //edit link
            $edit = drupal_render($element['edit_form']);
            if (!empty($element['ngid'])) {
                $edit .= drupal_render($element['ngid']);
            }
            $row[] = $edit;
            //Rotation
            if ($enable_rotation && !empty($file) && $file['type'] == 'image') {
                $row[] = drupal_render($element['rotate']);
            }
            elseif ($enable_rotation) {
                drupal_render($element['rotate']);
                $row[] = '';
            }

            $row[] = drupal_render($element['remove']);
            $rows[] = array('data' => $row);
        }
        $output = theme('table', array(
            'header' => $header,
            'rows' => $rows,
            'attributes' => array('id' => 'upload-attachments'),
            )
        );
        $output .= theme('pager');
        $output .= drupal_render_children($form);
        return $output;
    }


Why does drupal set a menu link which redirects to a node as the active trail rather than the node's menu link? I know the question might be hard to understand, so here's the problem:

I have this menu:

a

b
c

d

e
f (which has the url "/lorem/ipsum")

So, when I click on f the active trail is d > f, just as supposed to be.

The problem is, inside submenu a shall be another menu link which has the same link as f, i.e. "/lorem/ipsum". So I added a menu link and the menu looks like this:

a

b
c
g (which links to "/lorem/ipsum")

d

e
f (which has the url "/lorem/ipsum")

So now, when I click on the menu link g the site "/lorem/ipsum" opens, but now the active trail is a > g and not d > f. I just want g to be a redirect to that node/url. How to do that?

The only working solution so far is to create a new node and add a global redirect from that node/nid plus url alias to "lorem/ipsum". This is really awkward...


Behat drupal 8 configuration I have the following set up. I vagrant machine with d8 site setup.
The files are common. I have replicated the DB in my laptop outside the host so I can run the behat tests faster. The DB is a dump of the one in the vagrant host.

Behat for host:

default:
  suites:
  default:
    contexts:
      - FeatureContext:
        - "/vagrant/images/behat"
        - 813
        - 1855
      - Drupal\DrupalExtension\Context\DrupalContext
      - Drupal\DrupalExtension\Context\MinkContext
      - Drupal\DrupalExtension\Context\MessageContext
      - Drupal\DrupalExtension\Context\DrushContext
  extensions:
    Behat\MinkExtension:
      selenium2: ~
      base_url: http://mysite.dev  # Replace with your site's URL
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drush:
        alias: 'local'
      drupal:
        drupal_root: '/vagrant/drupal'

Behat for local:

default:
  suites:
    default:
      contexts:
        - FeatureContext:
          - "/vagrant/images/behat"
          - 813
          - 1855
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\DrushContext
  extensions:
    Behat\MinkExtension:
      selenium2:
        browser: chrome
      base_url: http://mysite.dev  # Replace with your site's URL
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drush:
        alias: 'local'
      drupal:
        drupal_root: '/home/user/Projects/myproject/vagrant/drupal'

When I run the following scenario on the vagrant I can log in while in my local machine it fails to log in.

 @node
 Scenario: Create a node
   Given I am logged in as a user with the "administrator" role
   When I am viewing an "article" content with the title "My article"
   Then I should see the heading "My article"

How can I resolve this?

The login step creates a user via the Drupal API, and logs in by manually submitting the form.

When you run from within the Vagrant machine, the process presumably has access to bootstrap Drupal, and create users. When you're running from your local machine, I think only 'blackbox' tests (eg, ones that don't require API access) will work.

One potential workaround for this would be to specify in your local behat file:

api_driver: drush
drush:
  alias: 'vagrant'

and then ensure your local machine had a drush alias @vagrant setup so that you could access your vagrant Drupal instance from your local machine.


How do you change the css of node editing forms? This ought to be really simple -- all I want to do is increase the font size of the textfields in the standard node editing form (node/123/edit).  This should be a trivial tweak of a stylesheet, and I've just spent the last hour adding different bits of css to my standard theme style sheet, with no effect.  Nothing is affecting the style of the fields and I can't even see (via browser Inspect Element) what stylesheet is setting the font size.

Has this changed in Drupal 7?  I'm clearly missing something; can anyone offer advice?

Arggh -- finally found it.  I'm running a modified version version of Bartik for my site theme, and Seven came along as the admin/overlay theme.  I can put changes into /themes/seven/style.css, and they work.  It all makes sense now, I guess.  Thanks for the pointers.


CSRF on module forms for anon users My module has 2 small forms which allow visitors to submit certain information.

Problem is when I am not logged in, no CSRF token is being added to the forms - so anonomous users/everyone are bypassing the CSRF. Can't find any documentation on this issue, could anyone point me in the right direction so i can get my CSRF tokens?

It is a requirement of my security testing that all forms include CSRF.

If you look at drupal_prepare_form() it says

  since tokens are session-bound and forms displayed to anonymous users are very likely cached, we cannot assign a token for them.

If you do want to go ahead with this, the following works when quickly tested with the default search and comment forms.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (!isset($form['#token'])) {
    $form['#token'] = $form_id;
    $form['form_token'] = array(
      '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
      '#type' => 'token',
      '#default_value' => drupal_get_token($form['#token']),
    );
  }
}

Be careful about page caching however (and a reverse proxy if you use one) if you do go down this road.


Language AND region selector I'm asked to build a website which allows visitors to select both a language and a region, together, so it's a set of combined choices (eg. one choice would be "Switzerland French", another would be "Switzerland German", and so on). (Right now it's a combination of two countries and two languages, but it may be extended to other countries or languages in the future.)

This choice then accompany the visitor everywhere on the site, until of course she decides to change it. (The selector will be visible on all pages.)

Based on this choice:

a language is set (the site will be localized),
some contents (based on Views) will be ordered differently, and some will be filtered out,
some contents (blocks or pages) will be made visible or not,
the rest of the contents remain accessible and basically unchanged (but localized).

I'm not completely new to Drupal, but I'm no Drupal guru either. And I have no idea on how to implement that.

Can you advise me on how to approach this?

In the absence of any other answer, I've decided to try using the Organic Group module to solve this case.
I made this choice after reading this article which is the closest I've found to my needs.

However, I'm still not entirely sure that this is the only or even the best solution, so any other suggestion is still welcome.


When should one use #value_callback and when #element_validate? I've tried to get into custom element creation but ran  into problems with #value_callback and when #element_validate, more specifically their lack of documentation.

Imagine you have a custom element called db_connection whose output is supposed to be a is supposed to be an SQL connection string.

The element itself consist of a few select elements and one textfield. The user then simply selects (let's say) the database in the first one, table in the second one, and writes numerical of desired row in the last textfield.

My question is, when should you go trough the individual inputs and create the SQL connection string from them? Should it be in #value_callback or in #element_validate?

The names suggest the latter should be more suitable but my experience so far say the very opposite... It also seems to me that other modules (date) do it in the former one.

If one should really do it in #value_callback then how should he approach validation? As far as I know, the value callback is called before validation happens so it might have to deal with invalid individual inputs from which it might be impossible to construct the final output (SQL connection string in our example)?

And if it in fact is to be done in #value_callback than what purpose does #value_callback serve? What should it do, what should it return, ...?

As of my research:

This article suggests that one should use  #value_callback to transform 'default_value' to element friendly data form and use #element_validate to transform inputed data to store / later use friendly form.

So basically it suggests to go with #element_validate for the SQL connection string creation and use the #value_callback only to properly set up the element in case the SQL connection string is given as default value.

In addition to this question I also have this one (that is more about #value_callback). Already partially answered.

#element_validate:

  A list of custom validation functions. The validation functions must use form_error() or form_set_error() to flag the element as having an error if the validation fails.

Use this when you want to validate the input into your custom element, and inform users of any failures. Code example of such a validation function:

function myelement_validate($element, &$form_state, $form) {
   if (empty($element['#value'])) {
     form_error($element, t('This field is required.'));
   }
}

#value_callback:

  Specifies the name of a custom value function that implements how user input is mapped to an element's #value property.

Use this when you simply want to change the state of something in your element based on contextual information. Don't use this method if that state-change has the potential to cause an error that the user should be made aware of; use a validate function in that instance instead.

Code example:

function file_field_widget_value($element, $input = FALSE, $form_state) {
  if ($input) {
    // Checkboxes lose their value when empty.
    // If the display field is present make sure its unchecked value is saved.
    $field = field_widget_field($element, $form_state);
    if (empty($input['display'])) {
      $input['display'] = $field['settings']['display_field'] ? 0 : 1;
    }
  }
}

So to your question:

  when should you go trough the individual inputs and create the SQL connection string from them?

If this is a process that needs to be validated, then in a validation function. If it's something that just needs to be done, regardless of the input, then it goes in the value callback function.

Reading through the code in a bunch of the core value callbacks should clear up the confusion even better:

form_type_select_value()
form_type_textfield_value()
form_type_checkbox_value()

Notice that nothing in any of those functions relates to validation of the input.

Also see form_builder(), where the callback is actually used.


How to include jquery from URL in custom module? I've got a question about module building and including JS.
I'm working on a D6 custom module, and for JS files I'm including from within my mod
    drupal_add_js(drupal_get_path('module', 'ingsavingsmap') .'/js/effects.js');
works just fine.

The question I have is: I'm trying to include jquery from the jquery site.
I know:
    drupal_add_js(drupal_get_path('module', 'ingsavingsmap') .'http://code.jquery.com/jquery-        latest.js');

is very wrong for a number of reasons, but I don't know how to go about adding JS from a URL.
Also, is it advisable to event be doing it this way? or should I just keep it all within the mod.

Any help or direction to documentation would be appreciate
Thanks!
Steph

D7

For those who need to do this in D7, its as simple as

drupal_add_js('http://example.com/example.js', 'external');

D6

I can not take credit for this example but found this to be rather nice and easy way of dealing with external js files.

$external_js = 'http://www.example.com/a.js';
drupal_add_js('document.write(unescape("%3Cscript src=\''. $external_js . '\' type=\'text/javascript\'%3E%3C/script%3E"));', 'inline');

Found this via http://www.wootenswebdesign.com/load-external-js-file-drupal-6


How include oun TPL in /admin/structure/types/manage/ I need to show this form by my oun .tpl. But i didnt undestand how i can do this.
Can anybody help me?

the function work by url (/admin/structure/types/manage/type)
but it give me default form generator.

function admt_form_node_type_form_alter(&$form, &$form_state) {
  $default_value =TRUE;// auto_nodetitle_get_setting($form['#node_type']->type);

  $type = $form['#node_type'];
  $form['#theme'] = 'admt_form_theme_function';
  $form['admt'] = array(
    '#type' => 'fieldset',
    '#title' => t('Graffic User Interface'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => false,
    '#group' => 'additional_settings',
    //'#theme' => 'admt_form_theme_function',
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'menu') . '/menu.admin.js'),
    ),
  );

    if (isset($type) && $type->has_title) {
    $title = $type->title_label;
    }
    $fields = array();
    $arrFieldsType=array(
    "number"=>"textfield",
    "text_textfield"=>"textfield",
    "options_select"=>"select",
    "taxonomy_autocomplete"=>"textfield",
    "text_textarea_with_summary"=>"textare",
    "image_image"=>"file",
    "checkboxes",
    "radios"
    );
  $instances = field_info_instances('node', $type->type);
  $extra_fields = field_info_extra_fields('node', $type->type, 'form');

  // Fields.
  foreach ($instances as $name => $instance) {
    $form['admt'][$name] = array(
    '#type' => $arrFieldsType[$instance["widget"]["type"]],
    '#title' => t($instance["label"]),
    '#default_value' => array('value' => '...'),
    //'#options' => $type2,
     );
        if($arrFieldsType[$instance["widget"]["type"]]!="select") $form['admt'][$name]['#size']= '20';
  }

  // Non-field elements.
  foreach ($extra_fields as $name => $extra_field) {
    if(!empty($extra_field["type"]))
    $typ=$arrFieldsType[$extra_field["type"]];
    else
    $typ="textfield";
    $form['admt'][$name] = array(
    '#type' => $typ,
    '#size' => '20',
    '#title' => t($extra_field["label"]),
    '#default_value' => array('value' => '...'),
    '#description' =>  t($extra_field["description"]),
    //'#options' => $type2,

     );
  }
 // drupal_add_js('(function ($) { Drupal.menu_update_parent_list(); })(jQuery);', array('scope' => 'footer', 'type' => 'inline'));

}
function admt_theme($existing, $type, $theme, $path)
{
  return array(
    'mymodule_userinfo_form_theme_function' => array(
      'render element' => 'form',
      'arguments' => array('form' => NULL),
    ),
  );
}

First of all change this line in your alter function -
$form['#theme'] = 'admt_form_theme_function';
change it to
$form['#theme'] = 'mymodule_userinfo_form_theme_function';

Add below line of code in your admt_theme function for mymodule_userinfo_form_theme_function.
'template' => 'your-tpl-name'

function admt_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_userinfo_form_theme_function' => array(
      'render element' => 'form',
      'template' => 'your-tpl-name',
    ),
  );
}

Then create your-tpl-name.tpl.php file inside your module folder.

Now you can use this new template for your form.


Does Drupal 7 require Drush 7? In a Drupal 7 project I'm working on I need to install Drush in order to perform a variety of operations.  The only trouble I see is that the latest Drush installer for windows only goes up to version 6.  I can install Drush 7 using cygwin, but I want to verify that I'm not missing something.  It seems logical that the Drush versions might be synced up with the Drupal version, but perhaps there is some cross version compatibility or something else I'm missing.

If I want to use drush commands on a drupal 7 site do I need to use Drush version 7?

If so is cygwin probably the best way to get Drush 7 up and running on a windows 8 machine?

Drush and what version(s) of Drupal are supported per version of Drush are clearly explained here:

http://docs.drush.org/en/master/install/


Search API: Custom processor not hitting addFieldValues I'm creating a custom module for adding a processor that adds relative entities. Here's my code for getPropertyDefinition.

public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
$properties = [];
if ($datasource) {
  $entity_type = \Drupal::service('entity_type.manager')->getStorage('group_type')->load(key($datasource->getBundles()));
  $entity_type_ids = [];
  $plugin_manager = \Drupal::service('plugin.manager.group_content_enabler')->getInstalled();
  foreach($plugin_manager->getInstanceIds() as $instance_id) {
    array_push($entity_type_ids, $plugin_manager->get($instance_id)->getPluginDefinition()['entity_type_id']);
  }
  foreach($entity_type_ids as $entity_type_id) {
    $definition = [
      'label' => $this->t(ucwords($entity_type_id)),
      'description' => $this->t('Entity reference of ' . $entity_type_id),
      'type' => 'entity:' . $entity_type_id,
      'processor_id' => $this->getPluginId(),
    ];
    $properties[$entity_type_id] = new EntityProcessorProperty($definition);
    $properties[$entity_type_id]->setEntityTypeId($entity_type_id);
  }
}
return $properties;
}

And, after adding relative fields to index, I think it should hit addFieldValues method but it doesn't. For test purpose, I only put die in the method.

public function addFieldValues(ItemInterface $item) {die;}

But, when I copied code from addURI's getPropertyDefinition into my getPropertyDefinition, it hits addFieldValues when indexing. Is there anything wrong in my getPropertyDefinition?

EDIT
I created an issue on the search API issue queue Custom Entity Reference processor does not trigger addFieldValues()* and the maintainer has pointed to an existing issue that it was duplicating. So there is an existing issue that is being worked on here - #2910638: Entity reference via processor sample code not working Jump on there and help test :)

I couldn't post the first link because of a lack of reputation and I figured the link to the issue where work is being carried out is more useful :D

I'm encountering the same behaviour and have an idea why this occurs but not an answer on how to fix it (I can't post a comment so needed to add this as an answer).

\Drupal\search_api\Item\Item::getFields is responsible for calling the instances' implementation of addFieldValues. Within that function there is this code block:

   foreach ($this->index->getFieldsByDatasource($datasource_id) as $field_id => $field) {
      // Don't overwrite fields that were previously set.
      if (empty($this->fields[$field_id])) {
        $this->fields[$field_id] = clone $field;

        $field_data_type = $this->fields[$field_id]->getType();
        // If the field data type is in the fallback mapping list, then use
        // the fallback type as field type.
        if (isset($data_type_fallback_mapping[$field_data_type])) {
          $this->fields[$field_id]->setType($data_type_fallback_mapping[$field_data_type]);
        }

        $property = $field->getDataDefinition();
        if ($property instanceof ProcessorPropertyInterface) {
          $processors_with_fields[$property->getProcessorId()] = TRUE;
        }
        elseif ($datasource_id) {
          $fields_by_property_path[$field->getPropertyPath()][] = $this->fields[$field_id];
        }
      }
    }
    try {
      if ($fields_by_property_path) {
        \Drupal::getContainer()
          ->get('search_api.fields_helper')
          ->extractFields($this->getOriginalObject(), $fields_by_property_path, $this->getLanguage());
      }
      if ($processors_with_fields) {
        $processors = $this->index->getProcessorsByStage(ProcessorInterface::STAGE_ADD_PROPERTIES);
        foreach ($processors as $processor_id => $processor) {
          if (isset($processors_with_fields[$processor_id])) {
            $processor->addFieldValues($this);
          }
        }
      }
    }

If the value of $property is not an instanceof ProcessorPropertyInterface then addFieldValues() is never called.

What I'm not sure of is what is the best path to take to begin solving this.

Should I add a new custom processor that only acts on this custom field and use addFieldValues() there? (I've yet to test this) OR
Is it an issue that addFieldValues() is never called and the Search API module needs to be updated so that it is?

I've tried implementing the other functions from the parent class (\Drupal\search_api\Processor\ProcessorPluginBase) ie alterIndexedItems but none of those are triggered.

I came across the same approach that you're using here on d.o - Adding an entity reference via a processor so it may be the docs need to be updated.


How to dynamically redirect user from /foo/X to /bar/X? So far I did the following:

I've installed Redirect and Token modules.
I've applied the patch for Redirect module to support wildcards.
I've applied the patch for Redirect module to implement hook_redirect_response_alter.
I've defined the following hook_redirect_response_alter to support and parse the tokens.

use Drupal\redirect\Entity\Redirect;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Component\Utility\UrlHelper;

/**
 * Implements hook_redirect_response_alter().
 */
function MYMODULE_redirect_response_alter(RedirectResponse $response, Redirect $redirect) {
  $uri = $redirect->getRedirect()['uri']; // "internal:/bar/[current-page:url:args:last]"
  if (!empty($uri) && strpos($uri, '[') !== FALSE) {
    $uri = \Drupal::token()->replace($uri); // "internal:/bar/"
    $external = UrlHelper::isValid($uri, TRUE); // bool
    $redirect->setRedirect($external ? $uri : explode('/', $uri, 2)[1]);
    $response->setTargetUrl($redirect->getRedirectUrl()->setAbsolute()->toString()); // "http://localhost/bar/"
  }
}

I've added the following redirect at /admin/config/search/redirect:

From: foo/*
To: /bar/[current-page:url:args:last]

Based on the above, I'm expecting that typing foo/X will redirect to bar/X, and foo/Y to bar/Y accordingly, and so on. However, the above token is replaced with an empty string. Similar thing when using token such as [current-page:url:args:value:2], it's not replaced at all. I've also learned here that using [redirect:url:args:last] won't work either, as the token is generated based on the entity type, so Redirect module isn't aware of it.

I've tried a few more tokens found at /admin/help/token which can potentially extract the second argument from the path, but I haven't found any suitable or working as expected for this task.

For example:

More details

Applying $redirect context for token's replace() method, as suggested in the comments, didn't work as expected.

So the following line:

$uri = \Drupal::token()->replace($uri, ['redirect' => $redirect]);

populates some token with redirect prefix, however it wrongly replaces the current path, e.g. [redirect:url:args:join:/] becomes admin/config/search/redirect/edit/25 for every page.

I've also tried to populate context for the current-page tokens, but it was requiring the current path exists, however during redirect the current path doesn't exist in the menu routing table, so it can't be loaded (I've tried Url::createFromRequest() and \Drupal::request()).

Question

What I'm missing? Is there any easier way to achieve the same thing?

Since passing context for token's replace method didn't work as expected, I've defined a new token in my custom module to return the specific components of the Drupal path (using the following guide).

my_redirect.tokens.inc

<?php

/**
 * @file
 * An include file defining custom tokens.
 */

use Drupal\Core\Render\BubbleableMetadata;

/**
 * Implements hook_token_info().
 */
function my_redirect_token_info() {
  $type = [
    'name' => t('Custom URL token for redirect'),
    'description' => t('Tokens helpful for redirect pages.'),
  ];

  $node['url-arg'] = [
    'name' => t("URL Argument"),
    'dynamic' => TRUE,
    'description' => t('Returns a component of the current Drupal path.'),
  ];

  return [
    'types' => ['my_redirect' => $type],
    'tokens' => ['my_redirect' => $node],
  ];
}

/**
 * Implements hook_tokens().
 */
function my_redirect_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {

  $replacements = [];

  if ($type == 'my_redirect') {
    if ($argTokens = \Drupal::token()->findWithPrefix($tokens, 'url-arg')) {
      foreach ($argTokens as $arg => $original) {
        $current_path = \Drupal::service('path.current')->getPath();
        if ($arg === "first") {
          $value = explode('/', $current_path)[1];
        }
        elseif ($arg === "last") {
          $value = end(explode('/', $current_path));
        }
        else {
          $value = explode('/', $current_path)[$arg ?: 0];
        }
        $replacements[$original] = $value;
      }
    }
  }

  return $replacements;
}

So after applying already mentioned patches, and above code, I can use the following Redirect rule:

From: foo/*
To: /bar/[my_redirect:url-arg:2]


How can I leave empty values in gmap field? I use gmap module to display a map on nodes that I want to have a location. On some nodes I don't want any location, and on those I don't want the map displayed at all. I tried to set default value in lat/long-fields to NaN or leave them empty, but then I get error when I save the node. Is there any way I can choose to display the map or not?

If you want to have an option to leave field blank, simply don't make it required. Go to /admin/structure/types/manage/your_content_type/fields/field_name and clear the "required" checkbox.


copy database for duplicate site? Now have set up multi-sites is it possible to just cp database.sql to other databases so the site is duplicated but running independently?

I remember when I first set up multi-sites I got it wrong so that when changes were made to one database , it would translate to other until I separately created databases for each.

I know there are other ways of saving settings for a commonly created site in features which I have yet to try but isn't it easier to just copy the mysql over
to other database and make small changes from there?

You can simply copy database all right, if you remember about critical points:

Make sure settings.php really points to proper databases
Before importing SQL file to new database, find and replace old URL and site name with new one.
If you keep any cache settings for external tools, like memcached, in database, make sure you either uninstall them before SQL export and then install again, or find & replace in SQL file before importing.


How to display taxonomy term reference field as a rendered entity? I have taxonomy term reference field which are displayed as checkbox.
Each taxonomy term has two fields 1. description and other 2. price
I want the description and price field to be displayed alongside the title in field(term refrence).
How can I achieve ut?

The function taxonomy_term_view is for displaying a taxonomy term as a rendered entity. If not specified explicitly with an extra parameter, it uses the view mode full, which displays all fields, one after the other. But you can adapt that in the admin backend, and also define other view modes. So in your case, the code would be like:

$term = taxonomy_term_load($entity->field_term_reference);
$term_view = taxonomy_term_view($term);

This generates a Drupal render array. In case you want to use this in a theme context, add one more line:

drupal_render($term_view);


Remove terms from taxonomy vocabulary for node type I have two node types that share a taxonomy vocabulary. I'll call them type1 and type2. type2 uses two terms from the vocabulary that type1 does not. Both type1 and type2 have views that allow filtering by the taxonomy terms. I need to have the two terms that type2 uses not show in the view for type1. Any ideas?

[EDIT]
The terms are in a dropdown menu.

I found an option in the settings for the Views filter called "Limit list to selected items" I checked that and selected all the ones I wanted to show up in the list of terms by the operator settings. That made the ones I didn't want not show up.


Empty body in node edit page I have created a node entering content for its body field; when I return to the node edit form, the body field is empty.

What may cause this problem?

If you are using node translations, when Drupal gets an empty body, it first search a translation with non empty body and, if found, shows it. That's probably why you are viewing body content in the node view but an empty textarea in the node edit form, the content surely comes from one translation.


Some tags in the output from my controller are filtered away I have a controller defined in MODULE.routing.yml which returns:

return array(
      '#type' => 'markup',
      '#markup' => $this->content(),
      '#attached' => array(
        'library' => $libs,
      ),
    );

The content contains H2, INPUT and SELECT (amongst others). The INPUT and SELECT are removed so I guess there's an input filter being run on this markup.

How do I control the input filter for this controller and/or disable it completely?

That is behavior Drupal 8 has for the #markup property, as described in Render API overview. It is different from the behavior Drupal 7 had; if you are converting code from Drupal 7, you need to change that part of the code accordingly.

  #markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, <script> and <style> are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Aternatively, you can use the render array key #allowed_tags to alter which tags are filtered.

The highlighted part tells you how to solve the filtering of tags.

See also the next part of the documentation.

  #allowed_tags: If #markup is supplied this can be used to change which tags are using to filter the markup. The value should be an array of tags that Xss::filter() would accept. If #plain_text is set this value is ignored.


Manage displays of Product:image field directly in Product Display? I have a "Product Display" node showing a "Product" (powered by the Drupal Commerce module).

I have installed the Display Suite module, and created a new view mode for the "Product Display" content type.

The problem is that this new mode is associated with the default view mode of "Product," and I see no way to change this.

What I need is to create a new mode for "Product" and get the view mode of "Product Display" associated with this new one.

Is there anyway to do it?

Go to the Manage Display tab of your product entity and enable the same "View Mode" you use at "Product Display". Do it in the "Custom display settings" fieldset.

Then set up image style for the Image field. And see changes at the "Product display" page


How do I localize menu items added to the Main menu by a views page? I have a multilingual site setup where the pages in the Main menu are all created by Views. Main Menu is configured to 'Translate and Localize.'

When clicking 'edit' for a menu item the 'Translate' tab does not appear in the top right hand corner when the Language selection box is set to Language Neutral.

(This, however, does appear when I change the language selection in the drop down box to something specific; however, I want to Localize, not create a translation set.)

I know I have done this before. What am I missing? Note I am using node translation (content translation) and not entity translation.

If I understand your question correctly:

Go to Structure > Menu > List links
Assign the correct language to the link and then you can add a translation for the term.

One of your languages is to be set as the source language for translation. As far as I know a language neutral entity (menu, node, whatever) can not have a translated counterpart, because there is no source language for translation available.

Hope this helps.


Drupal changes my markup in full html mode While editing body of the node in Full HTML format, i enter these lines:

    string 1

    string 2

    string 3

But the real generated html is:

    string 1

    string 2

string 3

What's wrong with that? Why Drupal changes my code in full html? I don't want any extra
's because it breaks the layout.

By default the Full HTML format has the

  Convert line breaks into HTML (i.e. <br> and <p>)

option selected. If you don't want that behaviour, just go to http://mysite.com/admin/config/content/formats/full_html and deselect that option:


How to block a content type from the RSS feed I simply want to remove one of my content types from being displayed in the feed, I can't find a solution anywhere - I would have thought there would be an option under Content Types which says "Don't put in feed" lol

I would have thought there would be an option under Content Types which says "Don't put in feed"

Yes, it's as simple as that. Simply uncheck the "Promoted to front page" from the content type settings and that content type's nodes won't be included in the RSS feed. :-)


Can I route individual websites to a multi-site Drupal installation? This isn't really Drupal-specific, but perhaps someone is already doing this with Drupal and can guide me. I host a few sites for my customers and several of those are Drupal-based, using a multi-site installation. No problems, except that those are not individual cPanel accounts, of course, and the customer cannot manage any part of their account -- I have to do it all.

Is it possible to set up my Drupal customers with individual cPanel accounts, yet route all their web traffic to the multi-site Drupal installation on my reseller account (typical reseller account on a shared host)?

I have never seen this done in cpanel. Maybe under your reseller account
you could  create a instance of multi-site and then create sub-domains then
your clients could domain could be redirected to the subdomain?

Have you tried talking to the guys who created cpanel that might
be another resource

http://forums.cpanel.net/forum.php


Display a Media Entity Image from other (referencing) node in a Twig template Seems that all found in the Internet does not work for my case. :/
In general, I need to display an Image and a Project, referenced by the node that has a reference field to my node.

I have:

a node of CT Idea (here I want to display my content)
a node of CT Example, which has:

1) a ref field to Idea
2) a ref field to a Media, Image
3) a ref field to a CT Project

I want to display Examples on an Idea page, each Example displays:
Description, Image, Project link

I've managed to display the Description, but can not display Image and Project.

Here is the code

in the *.theme file:

function showcase_lite_preprocess_node__idea(&$variables) {
  $current_node = $variables['node'];
  $current_node_id = $current_node->id();

  $query = \Drupal::entityQuery('node');
  $query->condition('type', 'example');
  $query->condition('status', 1);
  $query->condition('field_example_ideas', $current_node_id);
  $nids = $query->execute();
  $relatednodes = Node::loadMultiple($nids);

  if (!empty($relatednodes)) {
    foreach ($relatednodes as $related_node) {
      $related_node_image = $related_node->field_example_image->value;
      $related_node_description = $related_node->field_example_description->value;
      $related_node_project = $related_node->field_example_project->value;

      $variables['related_node_image'] = $related_node_image;
      $variables['related_node_description'] = $related_node_description;
      $variables['related_node_project'] = $related_node_project;
    }
  }
}

In the node--idea.html.twig file:

{% block content %}
    {{ content }}
    {{ related_node_description }}
    {{ related_node_image }}
    {{ related_node_project }}
{% endblock %}

This displays only the Idea content and the Example Description.

It seems to me that the problem is that the format of $related_node_image and $related_node_project does not correspond to what Twig is expecting. But I can not check what is inside the variable, because Kint gives an error of memory limit.

Drupal version: 8.5.3.

To get a renderable output for Twig use EntityViewBuilder::viewMultiple()

    $variables['related_nodes'] = \Drupal::entityTypeManager()
      ->getViewBuilder('node')
      ->viewMultiple($relatednodes, $view_mode, $current_node->language()->getId());

and configure the three fields in the view mode you've specified here.


The requested URL /node was not found on this server I am setting up Drupal locally in my Ubuntu.
I used drush to download and install Drupal 7. (using mysqladmin to create the database and the user)

All worked well, I have the default homepage, but when I try to do any action (logging in, registering) I get a 404. I imagine the mod_rewrite doesn't work..

I installed the Apache module and enabled it, restarted the server, but no lack...

I am guessing mod_rewrite needs more parameterization...?

update: I can access correctly the page with this url:

http://localhost/index.php?q=user

so I guess my mod_rewrite clearly doesn't work as it should..

Have you verified that the .htaccess file from the Drupal 7 core package is in the website root?

You can easily download and extract that file from drupal.org base package:  http://drupal.org/project/drupal


Send email after content update I have create a new content type with a field of email. In this field I put the email address of the person I want.

The case is:
I want every time the node of this content type updated, to send an email to the address from the email field.

With Rules module I cannot find a proper way to make it work because Rules are on a very early point of development.

There is two problems with rules:
1st - I have create a simple action to send an email every time the node is updated. This is work fine. When I create a condition "Node is of type" and select only one content type the sending email action is still working for all content types.

2nd - I cannot find any proper method for what suppose to write to the reciptient field to send the email to the address from the email field.

Can any one help? Any thoughts?

First, use the -dev version of Rules.

Second, always use the "Show a message on the site" action for testing. This is a LOT easier to debug than "Send email". You can use tokens in the message to test that the values are what you expect them to be, then when you get the right values you can use the email action with those same tokens in your email.

Third, always clear your caches after making changes to a rule.

Fourth, the issue queue contains many complete examples you can use. For instance, here is an example of how to show a system message when an "article" type node is created (from https://www.drupal.org/project/rules/issues/2852342). Try this you will see that "Node is of Type" DOES work to restrict the type - the message will never be shown if you create a node that is not an article:

uuid: c1b8486c-a96b-4f53-903a-8a08cb85355d
langcode: en
status: true
dependencies: {  }
id: test_rule
label: 'Test rule'
events:
  -
    event_name: 'rules_entity_insert:node'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: f8e466d6-51d6-41ea-93f1-34436470f3c3
  conditions:
    id: rules_and
    uuid: 7776a869-e0c6-4499-b09e-da727722213e
    conditions:
      -
        id: rules_condition
        uuid: 6bf893f5-7bcf-420c-9a62-7e1cb9a884f6
        context_values:
          types:
            - article
        context_mapping:
          node: node
        context_processors:
          types:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_node_is_of_type
        negate: false
  actions:
    id: rules_action_set
    uuid: f0bcccfd-685f-4a74-a4fd-0d36b540037a
    actions:
      -
        id: rules_action
        uuid: ec599dbc-cb40-448b-b37b-129d956c2eb7
        context_values:
          message: '<b>Test rule triggered</b> {{ node.title }}'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message

And finally, here's a complete example for how to send e-mail to an address contained in a field value. This example assumes you have a node content type with machine name "email" which has a single-valued required field of type "email" named "field_email".

uuid: bc3fb7fd-0cbd-416c-8b71-9d6b710eb0ce
langcode: en
status: true
dependencies: {  }
id: send_email_when_content_of_type_email_is_created
label: 'Send email when content of type "email" is created'
events:
  -
    event_name: 'rules_entity_insert:node'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 265d153c-9ce9-4250-a1b7-b8670be7826c
  conditions:
    id: rules_and
    uuid: 4f570c4e-3558-4628-96dc-aebb7b6d9e65
    conditions:
      -
        id: rules_condition
        uuid: 8014e5b0-680d-46c3-94fc-0785022447ca
        context_values:
          types:
            - email
        context_mapping:
          node: node
        context_processors:
          types:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_node_is_of_type
        negate: false
  actions:
    id: rules_action_set
    uuid: 25127564-6ab9-4587-b1b9-9336781aab9e
    actions:
      -
        id: rules_action
        uuid: 16f51441-39e8-4872-a3c2-e4e12a339f1e
        context_values:
          message: 'Email is {{ node.field_email.value }}'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message
      -
        id: rules_action
        uuid: 2c636fe9-9b9a-46b8-b930-81b9730f5ac2
        context_values:
          to:
            - '{{ node.field_email.value }}'
          subject: 'An Email node was created'
          message: 'An Email node was created'
          reply: ''
          language: ''
        context_mapping: {  }
        context_processors:
          to:
            rules_tokens: {  }
          subject:
            rules_tokens: {  }
          message:
            rules_tokens: {  }
          reply:
            rules_tokens: {  }
          language:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_send_email

If you import these Rules onto your site and inspect how they're constructed they will help you learn how to do this yourself.


I extended some functionality in the slick module, but I am looking to do it in a way that doesn't get erased each time I update slick I extended some functionality in the slick module, but I am looking to do it in a way that doesn't get erased each time I update slick.

I added a css file and edited the slick skin php file to use the css file depending on the user's choice. I also added a bootstrap class to the slick.html.twig template so that the slider would disappear on mobile devices.

Should I make a custom module that acts like slick_examples?

In my opinion, the easiest way to preserve changes to contributed code is to manage your dependencies through Composer and use patches. When you update slick in the future, the output of the command will directly tell you which of your patches have been broken by the update.


Can you cache blocks per language? I am working on a multilingual site right now, and am using the Internationalization suite of modules to build it out.

The site has some custom blocks in it that I would normally use DRUPAL_CACHE_GLOBAL in the hook_block_info() definition.  However, some of these will have translatable strings in them, so I really need to cache them per-language.

Is this possible?  Or, is my only real option to use DRUPAL_CACHE_PER_PAGE?

Just use DRUPAL_CACHE_GLOBAL. On multilingual sites the users language is part of the (cid), i.e. the key used when storing/fetching entries to/from the block cache.

The function responsible for this behavior is drupal_render_cid_parts which is called from _block_get_cache_id.

You can embed the following fragment into a custom PHP block in order to verify the mechanism:

$fakeblock = (object) array(
  'module' => 'some-module',
  'delta' => 'some-delta',
  'cache' => DRUPAL_CACHE_GLOBAL,
);
print _block_get_cache_id($fakeblock);

On a multilingual site, the fragment should print something like:

  some-module:some-delta:bartik:en


How to navigate URL after moving drupal site from one server to other server? I have just moved my drupal 7 website from one server to other server.
But after moving it i am not bale to see any css effect and not able to open naviagte any link. I am using linux server.

Can somebody suggest how to do this.

These kinds of problems (after transfer to a new host) might be caused by some type of permission problems. Some of the extra comments from the OPer in the question makes me believe that is the case here also.

So I'd verify that the userid of your webserver has appropriate file permissions.

Another option is to verify the various items mentioned in the community documentation about Migrating a site. One of the typical issues is (as mentioned in this link):

  Attempt to log on to the new site. You will probably find that you are locked out by a combination of site maintenance mode and the non-clean URLs. In that case navigate to newsite/?q=user to login, then turn on clean URLs.


How to upgrade to Drupals latest version via Composer? Currently I have 8.6.13 installed.

composer update drupal/core --with-dependencies
Package "drupal/core" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update

When I tried to look in to composer.json we don't have drupal/core in

require.

https://www.drupal.org/docs/8/update/update-core-via-composer

How to upgrade to 8.7.0?

$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.0].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.1].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.10].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.11].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.12].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.13].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.14].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.15].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.2].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.3].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.4].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.5].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.6].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.7].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.8].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.9].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.x-dev].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.15].
    - drupal/core 8.7.0 requires egulias/email-validator ^2.0 -> satisfiable by egulias/email-validator[2.0.x-dev].
    - Installation request for drupal/core 8.7.0 -> satisfiable by drupal/core[8.7.0].
    - Installation request for egulias/email-validator ^1.2 -> satisfiable by egulias/email-validator[1.2.0, 1.2.1, 1.2.10, 1.2.11, 1.2.12, 1.2.13, 1.2.14, 1.2.15, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.2.8, 1.2.9, 1.2.x-dev].

I had exactly the same issue while performing upgrades. The solution for me was removing/renaming the vendor folder and the composer.lock file and run composer update drupal/core --with-dependencies.

You can also try to update dependency explicitly with composer update egulias/email-validator drupal/core --with-dependencies. This usually works in this type of issues, but it didn't work for me.

Given that you don't see drupal/core in your composer.json you might also try composer require drupal/core.


Correct server permissions Possible Duplicate:
  What are the recommended directory permissions?

I have recently installed a site on a debian LAMP server. I've finally got to work by changing the permissions to -

/sites                - 755

/sites/all                    - 755

/sites /default           - 755

/sites /files                 -777

/sites /default/settings.php  -755

/private            -777

/public              -777

/sites /files/tmp                  -777

However, i am unsure if these are the correct permissions to use and they don't create any vulnerabilities.

Thanks in advance.

This is all subjective to your situation, but...

If you're the sole developer on the site then you just need to make sure that your Apache user's group has write access to your files directories (or any other directories where files are uploaded or generated.  That way both you and apache can access those files using 775 mode.

If you uploaded all of the directories as a user with a primary group that apache is not in, you are better off changing the group to one that apache is in and keeping 775 rather than granting 777 permission.-

If you're on a shared hosting, in some cases group write permission on files is dangerous, so don't do the above in that situation.


Automatically add node to menu How can I automatically create a menu link for a new node in Drupal 8?

You can use a deriver class for this.

In your foo.links.menu.yml file

entity.node.canonical:
  deriver: '\Drupal\foo\Plugin\Deriver\FooMenuLinkDeriver'
  route_name: entity.node.canonical

In Drupal\foo\Plugin\Deriver\FooMenuLinkDeriver

class FooMenuLinkDeriver extends DeriverBase implements ContainerDeriverInterface {
  public function getDerivativeDefinitions($base) {
    $plugin_definitions = [];
    foreach (Node::loadMultiple() as $nid => $node) {
      $plugin_definitions[$nid] = $base;
      $plugin_definitions[$nid]['route_parameters']['node'] = $nid;
      $plugin_definitions[$nid]['title'] = $node->label();
    }
    return $plugin_definitions;
  }


What's the best way to add an alert box to a link in D7 I have a link, which is rendered via the l function. It's a link which calls a function that deletes a node. Before the function is called, I want an alert box to pop up and give the user the option to 'Cancel' or 'Confirm'. Adding this as an argument to the l function works:

array('attributes' => array('onclick' => 'return confirm("Are you sure?")'))

...but is there an existing function, or something, that does a nicer job?

I'd rather not add a contrib module for such a small task.

no there is no js related function in drupal 7 that provides a functionality like that. just make sure that custom setup you have there is in your template.php


Ajax callback is not invoked I am using Drupal 7, and I used hook_form_alter() to add the following markup.

  $form['linkb'] = array(
    '#type' => 'markup',
    '#markup'=>"<a href=''>Click here </a>",
    '#title' => t('something'),
    '#name' => 'linkb',
    '#ajax' => array(
      'method' => 'html', // this is important without this if else condition for ajax will not work.
      'effect' => 'fade',
      'callback' => 'clicktell_verification',
      'wrapper' => 'replace_textfield_div',
    ),
  );

I want to run AJAX when I click on Click here, but this is not working. I have also created a callback function, but it doesn't still work.

Why isn't the AJAX callback being called?

#ajax is never used by elements of markup type. You need to use it with one of the following elements:

button
checkbox
checkboxes
image button
password
radio
radios
select
submit
tableselect
textarea
text_format
textfield


autofill from taxonomy term fields I'm trying to connect a field of a taxonomy term to a field in a content type, something like this:

Auto-Fill from on content type to another

I tried this on a node and it's working, but now I have some problems with the taxonomy term, is for this part?

// load node by nid
$node = node_load($nid);

Do I have to specify here the taxonomy? but I really don't know what to put in...

the field in content type is "field_descrizione_01" with empty field "field_udm"
the field with the data in the taxonomy terms is "field_udm_ti"

I've made this code (based on the link one):

/**
* Implements hook_field_widget_form_alter().
*/

function collegamento_field_widget_form_alter(&$element, &$form_state, $context) {

  if(isset($element['#field_name']) && $element['#field_name'] == 'field_descrizione_01') {
    $element['#ajax'] = array(
      'callback' => 'collegamento_auto_fill_callback',
    );
  }
}

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

  $commands = array();

  if(isset($form_state['values']['field_descrizione_01'])) {
    // get selected item/node from dropdown list
    $nid = $form_state['values']['field_descrizione_01']['und'][0]['nid'];

    // load node by nid
    $node = node_load($nid);

    if($node) {

      if(isset($node->field_udm_ti['und'])) {
        // fill text field
        $commands[] = ajax_command_invoke('#edit-field-udm', 'val', array($node->field_udm_ti['und'][0]['value']));
      }

    }
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

You need to load a taxonomy term using taxonomy_term_load

This should get you on the right track.


How can I place brackets around a field in a view? I'd like to place a field's value in a view between brackets. Let's say that there are 2 fields 'Name' and 'Country'. How can I display these as Name (Country) in a view? I know how to inline the fields, but I have no idea how to place the brackets around the second field.

How can I do this?

Simply use the rewrite field option: use the 'country' token and place brackets around it.

Special thanks to @Mołot!


In Drupal 8 how can I print the page title within a paragraph.html.twig Is there a way to print the page title within a paragraph.html.twig?

In Drupal 7 your could just do a drupal_get_title(); in an tpl.php and use it as a variable.

That function is depreciated and from what I read about TWIG not in the spirit of themeing in Drupal 8 now.

What is the Drupal 8 way to do this?

An alternative strategy to setting cache context is to use a placeholder. This is a more complex approach but you will never have issues with the database cache table filling up - as 4k4 points out this can be a real problem.

All of this code goes in themename.theme.

First we must define a callback function that returns the page title to the placeholder:

function _MyTheme_paragraphs_title_placeholder($page_title) {
  // Must go here, if you attempt to pass in $page_title from preprocess it will
  // be cached!
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $title_array = array(
    '#theme' => 'page_title',
    '#title' => $page_title,
  );

  return $title_array;
}

Next we create the placeholder in preprocess, we will print a variable in the template, so we must populate it with the placeholder:

function MyTheme_preprocess_paragraph(&$variables) {
  // Note: the first item in the #lazy_builder array is our callback.
  $placeholder_title = array(
    '#lazy_builder' => ['_MyTheme_paragraphs_title_placeholder', ['page_title']],
    '#create_placeholder' => TRUE,
  );

  $variables['title'] = $placeholder_title;
}

Finally create copy the paragraphs template and use the title variable:

<div{{ attributes.addClass(classes) }}>
  {{ title }}
  {{ content }}
</div>

This is how I have implemented the breadcrumb title feature in Adaptivetheme (D8 version), to avoid cache context url as I noticed the database entries, I think it's a great method and I'd love more feedback if I have done something wrong - I'm a themer of course, not a hardcore dev :)


How to select by default nodes of a content type in admin/content through a link? I'd like to make a link to admin/content/, but when the page was displayed I'd like to have it filtered by a certain content type.

The link can be like this admin/content/house so when I click it, the admin/content page is already filtered by house Content Type.

Is this possible?

Is something like this How to link to dblog filtered by type? but for the admin/content path.

Edit: If I click in a link that can be like this admin/content/house I can have in the admin/page the Content Types filtered by House, something like this picture

It looks like you're making use of the Admin Views module, so you can add filter options as GET parameters in the URL: http://localhost/admin/content?type=article

You can also make a clone of the content admin view and modify it. This would allow you to set contextual filters, modify the exposed filter fields, or adjust visible columns to make a more targeted content listing.


How to modify image field in field_attach_preprocess_alter I have an image field called field_grid_image on a custom node type "event". I want to populate this field when not available but I don't want to use a default image.
I want to add a default image based on the node's taxonomy. I have written the following code to load the image from node's taxonomy field but it doesn't show up in the final output.

function custom_event_field_attach_preprocess_alter(&$variables, $context) {
    if($context['entity_type'] == "node" && $context['entity']->type == "event" && sizeof($context['entity']->field_grid_image) == 0){
        $tid = $context['entity']->field_event_type['und'][0]['tid'];
        $taxonomy_term = taxonomy_term_load($tid);

        $values = field_get_items('taxonomy_term', $taxonomy_term, 'field_generic_image');
        $variables['field_grid_image']['und'][0] = $values[0];

        dpm ($values);
        dpm( $variables);
    }
}

When I print $variables I see the field populated from the taxonomy as follows.

Any ideas why the image is not rendered in the final output?

Thanks,

I've figured out the problem. I should have used field_view_value to render the field and add it to $variables['content'] instead of editing the field directly.

The below code works as expected now.

function custom_event_field_attach_preprocess_alter(&$variables, $context) {
    if($context['entity_type'] == "node" && $context['entity']->type == "event" && sizeof($context['entity']->field_grid_image) == 0){
        $tid = $context['entity']->field_event_type['und'][0]['tid'];
        $taxonomy_term = taxonomy_term_load($tid);

        $values = field_get_items('taxonomy_term', $taxonomy_term, 'field_generic_image');
        $node = $variables['node'];
        $output = field_view_value('node', $node, 'field_grid_image', $values[0], array(
            'type' => 'image',
            'settings' => array(
            'image_style' => 'gridimage',
            'image_link' => 'content',
            ),
        ));

        $variables['content']['group_image_text']['field_grid_image'] = $output;
    }
}


Drupal 8 One-off Custom Page for Theme I'd like to create a one-off custom page which will contain several text fields.

The layout for the page will be custom, placing the text fields in various locations next to design elements, diagrams and maps. I'd like the site editors to be able to update the text fields/labels, including language versions.

I'm generally familiar with the render API, page and node templates, and I do know that I could create a dedicated content type (node, content entity) with all the fields required and then a page template (Drupal 8 custom page template) to render the node (and its language versions).

Just wondering if it makes sense to create a complete content type for what will effectively be a one-off (albeit important) node/page.

Thoughts? Suggestions?

You might want to have a look at the Paragraphs project. It basically allows you to create different building blocks (Image with text, Diagram with description, ...) and then you can piece them together in the edit form pretty easily.

Check out the demo module that's part of the project for a quick start. You'll still have to actually implement the design for each building block but once you have that, you can easily change how you've combined them and move parts around, add new ones.. create multiple pages that each uses those building blocks differently.


Views attach block to a field I want to create a simple websites listing. I have created a content type named Sites and a taxonomy vocab named Sites to handle Sites nodes categorization. i.e every Site node (a content of type Sites) belongs to one term under Sites taxonomy vocab.

In the Views module, I have created a new Page view which has the path /sites-cats-listing and it shows Taxonomy terms of type Sites. The format is Unformatted list and it is only has one field Taxonomy term: Name

It renders a simple list of Taxonomy vocab Sites terms as expected. However, I want to list all of sites titles that belongs to each taxonomy term, so, I will get two levels list something like the following example:

-term1
--Site1
--Site2
--Site3
-term2
--Site4
--SiteA
etc...

Also I need to be able to rewrite the site's title field to make it linked directly to the destination website.

So, I need to know is there any way to attach a block to field which the block takes its contextual filter from the field value? Or is there any other workaround to complete this task? I have tried EVA but I could not able to find what I want to get.

this can be done with a bit of code in a tpl file or in a preprocess function.

Views has a function views_embed_view that you could use to embed the block into your field output.

print views_embed_view('views_name', 'display_id', $fieldvalue);

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


How to make the comment author name required for anonymous users? I'm trying to make the comment author name required with this code:

use Drupal\Core\Form\FormStateInterface;
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_comment_comment_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['name']['#required'] = true;
}

But I can't find the way to do so. How to make the comment author name required for anonymous users?

I found the answer:

Implementing the hook_form_FORM_ID_alter() hook you can use the comment form id (comment_comment_form) to alter the form.

The problem was that the field name is inside the author, so you need to use $form['author']['name']['#required'] = TRUE;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_comment_comment_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['author']['name']['#required'] = TRUE;
}


Translated node overwrites other languages I have a content type with a multivalue text field. Each time I add a translation, the translated node overwrites the source node. Also happens in opposite direction. It seems that whatever I do, the field always overwrites. The node title doesn't though.

I have synchronisation turned off on my content type. What could it be?

Try to do editing of node using path prefix of language in which the node you edit is. So, this would look like:

[site-domain]/[language-path-prefix]/[path-to-node-edit]

You need to enable 'URL' detection method in '/admin/config/regional/language/configure'

Let me know if this is working for you.


How do I do namespacing in a module from an external project which is not in the src directory? Based on Why do I have conflicts in namespacing? I adjusted my complete system.

As long as I do namespacing in /src, it is goes all very well.
I included my project from Github. Those class files are located in modules/custom/tb/vendor/ccxt/ccxt/php.

When not working with namespaces I included them with include "vendor\ccxt\ccxt\ccxt.php";.

How should I include those classes to module? Because of the Composer structure, those files are in  the vendor sub-directory.

Because of namespacing in Drupal, use \Drupal\tb\<classfile> doesn't work.

The content of the composer.json file is the following.

    "name": "org/tb",
    "description": "This extension provides new commands for Drush.",
    "type": "drupal-drush",
    "authors": [
        {
            "name": "Author name",
            "email": "author@example.com"
        }
    ],
    "require": {
        "php": ">=5.6.0",
        "arcturial/clickatell": "^3.0",
        "ccxt/ccxt": "^1.14"
    },
    "extra": {
        "drush": {
            "services": {
                "drush.services.yml": "^9"
            }
        }
    }
}

From your post, it looks like you added the above composer.json file, then ran composer from the module root. This is not the way to do it. This will create a vendor folder inside your module folder, which is not what you want.
What you need to do is add the composer.json file to your module, then push that to the remote repository. Then use Composer to install and manage the module. Doing this will add the library to the vendor folder for your project, and the library will be available when calling \ccxt\ccxt


Drupal feeds module causing high cpu usage when pulling feeds I am using the Drupal Feeds module to download the feeds from an external site. I have setup a dedicated content type to pull the feeds and then created nodes of another content type for the individual feed items.

After updating the site recently I noticed that the site was using the CPU continuously so much so that the hosting tech support notified me about it.

I proceeded to limit the frequency with which the feeds were being pulled but the CPU usage remained constant and I was finally forced to disable cron.php.

This never happened before the update.

Checking the dblog I noticed that the JobScheduler initiated the feed pull (I had set the watchdog to print the title of each node being created) and was repeating this scenario every minute 24x7.

I have not figured out what is causing this issue or from where to start?

Any possible solutions guys?

Site runs on Drupal 6.

If you are in shared hosting, then it is the right time to upgrade to VPS or Dedicated Server.

I had a same issue How to control resource usage of my website? , better you can remove the unwanted bots. You need to see the Access Log in your hosting control panel.

try disabling your modules one at a time to decide when the load time gets really high and remove the unwanted modules and also it delete from modules folder.


What D7 settings need changed to take advantage of bigger cloud server I've just upgraded my Rackspace cloud server to 2GB in hopes of speeding up my site. What steps should I now take to enable my Drupal site to utilize this extra memory?

Php mem is to 512MB at present. This is as far as I have gone in changed things (could I go higher, should I?)These are the types of questions I have..

Varnish, Memcache, & APC come to mind. PHP either has enough memory or it doesn't; giving it 512MB wont speed it up.


Can't edit Main menu block in sidebar by clicking on "gear" Today on one of my websites I encountered something strange. I have my "Main menu" block in my left sidebar, and when I hover over that block, the "gear" to edit it shows up, but clicking on it does nothing. Also, on pages that the block wouldn't show up on, it does (rather, the blank space does) with nothing in it, and the gear still shows up and is not clickable.

I tried moving the block out of the region, saving, refreshing, moving it back, saving, and refreshing again to see if that would fix anything, but that has not.

Any help would be greatly appreciated!

Updates:

What I mean by "nothing" is that there is the empty region with my main content area pushed over as if there actually was block content there.
And 3 errors in the console: Uncaught TypeError: Cannot read property 'msie' of undefined panels.js?ndi45m:6.... Uncaught TypeError: Cannot read property 'msie' of undefined admin_menu.js?ndi45m:223.... Failed to load resource: net::ERR_CACHE_MISS

It is caused by legacy functionality in old versions of jQuery no longer being supported in more modern versions. In this particular case I think it has to do with browser version detection, which has fallen out of favour for feature detection.

Add the jquery-migrate script to your theme's javascript folder and load it via your theme's info file.

If you continue to have issues you might need to make sure this file loads directly after the jQuery main file.


How the RTL css system works in drupal specially in omega theme? I am building a multilingual site (using Omega theme) which has two languages, one LTR and the other is RTL.

Can someone please explain how the RTL mechanism works for css in Omega theme?

The css file with the rtl at the end will be loaded whenever you have a RTL language added to your site. in Omega as the CSS files are generated by Scss you need to create a scss file with the rtl at the end of the file so at the time of compiling the scss you will have the rtl css files ready to use.
The RTL files will override the original files.