Untrusted Host "localhost" in From Drupal 8 beta 6 (released today), I have this error :

  Error message UnexpectedValueException: Untrusted Host "localhost" in
  Symfony\Component\HttpFoundation\Request->getHost() (line 1221 of
  core/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/Request.php).

I use this local url to call my site: http://theming.dev

Inside my setting file, I have:

     $settings['trusted_host_patterns'] = array(
        'theming\.dev$',
     );

Note, this error is displayed only when I uncomment this lines:

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

What is the problem please ? Thanks.

This problem occurred for me when building an 8.0.0-beta6 test site on my Ubuntu 14.04 laptop.  I have an Apache web server running locally, with the test site defined using a VirtualHost directive.  I add the domain name of the test site ("example.com") to my /etc/hosts file, pointing to 127.0.2.1, to bypass the need to use real DNS entries.

After installing the site, everything looked fine.  However, I noticed a warning message on the Status Report page about not having trusted_host_patterns set, so I went into my /sites/default/settings.php file and added these lines:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^www\.example\.com$',
);

Upon saving the file and reloading my browser, I got a very generic error page and, after commenting-out the new lines, noticed the Untrusted Host "localhost"... log message.

It appears that because I'm web-browsing from the same computer on which the web server is running, the Host is at some point getting converted to localhost, and thus is failing to match the set of patterns I had specified.  I was able to fix this issue by changing these lines to:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^www\.example\.com$',
  '^localhost$',
);

On a site that is intended to be put into production, you might want to utilize a settings.local.php file to specify ^localhost$ as a valid host pattern for testing purposes only.  Note that if you want to do this, you'll need to uncomment these lines in the default settings.php, and move them to the bottom of the settings.php file:

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

In this case, the settings.php file would only contain the actual domain names:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
  '^www\.example\.com$',
);

and settings.local.php would contain:

<?php
$settings['trusted_host_patterns'][] = '^localhost$';

to append localhost to the list of valid hosts.  With this configuration, you would not copy the settings.local.php file when copying the site to the production server.


How to remove white space from a field using Search API module I'm using Search API and Search Views to search the Drupal user database.

One of the fields is phone number where users are able to enter free text.

I can include this field in the search, but the search will not pick up part words.

E.g. 6162 5555 - does not display when I search for 25555 because the index sees these terms as separate words.

Is there a way to strip all the site space (and maybe then brackets) from the field before it is indexed by Search API?

I would use Computed Fields. Store and display user input with spaces, but index and search computed field too.

  These computed fields are populated with values that you define via PHP code.

So you can simply remove white spaces, or re-format phone number in any way you please, and store a standardised copy of user's phone number. That way both representations will be searchable.

As a small bonus, other modules (like Views, various exporters and connectors or phone integration) would be able to benefit from this too. Bad thing is a slight overhead on reads and saves.


Ability to only allow certain content to be added between a range of dates I have a drupal 7 site that is used for registration for certain events.  We are currently using content types to collect the information.  What I need is to only allow registered users to post certain content types between a certain set of dates.  Certain roles should be able to add/edit at any time.

For example.  One of the content types is Grant.  But we only accept grants between May 1 and May 31st.

Before May 1st we'd like to have a message that states: Grants are currently not open, please check back May 1st.
After May 31st we'd like a message to state: Grants are currently closed for Spring 2018, please try again next year.  or something like that.

I would suggest looking into the Rules module for this.

Using this module, you can use its Condition feature to:

Check the date ranges that you specified
Check what content type is being created
Check the current logged in user's role if it's the permitted user role to create a content type

Based if these conditions are met, you can then add what event or message for this matter to display to the user. You aren't also limited to creating one rule but you can create multiple rules based on your conditions.

Hope this gives you an idea and solution.


I need a .schema.yml file when I create a new custom field? I just read Create a custom field type and I can't find a lot of information about the .schema.yml file. So, I just create a custom field without the .schema.yml file and I see that if I add my custom field in a content type and I export my config the field is exported with all the configuration.

So we really need the schema.yml file when I create a new custom field?

To make sure configuration and default values are using the correct types, there can be tricky bugs related to float/int for example.

If you have interface strings in your settings, you can also use the config schema definitions to make them translatable.

And it can be used to validate configuration.

Config schema is not enforced by default, see https://www.drupal.org/node/2625212. But it enforced by default in tests, so try to write a test that creates a field of your type and it will complain and tell you what schema is missing.


Using a field for populating the meta-tags of view pages I've got taxonomy pages that are emulated by real views. The vocabulary terms have an additional field "field_meta_description", where meta-description tags can be added. On the view page of each term, this field should be used to populate the content of the html tag <meta name="description"/>.
How can this be accomplished? I know there are some modules out there like metatag, but I am looking for a custom way to do it by lightweight self-coding.

Assuming Drupal 7:

You can go for implementing hook_page_alter() in your theme's template.php and use drupal_add_html_head() to insert your own metatags. Following the link you will find lots of exmples in the comments.


How to add file extensions while creating a field (type file) through the module installer.yaml? I need to add 4 fields to an existing content type in Drupal 8 website, 2 of them is text another 2 is file type, I have a multisite setup and have 30 country-specific sites so I need to add for every locale site, Now I have created a module and created installer file, right now I am able to create the fields but I am unable to add the file extension to the file type field. can anyone please help with this?

I have followed this below documentation to create the filed.

https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type

Really, that's a task for the Features module. And even if you decide against fully using Features in the end, you could at least use it locally to export your content type and fields and see in the resulting installer files how the allowed file extensions needs to be defined in your own module then. As Features exports its config into ready-made modules. But going for fully using Features also will enable you to constantly sync certain config (content types, fields, image styles etc.) pretty easily across all your multisite instances.

Take one of your multisite instances where you have the content type like you want it to be on all other sites.
Go through Features' UI and create a features module from it (that's called "package", usually that goes under /modules/features/my_package).
Activate the resulting package (module) on all other instances.

Leaving the Features module and your package module activated on all instances now allows you to sync all following changes to your content type by a certain set of commands:

# In the site_foo instance export changes into its package module.
drush -y features:export my_package -l site_foo

# In the site_bar instance import the changes.
drush -y features:import:all --bundle my_bundle -l site_bar

# In the end export config as usual.
drush -y config:export -l site_foo
drush -y config:export -l site_bar

To have a file field install sample yaml:

langcode: en
status: true
dependencies:
  config:
    - field.storage.paragraph.field_dlbox_files
    - paragraphs.paragraphs_type.dlbox
  module:
    - file
id: paragraph.dlbox.field_dlbox_files
field_name: field_dlbox_files
entity_type: paragraph
bundle: dlbox
label: Files
description: ''
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings:
  file_directory: paragraphs/dlboxfiles
  file_extensions: 'pdf doc docx'
  max_filesize: ''
  description_field: true
  handler: 'default:file'
  handler_settings: {  }
field_type: file


Admin language module I'm currently building websites with the Administration Language Module. For the first time, the admin language is different than the default language but it doesn't work. For example, my default language is English and I'll set Spanish for the admin menu. My admin menu (and all administration dashboard) is partially translate.

As you can see, sometime item's menu are in English and in Spanish.

However, "People" is correctly translate in Translate Admin.

Can you help me?

Visit admin/config/regional/language and select an admin language
Visit admin/config/regional/language/admin_language and enable Use administration language for the core toolbar


after migrating to D7 all images are missing After migrating to D 7.20 all my images are gone, actually they exist on the server but are not being displayed at all. I have a multi-site installation and I've successfully migrated all the content and re-enabled the modules.
I have a page where all the users pictures should be displayed and none of them are being displayed. So, I've created a new account and uploaded a picture for it and this new picture appears. What should I be looking at? How can I migrate all the pictures to the new installation properly ?

Thanks.

The storage of user pictures changed from D6 to D7. I think the answer for your problem might be found at Picture Migration on drupal.org.


How to add a theme preprocess function for published state? I want to create a body class for the published state of a node. I found some suggestions below for Drupal 7, but this code is not working for my Drupal 8 theme.

Add class based on published state

How can I acheive this?

You can fetch the node using routeMatch and add the class like this:

function THEME_NAME_preprocess_html(&$variables) {
  $routeMatch = \Drupal::routeMatch();
  $node = $routeMatch->getParameter('node');
  if (isset($node) && $routeMatch->getRouteName() == 'entity.node.canonical') {
    if ($node->isPublished()) {
      $variables['attributes']['class'][] = 'class-name-published';
    }
    else {
      $variables['attributes']['class'][] = 'class-name-unpublished';
    }
  }
}

This only adds the body class if you're on the entity.node.canonical route, to make sure that we always get a node object from the route parameter.


Custom REST Resource POST problem I want to POST json data to a custom REST resource. I tested with postman and Insomnia but i get the message as if would've done a GET request and returns the get functions result. The GET function works fine btw.

In the logs it says "Switched from post to get".

I just want to return the data the user passes. This is the code of my custom REST resource:

<?php
namespace Drupal\foolzz_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides User Profile REST Resource
 *
 * @RestResource(
 *   id = "profile_resource",
 *   label = @Translation("Profile resource"),
 *   uri_paths = {
 *     "canonical" = "/foolzz_rest_api/profile/{uid}"
 *   }
 * )
 */
class ProfileResource extends ResourceBase
{
    /**
     * Responds to entity GET requests.
     * @return \Drupal\rest\ResourceResponse
     */
    public function get($uid = NULL)
    {
        $query = \Drupal::database()->select('foolzz_users_profile', 'data');
        $query->fields('data', array('fk_users_uid','status','displayname','birthdate','biography','gender','realname'));
        $query->condition('data.fk_users_uid', $uid);

        $profile = $query->execute()->fetchAssoc();

        $response = ['profile' => $profile
        ];

        $build = array(
            '#cache' => array(
                'max-age' => 0,
            ),
        );

        return (new ResourceResponse($response))->addCacheableDependency($build);
    }

    /**
     * Responds to POST requests.
     * @return \Drupal\rest\ResourceResponse
     * Returns a list of bundles for specified entity.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     *   Throws exception expected.
     */
    public function post(array $data = []) {

        $response = array(
            "data" => $data,
        );

        $build = array(
            '#cache' => array(
                'max-age' => 0,
            ),
        );

        return (new ResourceResponse($response))->addCacheableDependency($build);
    }
}

Looks like you've stumbled across the same stumbling block as I have a couple of times. Try with this piece of code - note the create entry after canonical:

 *   uri_paths = {
 *     "canonical" = "/foolzz_rest_api/profile/{uid}",
 *     "https://www.drupal.org/link-relations/create" = "/foolzz_rest_api/profile/{uid}"
 *   }
 * )

Read more at:
https://www.drupal.org/node/2811757
and
https://www.drupal.org/docs/8/api/restful-web-services-api/restful-web-services-api-overview

Oh and for the post request, I'd use ModifiedResourceResponse instead of fiddling with cache headers by hand (I learned about the existence of that from Drupal Core's EntityResource)


why Cache-tags is different if i am logged? I try to understand how drupal core cache tags is add :

this is my tags on my home when i am logged :

node:121 node:158 node:23945 node:23946 node:43328 node:491 node:514 node:59139

It's good, this relate my node on my home.

But if i check my home in anonymous, this is what i get :

node:115 node:121 node:153 node:158 node:172 node:18240 node:18244 node:18256 node:23945 node:23946 node:307 node:43328 node:45 node:491 node:514 node:59139 node:59143 node:59144 node:59145 node:59146 node:59147 node:59148 node:59149 node:59193 node:59197 node:59239 node:59269 node:59283 node:59289 node:59293 node:59522 node:59770 node:60375 node:60390 node:60415 node:60418 node:60480 node:60542 node:60606 node:60616 node:60727 node:60785 node:60793 node:60819 node:60824 node:60827 node:60873 node:66011 node:66019 node:66026 node:66028 node:66030 node:66036 node:66039 node:8555 node:8561

And most of this tag is wrong for the home page, how drupal find them ?

I know there is a cache context, but its the core who add this tags

EDIT

After some debug i got some answer :

Context : my menu is render by core block menu in region.

For anonymous user, drupal add the tag node:id for every item in my menu.

if i remove the block, all node:id tag is removed.

So i have 2 solutions :

For all user who hasn't bypass node access permission drupal add every tag from the menu block render.

So i can try to fix the access check on the menu

Remove the drupal core block menu from region and build my own block programmatically and load my menu inside with menu_tree service.

i have try the second point and since its not drupal who render my custom block, tags is not add.

But for me the best way is to find a way for fix the check access.

i can't clear all the node in the cache when someone edit a node in the menu.

For that i want use the tag menu_link_item but not the node:id...

You don't need to render a node to bubble up its cache tag. There are other reasons, for example access checks, which heavily depend on the current user. A negative access check still could bubble up the node cache tag when the result depends on field values. So the tags of not rendered nodes could be unpublished nodes in views or menus. When you publish one of those nodes you want that the page gets refreshed to include the now published node.

Edit

You can replace the core menu block with a custom menu block, see

  Rendering menus

  Once you have created menus (that contain menu links),
  you want to render them. Drupal provides a block
  (Drupal\system\Plugin\Block\SystemMenuBlock) to do so.

  However, perhaps you have more advanced needs and you're not satisfied
  with what the menu blocks offer you. If that's the case, you'll want
  to:

  ...

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/group/menu/8.8.x

By doing so you have the options to not use access checks at all, add your own version of an access check tree manipulator or use the core one and remove the cache tags from the tree access objects afterwards with AccessResult::resetCacheTags


Programmatically using values from a loaded entity inside a message I am using Firebase module to send push notifications to a specific mobile user when a webform is submitted.

Below is my custom webform handler:

<?php

namespace Drupal\my_custom_module\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Send Push Notification when a webform submission is submitted.
 *
 * @WebformHandler(
 *   id = "Send Push Notification when a webform submission is submitted",
 *   label = @Translation("Send Push Notification when a webform submission is submitted"),
 *   category = @Translation("Push Notification"),
 *   description = @Translation("Send Push Notification when a webform submission is submitted"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */
class PushNotificationWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get (NID) from text element available on the webform.
    $nidvalue = $values["attached_node"];

    // Load the node.
    $node = \Drupal\node\Entity\Node::load($nidvalue);

    // Get (selected_node_owner) value from the User Entity reference element available on the webform.
    $nodeowner = $values["selected_node_owner"];

    // Get (token) value from the loaded node through the 'field_node_owner' Entity field.
    $usertoken = $node->field_node_owner->entity->field_user_push_token->value;

    // Send the Push Notification.
    // Token is generated by app. You'll have to send the token to Drupal.
    $messageService = \Drupal::service('firebase.message');
    $messageService->setRecipients($usertoken);
    $messageService->setNotification([
        'title' => 'Hello',
        'body' => 'Hello $nodeowner this is your body message',
        'badge' => 1,
        'icon' => 'optional-icon',
        'sound' => 'optional-sound',
        'click_action' => 'optional-action',
    ]);
    $messageService->setData([
        'score' => '3x1',
        'date' => '2019-04-05',
        'optional' => 'Data is used to send silent pushes. Otherwise, optional.',
    ]);
    $messageService->setOptions(['priority' => 'normal']);
    $messageService->send();
    }
}

Everything is working as expected but the 'Variables' are not rendering any values and printed as they are.

Example:

I am expecting the body of the notification message to be something like below (Say the selected_node_owner name is "Elie Masaad"):

Hello Elie Masaad this is your body message

but instead I am getting the below:

Hello $nodeowner this is your body message

Module maintainer gave the below hint:

You should use a Token or simple str_replace for replacing something in string.

Can anyone guide me on how to pragmatically use tokens for my above requirement ?

As Clive also mentioned use double quotes instead of single quotes to allow the variables to get replaced inside the string

'body' => "Hello $nodeowner this is your body message"

if $values["selected_node_owner"] gives you the UID here is how to get the username

$account = \Drupal\user\Entity\User::load($values["selected_node_owner"]);
$nodeowner = $account->getUsername();


Multiple login attempts from different IP Addresses My website has been getting about 25 login attempts per hour for the past few days for usernames admin, administrator and our website name. The attacker seems to be using differing IP addresses and when I checked the last 3 hours worth, only two were are actually repeated. It's not much of a security issue since those are not the usernames we use for admins but it's kind of annoying that it's filling up our logs. What modules/options are available?

You can use Rename Admin Paths module to override the admin path.

  This module allows you to:

rename path like '/admin/...' to '/something/...'
rename path like '/user/..' to '/something else/..'

  It can be effective against registration spam bots or malicious
  people.

And using the Login Security module you can

  limit the number of invalid login attempts before blocking accounts,
  or deny access by IP address, temporarily or permanently.

  A set of notifications by email or Nagios may help the site
  administrator to know when something is happening with the login form
  of their site:

  password and account guessing,
  bruteforce login attempts or just unexpected behaviour with the login
  operation.

  For alternative controls, Login Security can disable Drupal core's
  login error messages, obfuscating the reason for the login failure.
  This could make it harder for an attacker to discover whether the
  account even exists.

The use of the Flood control module is another option to control variables like the login attempt limiters and any future hidden variables.


Using php if else statement in display suite Ok i purchased a theme from themeforest called wunderkind.

I liked most of the things about it except for the blog page.  I liked the more traditional look of the summary image/video on the right and the blog summary on the left. Instead of one on top of the other.

So I am using display suites to layout the blog teaser and everything is working fine except that the blog article content type is dynamic.  You can have either a standard post or a video post.  If you choose video then a video URL field appears, and if you choose image then an image field appears.

I am trying to figure out how to create a code field in display suites that will either display the image or display an iframe with the video url.

The other route I am considering is simply creating a field in the blog called summary image and have it display on the main blog page.

Any help would be appreciated.

If your need is simple, a "hide when empty" for example, you definitely need to look into Field formatter conditions module, it will allow you do simple conditions on your field formatters for a given view mode.

If that's not enough, Display Suite allows to have arbitrary fields added to the view modes, you need to look into hook_ds_fields_info and implement it in a custom module for your needs.

/**
 * Implements hook_ds_fields_info()
 */
function my_module_ds_fields_info($entity_type) {
  $fields = array();

  $fields['my_field'] = array(
    'title' => t('My field'),
    'field_type' => DS_FIELD_TYPE_FUNCTION,
    'ui_limit' => array('node_type|*'),
    'function' => 'my_module_callback_function',
  );

  return array('node' => $fields);
}

function my_module_callback_function(&$field) {
  // Here goes your code, the conditions to display or not another field
  // and return an array with the data.
}

Further examples in https://stackoverflow.com/questions/16253312/using-hook-ds-fields-info-is-there-a-way-to-use-standard-formatters-so-the-op and http://www.previousnext.com.au/blog/creating-custom-display-suite-fields-or-how-i-learned-stop-worrying-and-use-hookdsfieldsinfo


White Screen of Death, From Apache to Litespeed I'm facing a White Screen of Death on some backend(admin) pages after migrating to a new server. Apache--->LiteSpeed. New domain. When I migrate to a different server running Apache I don't have any issues.

I get WSOD when I click "Flush all caches" or after enabling a module.

The link to configure AWS for PHP module is missing from the admin menu.

Recent logs messages:

page not found   2013-08-01 18:19    build/mediaelement-and-player.min.js
page not found   2013-08-01 18:20    favicon.ico

May you help?

You want to increase your memory_limit and max_execution_time in your php.ini file.

Here is a link that tells you more about that


Custom Form API elements in node form I am rendering node form on my custom page with such a code:

<?php
 $form_state['build_info']['args'] = array($node);
 form_load_include($form_state, 'inc', 'node', 'node.pages');
 $form = drupal_build_form($type . '_node_form', $form_state);
 return drupal_render($form);
 ?>

I need to add  some custom form elements to the form as follows:

 <?php
  $form['mycode'] = array(
 '#type' => 'textfield',
 '#title' => t('My code'),
 );
 ?>

The custom form elements are displayed correctly in the form. The problem is, when I submit the form, I cannot see custom values in $form_state or even $_REQUEST array.
I am checking $form_state values in the implementation of hook_node_submit

What is the correct way to add custom form elements to node form (except creation of fields) ?
(I need custom form elements because I need to use different field widgets for various user roles. I also need to add checkbox like "I have read Terms and Conditions" into node form.)

thanks
Tomas

You need to use hook_form_alter for this requirement. You can create a submit function for the same & declare it as submit function for previously created alter function. You can access $form_state into that.

In same way you can have your own validate function etc.


Notifications for anonymous users on nodes I am looking for a module or some kind of workaround e.g. involving Rules, that will allow anonymous users to subscribe to new comments on nodes they have created. My user scenario is as follows:

An anonymous user wants to post a new forum topic
She clicks on the “Add new forum topic” button
On the URL node/add/forumtopic she is presented by the usual form
On the form there is an email field with a check box underneath with the label “I would like to receive an email when comments are posted to my thread”
She types in her email and marks the checkbox - yes, she would like to have email notifications
She submits the form and when a comment is posted in her thread, she
gets a notification email with a link to the comment and a link that
allows her to unsubscribe from the thread.

I have looked at this nice writeup on groups.drupal.org where different notification modules are compared, but none seems to be offering the functionality I am looking for.

I have installed Comment Notify that offers the desired functionality - but only on comments, not on nodes.

I have tried installing Watcher, but it is early in development and still seems pretty buggy.

This seems to me like a very common scenario - what would be the recommended way of implementing this feature? Any help is very appreciated.

I would probably solve this with the following Rules-based setup:

1) Create a custom entity for anonymous posters with only a text field for email and an entity reference field for the node they created. Here's a pretty good writeup on creating custom entities:
http://www.istos.it/blog/drupal-entities/drupal-entities-part-3-programming-hello-drupal-entity

And here's Drupal.org: http://drupal.org/node/1026420

2) Create a rule for "Node->After saving new content" that checks if the poster was anonymous and if so, creates a new anonymous posters entity with the user's email + reference to the created node.

3) Create a rule for "Comment->After saving a new comment" that does a "Fetch entity by property" action and after a anonymous poster entity, sends an email out to them.

The only trick you need to figure out is how to play with rules upon fetching entities and accessing their fields. You need to create some rules component so achieve this whole flow since in order to access the field in the entity, you need to verify the type of the entity and this happens in "conditions", which can't be done after "actions" which is where the "fetch entity by property" magic happens.

So you'll basically have to create a Rules Component that does what needs to be done with the fetched entity.

This is definitely not the only way to achieve what you need to accomplish, but since I'm a strong believer in the endless powers of Rules, I like solving things with it. :)


How to correctly invalidate a cached node when a menu link content is added/updated/deleted? I'm currently facing an issue:

By following the contrib module's(menu_link_attributes) functionality, I altered the menu item's form to have a visibility by path option(almost the same as in the block config form).

I am saving the input data from the form in the menu_link_content's options column, then unsetting the menu item in hook_preprocess_HOOK() if the conditions are met.

The thing is, we have cached pages which are basically nodes(only on dev environment, the local one works as expected because caching is disabled) and the menu item is unset only after a CC.

I'm trying to add a cache tag to the node so that it's invalidated after I'm done with menu items.

/**
 * Implements hook_preprocess_HOOK().
 */
function prl_menu_item_visibility_preprocess_node(&$variables) {
  // Since all the pages are nodes and all of them are using footer menu, we add the menu_link_content cache tag and invalidate it
  // when a link is saved and supposed to be hidden on specific pages.
  $variables['#cache']['tags'][] = 'menu_link_content';
}

Unfortunately, no success.

The tag you add doesn't exists. You probably want to add the list tag from the menu link content, which is invalidated in all cases when a link item is added, updated or deleted:

$variables['#cache']['tags'][] = 'menu_link_content_list';

But there might be another problem. As I understand your idea is, if you have a cache tag somewhere on the page, the complete page gets invalidated. This is true, but it will not help you. The rebuilt page will contain the cached menu block, if the block has not the correct cache tag on its own. So if you add a cache tag from the menu link to the node you have to do the same vice versa, add a node tag to the menu.

And probably you also need a cache context in the menu block for the visibility.


FileDepot module help I am using FileDepot module, and I wanted some help in this. I wanted the authenticated users to create their own folder, and upload their files. They can upload files, but they cannot create their own folder. How do them give them the permission to create their folder?

I found a feature like LOCK. What is this lock feature basically used for?

I think the lock feature is to indicate that you are editing the manuscript. When you are ready editing, and have uploaded the next version, you can unlock it.


Commerce and Attribute Quantities Our Goal

We're creating a book product. It comes in a variety of sizes (ex. 5x5, 8x8, 10x10) with 20 pages included. We're using the size as an attribute field. Customers can order a standard book, or add additional pages up to 100 total pages. Additional pages are priced /page and /size; for example 5x5 = $1.00/page, 8x8 = $1.50/page etc. The "Add to Cart" section should look something like this:

===========================

BOOK

Size [5x5]
Pages [ enter amount ]

Total: $75.00
[Add to Cart]

===========================

The simplest solution would be to add a pricing option with its own quantity field, except that functionality doesn't seem to be available.

I've considered the following:

Commerce Option I: Creating a pricing attributes option (select list or radio button styles as a slider). The only caveat is the admin on adjusting pricing for 4000 options (50 books with 80 page options each) is a usability nightmare.
Commerce Option II: Creating a pricing attributes integer field (acting as a quantity field) and using Rules to do the math and adjust the pricing. Unfortunately the variables and math did not seem to be available to Rules.
Commerce Product Bundle: Creating a pages product variation and using page size as an attribute field. That would allow us to leverage the quantity field in the bundle's add to cart display. The problem in this case is two fold:

Having to create 3 product variations, then having to create at least 2 products (book and book/pages bundle; 3 if you have different papers or page pricing needs to vary) each time you add a new book to your collection. This very quickly creates something close to an administrative hell for the shop owner.
Commerce Product Bundle is still in Alpha, and has been for 2 years. No commits have been made in over a year. The module, even though it often works well, is buggy and doesn't play well with Commerce Option; which we leverage quite substantially.

Custom Line Item: Using Randy Fay's "custom line item custom discount technique" leveraging an integer field and rules. I added an integer field to the product variation for cost per page. Then created an integer field which needed to be exposed to the customer. Using the combination of both I attempted to create a rule which calculated the additional price based on the product of the those fields. It does not appear that this is possible using Rules.

Conclusion, and request for additional brain power

I've gone around multiple circles trying to figure this one out and am about to go completely bonkers. Perhaps I'm missing something completely simple, or I'm approaching this problem from the wrong angle. Has anyone been able to do something similar? How did you achieve it?

Commerce by default supports line item fields that can appear on the Add to Cart form. If you only sell this one type of product on the site and will always need that "additional pages" field, then you could just add the field to the default product line item type. If you have other needs, you'd use a custom line item type either defined in code or created via https://drupal.org/project/commerce_custom_product.

Once you have customers putting in their custom number of pages, it's up to you to adjust the price accordingly. Pricing rules receive the full line item object for price manipulation, including the values of any line item fields present on the Add to Cart form. You can construct a variety of rules that look at the referenced product to determine how much to charge for additional pages and work it out using the Rules actions to create data values.


How to call a function on node submit in drupal 7 I have created content type programmatically.. I don't want to display its node data in a block. Now I want to fetch data and save fetched data in a variable.
How can I do it ?

Or else how can I call a function on node submit ?

here is my code :

function default_content_form_alter(&$form, &$form_state, $form_id) {
    debug($form_id);exit;

    switch($form_id) {
        case 'name_of_the_form':
            $form['#submit'][] = 'test_form_submit';
        break;
    }
}

function MODULE_form_alter(&$form, &$form_state, $form_id)
{
  //echo $form_id; // get the form id
    switch($form_id)
    {
        case 'name_of_the_form':
           $form['#submit'][] = 'test_form_submit';
           break;
    }
}

function test_form_submit($form, &$form_state)
{
  drupal_set_message("How are you");
}


Using version control/deployments with Context I've started to use Context. It actually works pretty well. I've created a context locally. It looks like, in order to get that context remotely, I have to export it and then copy and paste that into the remote server.

It's not a major pain, but we have dev, stage and live servers, plus the context isn't under version control, so any changes (or in fact the context itself) aren't stored in code.

Ideally, I'd have a situation like Views where I export the View, paste it into a file, deploy that file from version control to remote servers and the View updates on those servers.

Is this possible for context? Maybe using CTools?

The slight quirk is: I don't really like Features, and, at the moment, it seems overkill to add that as a module just for the sake of one context.

OK; so I swear I did look reasonably hard for this before I posted the question, but I have done the thing where I've genuinely found the answer 15 minutes after posting.

http://www.mcdruid.co.uk/content/default-drupal-contexts-like-default-views was the blogpost I needed - he's created an issue to get this information into the module, but it looks like it won't happened.

This seems to work really well, and I've created a separate submodule just for contexts.


D6: Create block view which returns all nodes with related terms I have a vocabulary which contains a large number of terms, most of which have been given relationships to other terms.

I want to create a block display of a view which takes the term from the current node and displays all the other content which has a related term from the same vocabulary.

So far, I have been able to return all nodes with the same term using this as a views argument:

node = node_load(arg(1));
if($node) {
foreach($node->taxonomy as $term) { $terms[] = $term->tid; }
return implode('+',$terms);
} else { return; }

However, I haven't been able to combine this with taxonomy_get_related to return nodes related by term.  Any suggestions?

You probably have to do the follwing:

create a view
add a block to that view
add a contextual filter (in Drupal 6 it is an Argument)
configure it with:

Action to take if argument is not present: Provide default argument
Default argument type: Node ID from URL
Validator: taxonomy term
You can use Term ID from the URL, or try to use the term name.

Then you have to save and configure the block to show on the desired page...

These settings in Drupal 7 (more or less, there are some slight differences in interface) work for me...


How can I render a block in the sidebar in php? I'm using the Zen theme and I'm trying to keep as much in code as possible. I'm currently using context to render the block, but I like my php :)

I'm aware of

$block = module_invoke('views', 'block_view', 'name_of_view_display');
print render($block);

// and this
$block = block_load('views', 'name_of_view-name_of_view_display');
$output = _block_get_renderable_array(_block_render_blocks(array($block)));

which works perfectly in most cases. My page.tpl file says

<?php if ($sidebar_first || $sidebar_second): ?>
  <aside class="sidebars">
    <?php print $sidebar_first; ?>
    <?php print $sidebar_second; ?>
  </aside>
<?php endif; ?>

So, clearly, my $sidebar_second variable is empty. I tried to render the block in a theme_preprocess_page function, adding the block to the $vars['page']['sidebar_second'] array, but no luck so far.

Any ideas?

Thanks,
Brett

If you need to assign block to region programmatically you can implement hook_block_info_alter

function YOURMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  if (isset($blocks['views']['name_of_view-name_of_view_display'])) {
    // assign block to region
    $blocks['views']['name_of_view-name_of_view_display']['region'] = 'sidebar_second';
  }
}


How to get rid of 'security updates available' warnings? I am using the ShareThis module on my website. Unfortunately, recent release 2.3 is flagged as a security update, but it is has a major bug (settings can't be saved). I have reverted to release 2.2.

The consequence is that 'security updates available' warnings are displayed all the time in administration screens. Is it possible to get rid of them? I tried to find an option, but could not find any.

I had a similar problem recently (see How do I avoid checking for updates for a specific module?) and managed to get around it using hook_update_projects_alter(). You can use it to easily remove any module that you don't want to be part of the update process:

function MYMODULE_update_projects_alter(&$projects) {
  $blacklist = array(
    'sharethis',
    // Any others you might want
  );

  foreach ($blacklist as $module) {
    unset($projects[$module]);
  }
}

As Drupal no longer considers any module you put in the $blacklist array as one that needs to be updated, you should stop getting the security warning.

It would probably be a good idea to keep an eye on the progress of the bug in the ShareThis module so that you can remove this restriction when possible.


Configuring Blocks and the use of wild cards Quite inexperienced in Drupal.
I want to place a Block in my site, but I want it hidden on Front Page, on any node and on any user page (except /user/login and /user/register and /user/password).
If I chose to “Hide for the listed pages”:
/node/
/user/*
*
The pages: /user/login and /user/register and /user/password will also be excluded

Is there a will card just for numbers? That would allow me to exclude the user profiles but not those 3 pages?

Regular expressions based matching is not yet supported on D8 block visibility patterns and wildcards. The best bet at this point is the following module:
https://www.drupal.org/project/block_visibility_groups

You can add multiple rules to show or hide blocks.


Suitable way to hide a paragraph entity I have read Hide an entity with hook_entity_view_alter(), and by all rights this code should hide every paragraph on a page:

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_paragraph_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $build['#access'] = false;
}

There are no errors, I know the function is being called because the debugger stops there on a breakpoint, I've cleared cache with every test.

I've tried hook_entity_view, hook_entity_view_alter, hook_ENTITY_TYPE_view and hook_ENTITY_TYPE_view_alter.

None of them have any effect whether I'm logged in or not.

['#access'] is not showing up in the build array in any of these hooks which makes me think the advice might be out of date since 8.4 dropped? If it does work - why should it work?

Are there any other ways, better ways of hiding paragraph entities (or any entity really)?

Obviously there will be some logic involved later which is why I want to do it in one of these hooks (or similar).

Edit 1: It has been suggested that there should be a $build['content'] array or similar. There is only the entity object in whichever hook I try of the four I have listed:


How to render only markup in region template? I have created a region--footer.html.twig template which only contains the static markup for the footer. Now I would like to render this region at the bottom of each page so I have added the following to the end of page.html.twig:

{{ page.footer }}

This works fine as long as I have connected a block to the footer region under admin/structure/block. If no blocks are placed in the region it is regardes as empty and is not rendered. How can I change so the region--footer.html.twig is used even if there is no blocks placed in the region?

I was thinking of using a preprocess function for the region doing something like this:

function template_preprocess_region(&$variables) {
  if ($variables['region'] == 'footer') {
    $variables['content'] = 1;
  }
}

/**
 * Implements hook_preprocess_page() for page.html.twig.
 */
 function hook_preprocess_page(array &$variables) {
   $variables['page']['footer'] = [     # Specify the region name
     '#theme_wrappers' => ['region'],
     '#region' => 'footer',             # Specify the region name
     'phantom_block' => [
       '#markup' => ' ',
       '#weight' => "-100",
     ],
   ];
 }

This way you are adding a block with a space to the region. Forcing Drupal to render that region. But as you will put a static HTML in that region, the content of the phantom block will not be rendered.


Permission to edit own unpublished content (only)? I have a content type Poll with an unpublished option. When a user creates a poll the poll remains unpublished for 1 hour and after that it becomes published (done with rules).

What i want to achieve is: Give the Poll author the permission to edit his poll node only while it is unpublished. When it gets published this permission will expire.

How can i work this out?

hook_node_access() to the rescue!  You need to create a new module to do this.  In the new module's .module file you'll need to put this:

function YOUR_MODULE_node_access($node, $op, $account) {
  // Deny updating the content if it's a published poll
  if ($node->type == 'poll' && $node->status && $op == 'update') {
    drupal_set_message('This poll has been published, you may not make changes to it.','error');
    return NODE_ACCESS_DENY;
  }
}


How to implement access permissions per individual field and individual nodes? I know there is https://www.drupal.org/project/field_permissions module, which allows to set field permissions per role, however what I need is to provide each individual field access permissions. As put on https://www.drupal.org/node/1376182

  It looks that there is no module allowing to restrict access to
  certain files / images per role. What I think about is having
  checkboxes beside each file/image where to select the roles to have
  view access to the according entry.

I can't believe this was not implemented before, so hopefully someone can point out a viable solution.

Edit: I've got couple responses confused about what I wanted, so I believe I have to elaborate little more.

Field Permissions set role permissions for the field across all the nodes. What I am looking for is role permissions for individual field PER NODE. For example, an admin for Drupal 7 site could edit node 1 and make the file attached to it viewable to role "subscriber", but that wouldn't change any permission for another file attached to node 2. I hope it is now clear.

Not sure if it is going to be the best/most elegant solution, but here is "an" approach that might work:

Use the Entity reference module to replace your file field in your existing content type with a reference to some other content type (say Resource).
Attach your files to nodes of content type Resource (so not in your already existing content type nodes).
Use the Content Access module to implement the refined access that you are looking for, but applied to that Resource content type.
Create some testcase(s) to verify how that refenced Resource node is going to be shown in your original nodes.

Get the idea? Pretty basic Drupal techniques (to KeepItSuperSimple, aka KISS).

I haven't tested it (yet) while writing this answer, but I bet functionally it will behave exactly as what you'd want. And guess what: no need for the field permissions module to make this work.

FYI: the above is a D7-equivalent of how I used to create such kinds of related content in D6 already (also using the Content Access module, and I believe in D6 it was "node reference" or something like that).


Adding CCK fields to Simplenews email newsletter I am designing a newsletter using Simplenews, however I need to add a couple of additional CCK fields to each node included in the newsletter. Seeing as the template file the email newsletter uses (simplenews-newsletter-body.tpl.php) simply uses a $body variable to output content, where would I instruct simplenews to add my additional CCK fields to each of the nodes I am sending?

Try this - it's pretty in deoth on what files and variables you can use with simplenews and cck in Drupal 6: http://drupal.org/node/268404


Is responsive.desktop.css for desktop & laptops design? I am also using the Adaptive theme and same question raised. I checked their documentation, but they do not have point to point instruction.

Its css file has following file,

global.base.css
global.styles.css
responsive.custom.css

1. responsive.desktop.css
2. responsive.smalltouch.landscape.css
3. responsive.smalltouch.portrait.css
4. responsive.tablet.landscape.css
5. responsive.tablet.portrait.css

So, if we see that five different screen size listed in adaptive theme as above, Do we have to use response.desktop.css for desktop/laptop design or just global.style.css?
Another thing when we see the adaptive theme setting at admin/apperance/ATthem(sub)/setting.....we see three option Standard Layout, Tablet Layout and smalltouch layout....So Tablet and Smalltouch are understable, they have their own css which means last 4 files, but for standard it is responsive.desktop.css?

I'll quote from the adaptive theme documentation:

  Global styles always load.
  Responsive styles load in media queries.

So, you don't need to use responsive.desktop.css if you can declare all your styles in global.style.css. This is most probably the case if you don't follow the "mobile first" approach. But if you do, you probably have additional styles for devices larger than tablets, and that's when responsive.desktop.css comes into play. And of course this is also for laptops. It's the screen size that defines this, not the "wording"...

  Global Stylesheets

  These load by default. Using a mobile first approach you would only
  place styles that are going to be used for all devices. You need to be
  ruthless about this and cut down on what is going into these files -
  its very easy to assume you will use this or that everwhere, but in
  reality you are merely falling into the familiar routine of desktop
  first theming. On your average site these files will be rather small.
  If they start getting really big, and if you find yourself overriding
  stuff later in the responsive sheets - then you know you have a
  problem and need to re-think what you are doing.

[...]

  Responsive Stylesheets

  Adaptivetheme provides five responsive stylesheets - one for each
  breakpoint set in your theme settings. During development (see sidebar
  Development and Production Modes) each of these files is loaded in a
  link element and places the media query inside the link element
  itself, as opposed to inside the actual file as an @media declaration.
  The media queries are those you set in the Appearance settings for
  each device type. Adaptivetheme automatically uses these so your
  styles will match to your layout breakpoints.

And do not forget about this setting in the theme settings (css):

  Mobile First or Desktop First Adaptivetheme supports both mobile first and desktop first design approaches. This setting fundementally
  alters what CSS is loaded and how it is loaded. At the most basic
  level if you select Mobile first the Smartphone portrait layout will
  load as the default, if you select Desktop first the Standard layout
  will load as the default. Many other changes take place regarding
  loading of CSS for Internet Explorer, Responsive Gpanels and Panels as
  well.


How to redirect form to a url having wild card character in drupal? How to redirect form to a url having wild card character in drupal? For example, can I do like this below shown?

$form_state['redirect'] = 'admin/component/%/edit'

or any other alternative approach to do like this?

You cannot do this in a form because the redirect has to be definitive. You much know the variable being put into the % via some means.


How do I get the path for the private filesystem? I just trying to get the real path of my private filesystem but I just obtain an empty string if I use:

\Drupal::service('file_system')->realpath("private://");

There one user in Get the public path directory that says that this is the correct way, but this is not working for me.

My private filesystem is configured as:

$settings['file_private_path'] = '/User/adriancid/private-drupal-folder';

If I use file_default_scheme() I see:

  private

The problem is solved.

I had a problem with the path, so the correct path is

$settings['file_private_path'] = '/Users/adriancid/private-drupal-folder';

And I give permissions to write in the folder to the webserver.


Using Grunt.js with Drupal I'm in need of an organization system for my JavaScript code Drupal. Currently, I've got it inside a folder in my theme's directory: "sites/all/themes/mytheme/js". I've looked at using Grunt.js, and wondering how I might implement it into my website. How would it help me?

Can it help organize large JavaScript files?

Could it help improve the speed of my website?

I started using Grunt.js by reading their easy to follow tutorial. Then, I created a Gruntfile.js inside of my theme’s js directory “sites/all/themes/mytheme/js/Gruntfile.js”:

  module.exports = function(grunt) {
    grunt.initConfig({
       pkg: grunt.file.readJSON('package.json'),
       concat: {
          main: {
             src: [
                'src/*.js',
             ],
             dest: 'production.js'
          }
       },
       uglify: {
          build: {
             files: {
                'production.min.js': 'production.js',
             }
          }
       },
       jshint: {
          files: ['Gruntfile.js', 'src/*.js'],
          options: {
             globals: {
                jQuery: true,
                console: true,
                module: true,
                document: true
             }
          }
       },
       watch: {
          files: ['src/*.js'],
          tasks: ['concat', 'jshint', 'uglify']
       }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-qunit');

    grunt.registerTask('test', ['concat', 'jshint']);
    grunt.registerTask('default', ['concat', 'jshint', 'uglify']);
  };

My Gruntfile does 3 things for me (right now):

Combines smaller, more manageable files inside src/ into one file.
Checks for errors in my compiled file.
Compresses my file when I’m ready for production.

All I have to do is run grunt watch from the terminal and whenever one of the files inside src/ is changed my production.js file is updated and compressed. When I’m all done debugging I just change the following in my .info file:

scripts[] = js/production[.min].js

This results in faster page loads because only one (smaller) request is being performed as opposed to many uncompressed file requests.


How do I check login? I have a php file in my Drupal 8 module.The name of my custom module is fb. Within the fb folder I have a php file fb.php .The content of that file is loaded as an iframe using the follwing code
  public function buildForm(array $form, FormStateInterface $form_state) {
  $extpath = take_control_fb_ext_client_path();
  $fbpath = take_control_client_path(drupal_get_path('module', 'fb') . '/fb.php?extpath=' . $extpath);
  global $base_url;
  $form['#attached']['take_Control_fb']['library'][] = 'fb/fb';
      $form = array(
      'take_control_fb_container' => [
    '#type' => 'inline_template',
    '#template' => '',
    '#context' => [
      'url' => '/modules/fb/fb.php?extpath=/libraries/extjs/ext-3.4.1'
  ],
],
  );
return $form;
  }

.I need to check drupal login is set or not in the fb.php file.  I have used the following code to check that

$logged_in = \Drupal::currentUser()->isAuthenticated();

Ref link : https://docs.acquia.com/articles/there-drupal-function-check-if-user-logged

But it resulted the error 'PHP Fatal error:  Class 'Drupal' not found'.

Please help me to figure out some solution to fix this.

The correct approach for this would be to implement a service, in which you put the contents of the fb.php and there all the Drupal functions will be recognized.
Here is an example of a service implementation: https://docs.acquia.com/articles/drupal-8-services-dependency-injection-and-service-containers


display just the label from node_lode() How to display just the label from the object returned by the function
node_load().
the field_view_field() can hide the label and view the value
but i want the converse.

If you want to find the label for a specific field then you can use field_info_instance()

https://api.drupal.org/api/drupal/modules!field!field.info.inc/function/field_info_instance/7

<?php
$field_instance = field_info_instance('node', 'field_body', 'article');
$label = $field_instance['label'];
?>

However, the titles are available in the rendered node if they are not hidden in your view mode, and can accessed like :

<?php
$node  = node_view(node_load($nid));
$label = $node['field_body']['#title'];
?>


How can I add items to the Admin Toolbar? In Drupal 8, I want to add a menu item to the Admin Toolbar with a submenu, with different links.

How can I do it?

You can add items to the admin toolbar in two ways:

As content:

In ui /admin/structure/menu/manage/admin

or in code:

$item = \Drupal\menu_link_content\Entity\MenuLinkContent::create([
  'link' => ['uri' => 'internal:/<front>'],
  'title' => 'Front Page',
  'menu_name' => 'admin',
]);
$item->save();

Or in static configuration files:

system.admin:
  title: Administration
  route_name: system.admin
  weight: 9
  menu_name: admin
system.admin_content:
  title: Content
  description: 'Find and manage content.'
  route_name: system.admin_content
  parent: system.admin
  weight: -10
system.admin_structure:
  route_name: system.admin_structure
  parent: system.admin
  description: 'Administer blocks, content types, menus, etc.'
  title: Structure
  weight: -8
system.themes_page:
  route_name: system.themes_page
  title: Appearance
  description: 'Select and configure themes.'
  parent: system.admin
  weight: -6

This is the start of system.links.menu.yml, which defines the admin menu as we know it from D8. You can add your own entries in mymodule.links.menu.yml.

Edit:

To add an item to the top row, use the hook mymodule_toolbar(). This is an example from the tour module:

/**
 * Implements hook_toolbar().
 */
function tour_toolbar() {
  $items = [];
  $items['tour'] = [
    '#cache' => [
      'contexts' => [
        'user.permissions',
      ],
    ],
  ];

  if (!\Drupal::currentUser()->hasPermission('access tour')) {
    return $items;
  }

  $items['tour'] += array(
    '#type' => 'toolbar_item',
    'tab' => array(
      '#type' => 'html_tag',
      '#tag' => 'button',
      '#value' => t('Tour'),
      '#attributes' => array(
        'class' => array('toolbar-icon', 'toolbar-icon-help'),
        'aria-pressed' => 'false',
      ),
    ),
    '#wrapper_attributes' => array(
      'class' => array('tour-toolbar-tab', 'hidden'),
      'id' => 'toolbar-tab-tour',
    ),
    '#attached' => array(
      'library' => array(
        'tour/tour',
      ),
    ),
  );
 return $items;
}


Call to undefined function entity_create() i try to include a node creation form by a field attach form. So i try to load the entity of a custom content type created by the back-office with is called 'friterie'. But when i call the entity_create function i get this error : Call to undefined function entity_create()

Here is my code :

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

    // INCLUDE FRITERIE ADD FORM
    $form['friterie'] = array();
    //module_load_include('inc', 'node', 'node.pages'); this is an old method
    //$form['friterie'] = node_add('friterie');
    global $language;
    $entity = entity_create('node', array('type' => 'friterie', 'language' => $language->language));
    //$form['friterie'] = field_attach_form('node', $entity, $form['friterie'], $form_state);

    // INCLUDE USER REGISTER FORM
    //$form['user'] = drupal_get_form('user_register_form');

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Enregistrer la friterie'),
    );

    dsm($form);
    return $form;
}

I don't know why i get this error, i watch on the official documentation and it says i can do it like i did :/

As Gulok said, check if the module entity is installed and enabled.

Be sure to add entity as a depencencie in your .info file as well.


How to use hook_views_query_alter to add field with no table in Drupal 7 Views 3 I am new to Drupal 7/Views 3 hooks. I am trying to approximate this query:

SELECT *, 3956 * 2 * ASIN(SQRT(POWER(SIN(($postcode_lat - abs(lat))*pi()/180/2),2) + COS($postcode_lat * pi()/180) * COS(abs(lat) * pi()/180) * POWER(SIN(($postcode_lng - lng) * pi()/180/2),2))) AS distance
WHERE distance < 500
ORDER BY distance ASC

This gives a list of locations sorted by distance. However, in trying to implement with hooks, I am struggling. Here is the code that I tried:

$query->addField('', '3956 * 2 * ASIN(SQRT(POWER(SIN((32.7828 - abs(29.7631))*pi()/180/2),2) + COS(32.7828 * pi()/180) * COS(abs(29.7631) * pi()/180) * POWER(SIN((96.8039 - 95.2665) * pi()/180/2),2)))', 'distance');

Drupal doesn't like the empty parameter for table. But how can I add a field with no table?

I appreciate any suggestions offered.

I had the same problem. And I've solved it.

    function ModuleName_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view' && 'my_block_name' == $view->current_display)) {

    $formula = "3956 * 2 * ASIN(SQRT(POWER(SIN(($postcode_lat - abs(lat))*pi()/180/2),2) + COS($postcode_lat * pi()/180) * COS(abs(lat) * pi()/180) * POWER(SIN(($postcode_lng - lng) * pi()/180/2),2)))";

    // Sets the formula's alias.
    $query->add_field(NULL, $formula, 'distance');
    $query->add_where(0, "$formula < 500", array(), 'formula');

    // Sets the order by reference
    $query->orderby = array(
      array(
        'field' => 'distance',
        'direction' => 'ASC',
      )
    );
  }
}

See http://roldanarts.com/2013/11/22/diego-f-roldan/blog/using-formulas-views-hook-views-query-alter for more details.


What's $mask in file_scan_directory() to find all png files? I try to find all png files in a directory inside my module using this code with no success:

$banks = file_scan_directory(drupal_get_path('module', 'order').'/images/gateways', '/^.*\png$/');

What mask should I used for getting all png files?

The following mask should work for you:

'/.*\.png$/'


How i can add new fancybox-style (theme) for display uploaded image in WYSIWYG / CKEditor with Media module? When I upload new image with Media Browser (WYSIWYG + CKEditor + Media), I see themes: original, small, large... How i can add my own template to this list for fancybox?

Maybe already have a module for this theme?

Go to configuration, media, image,styles, add style, or directly

http://example.com/admin/config/media/image-styles/add

And add a custom image style.


Display a node form in default theme for admin I think this question has been asked many times, but I am sorry not to find a working solution. May be I am doing something wrong. I want to display a specific node form in my default custom theme and not in the admin theme when the administrator logs in. However, other node forms should continue to display in the admin theme. Hence the "Use the administration theme when editing or creating content " should be checked.

I have tried the themekey module. I came across that there's something called themekey compatibility by which this can be achieved. But I fail to find an example.

I want the default theme for a specific content type. Also I tried the followings: hook_custom_theme & hook_theme_init as described in How to change the theme for a particular admin page in drupal?

Thanks

There is a hook that you can use to set which pages use the admin theme and which don't.

The hook is hook_admin_paths().

The node module uses this hook to provide the functionaity where you can set node forms to use the admin theme (see node_admin_paths()).

If you wanted to set certain paths to use the admin them (or not use it) you could implement that hook, however if you want to change admin paths that another module has already defined you need to use hook_admin_paths_alter().

In this case the node module defines a wild card path for all node add pages like this 'node/add/*' => TRUE

Since you only care about a specific node type you can ignore that and do this:

/**
 * Implements hook_admin_paths().
 */
function MODULENAME_admin_paths() {
  // We have configured the site to use the admin theme for node forms
  // however we want the article content type to use the default theme
  // instead of the admin theme.
  $paths = array(
    'node/add/article' => FALSE,
  );
  return $paths;
}

As you can see in path_is_admin(), where the check is done to see if the current page is an admin page, for a page to be an admin page it must have a matching path that is TRUE and also not have one that is FALSE.
So by adding this FALSE in for this specific page you are overriding the wildcard node/add/* from the node module.

The problem that you then have is the node edit page (if you also want that to use the same theme as the node add form), because the URL for the node edit page has nothing in it that relates to the content type so you can't override node edit pages based on their type.

You could get the node IDs of all nodes of your specific type and add each individual node edit path however if you have a large number of nodes that is not going to be ideal.


Site broken after update I am building a drupal 8 site and I am keeping my code on git.
I am using a copy of example.gitignore as my .gitignore which exclude vendor folder.
I have been working on my sandbox, at some point I have update drupal core from version 8.1.1 to version 8.1.3 and push it to git.

I have created a new sandbox, pulled code from git and system throw few errors because vendor folder wasn't there so I run composer install. Even then, I still had errors. I run composer update and I had errors again.

What is the right procedure in order to keep drupal 8 on git and at the same time not having problem with vendor folder?

If you download drupal 8 from drupal.org it contains vendor folder, should I keep vendor folder on git?

Thanks in advance.

I strongly recommend you (as a current best practice), to use Drupal8 Composer project

In this case, the root folder is going to contain "web" and "vendor" directories, so you will have to set your apache/nginix vhost for looking the index.php for one directory deeper.


Drupal Commerce assign role on account create on checkout When a checkout is completed by an anonymous user on a Drupal Commerce website, a Drupal account will be created. I would look to auto-assign a role like 'customer' to the newly created Commerce user. How can I do that programmatically? It has to be in Drupal 7 code so I can use it for my custom module.

$account = new stdClass;
$account->is_new = TRUE; //indicate the account is new
$account->name = 'account_name';
$account->pass = user_hash_password('password'); // make a function to create random passwords
$account->mail = 'email';
$account->init = 'email';
$account->status = TRUE; //set the user to activated at creation
$account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE); //set user as authenticated user
$account->timezone = variable_get('date_default_timezone', '');
$new_user = user_save($account); //create user (user_save() returns a fully loaded $user object)

$role_name = 'ROLE_NAME'; // The name of the role to add.
if ($role = user_role_load_by_name($role_name)) {
  user_multiple_role_edit(array($new_user->uid), 'add_role', $role->rid);
}

You can use the hook: hook_user_insert.
And apply the last piece of code from above to update the role.


Image Responsive Carousel like image Gallery I have created a view of images and I want to display those images in a carousel like display but that needs to be responsive. I came across a jquery plugin for this called "elastislide" but cannot properly figure out how to use it with drupal views I have followed the example here, but nothing is working as such.

If you want a fairly simple responsive carousel in views I would recommend checking out Flexslider - it's pretty simple to setup and does everything you want I believe.


Boost Security_review compatibility I had security_review warning for boost cache folder.

I've changed cache folder location to "sites/default/files/cache"

And now I have no warning.

Is this solution correct and safe?

From the point of view of the Boost module, it should be safe as well. Make sure you also regenerate the .htaccess for your site.


Why is hook_node_access($node, $op, $account) called with $op equal to "create"? I am using the function mymodule_node_access($node, $op, $account) to intercept the operation of creating a new node type "article" by the user Advertiser.

I created a new user "Advertiser"
The new user "Advertiser" has all permissions enabled on the node type "article"
The user "Advertiser" can use the admin bar
I created a custom module to control access to the node by the user "Advertiser"
In mymodule_node_access($node, $op, $account), I displays the values of $node and $op

When the user logs into the system, the function mymodule_node_access($node, $op, $account) displays:

  Type of node: article Operation: create

Why does that happen?

The user "Advetiser" has not yet created a new node type article.

Besides, if I disable the use of the admin bar by the user "Advertiser", the situation does not occur.

How can I fix?

The admin menu contains links to create new content, and menu items also go through an access check to make sure the current user has access to the path. If they don't, the menu item is hidden.

The access callback for the path node/add/* is node_access(), which invokes hook_node_access(), which is why your access hook is being invoked when the admin menu is present.

You can either remove the admin menu altogether, or remove the links to create new content from it and your hook won't be invoked any more.


Change #default_value of a textarea on admin pages I need to change specific textarea max-length (currently 100 letters).

Where is the default value stored or how it is possible to override this setting?

The teaxtarea form field doesn't have any property for the maximum length of the accepted text. The module showing the textarea can implement a form validation handler to limit the length of the entered value, and (generally speaking) that limit is not saved in a module settings; it is generally hard-coded.

In the case the value contained in the textarea field is saved in a database table created from the module showing the form, there is another issue: The value contained in the textarea field must be contained in the database field. If it is longer than what the database field can store, you would get SQL errors.


filter homepage content based on term id I have two pages "homepage" and "countries", the default behavior is that when a visitor first visit my homepage all content is gathered regardless of the country.

But if the user went to the countries page, which is a view that's getting term ids from a taxonomy list, and selects a country, he/she will get redirected to the homepage and the homepage content will get filtered to the term id the person chose from the countries page.

I think I should be using contextual filters, but I'm confused right now.

my question is how can I do this filter on homepage based on a term clicked from another view.

any help will be greatly appreciated with hot cookies.

Okay, now i understand your problem!

When a user clicks on a link in the "countries" page, he will see the standard taxonomy term "view". But i guess you want him to see your normal "homepage" BUT with filtered content.

You have two options:

Alter the taxonomy term page.
Use contextual filter on the "homepage" and change the links on the "countries" page according to use the filter.

In my opinion you should clearly prefer option two. Also have a look at the view "Glossary", which should be included, but not activated out of the box, this should help you a lot in configuration!


Entity query returns wrong NID I have the following query:

$query = \Drupal::entityQuery('node')->condition('type','article');
$result = $query->execute();

Then I want to access all content:

$nodes = \Drupal\node\Entity\Node::loadMultiple(array_keys($result));

But in variable $results, there are wrong NIDs. My first article ID is '12' and second article '13'. But in $result are '9' and '10'

Do you have an explanation for this?

Ok, I found out I can't use array_keys... because keys are not same as IDs. Proved just now in an easy example... in my $result[9] there is the right id '12'.

The return value of Query::execute,

  int|array Returns an integer for count queries or an array of ids. The
  values of the array are always entity ids. The keys will be revision
  ids if the entity supports revision and entity ids if not.

Nodes support revisions so the keys will be revision ids and not entity ids.

$nodes = \Drupal\node\Entity\Node::loadMultiple(array_values($result));


Possible to customize the look/length of CKEditor Styles dropdown? I've added custom styles to the Styles dropdown in CKEditor included by default in Drupal 8. They work fine. However, the dropdown isn't convenient for editors to use because

It isn't tall enough
There's a lot of vertical spacing between items
Items have the style they represent, taking even more space

Here's a snip of my default Styles dropdown:

It's fine that the items have the style they represent, except it can take a lot of space in the very small box, especially if the font is large. Plus there's lots of vertical spacing between items.

I've figured a [hackish] way to keep the items from taking on their represented style, producing this:

But it's still too short with a lot of space between items, so only four styles of 20 show.

QUESTION:

Is there a way to customize the look of the Styles dropdown, or at least to make it longer? Lots of reading of posts and documentation hasn't provided an answer, if there is one.

After a good bit of trial and error (I'm slow, but persistent), I've figured out the classes to modify the height and item styles in the CKEditor Styles dropdown. Here's an example using values that work for me:

div.cke_combopanel {
  height: 300px !important;
}
li.cke_panel_listItem a {
  padding: 3px 5px !important;
  font-size: .8em !important;
}

The div and li prefixes aren't required; I've included them here simply to identify the element types involved. Setting a fixed height for cke_combopanel is an imperfect solution, but better than the short one I get by default.


Render commerce item page with views - how to get proper add to cart form? I use Drupal Commerce module to build my store. There are items in this store with sets of attributes such a color, size etc. I've created a content type to render a product. When I use a built in way to render this content type I have an interactive add to cart form with select lists or radio buttons for all attributes which loads values such a photo etc depend on it's values. Please suggest an approach how can I get this form using views?

I guess it should be quite a common task.

Create a View of your content.

Add field "Commerce Product: Add to Cart Form" to your View.


how to give read more link in a block? I have a views block which display user's detail like name, picture and about.
i want to give a read more link in "about" field, by click "read more" link the trimmed "about" will open in the same block.

"About" is a field from view, so in this field text will trim after 200 words if the about field is more then 200 words then after trimmed part there will be a read more link and after clicking this link the whole text will visible on the same position just increase the height of the block.

Thanks

jQuery expander module will work for you.

You will have to select expander from formater options in views field configuration.


Add a JS app in Acquia root domain folder I have a decoupled app, both backend and frontend parts, and I want to add them to Acquia cloud. Right now the js app is placed in a subfolder in drupal's docroot folder.
What I need is to have the JS app in the domain's root folder and have Drupal instance in a subdomain or subfolder. Is this possible? Thanks.

is your frontend an Angular / React / Vue app?
Anyway I don't know Acquia cloud but I can confirm that your setup works on an Apache server. I have my Angular app in the root folder along with the vendor and and web folders, and then I have in the web folder the core, libraries, modules eccc.. folders.


How to grant permission to FileSystem.php file I navigate to admin/config/media/file-system in the drupal admin interface. I get this error

  Warning: mkdir(): Permission denied in Drupal\Core\File\FileSystem->mkdirCall() (line 244 of core/lib/Drupal/Core/File/FileSystem.php) .

I granted the permission to sites folder using the following commands chown -R www-data:www-data sites and chmod -R g+rw sites.
But still the error appears.

Any advice?

First of all make sure that the files directory (sites/default/files by default) has the right owner and permissions.
And also directory of temporary files, in general /tmp if you don't have create one and give it the right permissions.


How do I setup the date picker popup for date fields in a view? I setup a date field for my content type and also have an exposed date filter for my view, but I can't seem to figure out how to get the date picker popup to show up. Is there a setting that I have to set somewhere?

I've also installed Better Exposed Filters and I still don't see any option for my view. Also installed Date and the Calendar module. I know jQuery UI has a built in calendar popup and that's installed by default on Drupal 8 installs.

How do I turn this on?

This is usually because the ui.datepicker wasn't added as a dependency in your theme as this isn't usually enabled by default in themes.

I use the seven theme for administration, so I had to add the line:

  - core/jquery.ui.datepicker

Looks like this in my seven.libraries.yml file:


Is there a way to pass a PHP value to JavaScript? I have a link generated within a JavaScript file that contains the following code:

jQuery(".url").append('');

I would like to alter the path variables when user is not logged. In Drupal terms this would look like: global $user; if (user->uid == 0) {..redirect page.} or global $user; return !(bool) $user->uid;

How can I use the $user->uid property with JavaScript code?

You're looking for drupal_add_js(). You can use it to pass data from PHP to JavaScript. Something like the following should suffice:

/**
 * Implementation of hook_init().
 */
function modulename_init() {
  if (!user_is_logged_in()) {
    drupal_add_js(array(
      'modulename' => array(
        'path' => $logged_out_path
      )
    ), 'setting');
  }
}

Note that I am calling this from within an implementation of hook_init(), but really you can do this anywhere, be it from a module or a theme. Also note that I have provided a sufficient namespace for the value to live (i.e. within 'modulename' => 'path'). This will make it clear from JavaScript's point of view exactly who owns the variable (i.e. which module it came from), but more importantly will help to prevent collisions with settings in other modules.

From JavaScript you can access the value of $logged_out_path like this:

var path = Drupal.settings.modulename.path;


Add comments via REST I am using waterwheel-swift to connect my iOS app to Drupal 8. Logging-in and node posting/editing work great, but when I try to post a comment, I get a 400 error.

I am using the following code.

    let body = [
        "entity_type": [
            [
                "value": "node"
            ]
        ],
        "entity_id": [
            [
                "target_id": self.nodeID
            ]
        ],
        "field_name": [
            [
                "value": "field_x"
            ]
        ],
        "comment_body": [
            [
                "value": "How are you?"
            ]
        ]
    ]

    waterwheel.entityPost(entityType: .Comment, params: body as paramType) { (success, response, json, error) in
        if (success) {
            print(response)
        } else {
            print(error)
        }
    }

I get the following error:

  Error Domain=Alamofire.AFError Code=3 "Response status code was unacceptable: 400."

rest.resource.entity.comment config is the following.

  langcode: en
  status: true
  dependencies:
    module:
      - basic_auth
      - comment
      - csv_serialization
      - hal
      - serialization
      - user
  id: entity.comment
  plugin_id: 'entity:comment'
  granularity: method
  configuration:
    GET:
      supported_formats:
        - csv
        - hal_json
        - json
        - xml
      supported_auth:
        - basic_auth
        - cookie
    POST:
      supported_formats:
        - csv
        - hal_json
        - json
        - xml
      supported_auth:
        - basic_auth
        - cookie
    DELETE:
      supported_formats:
        - csv
        - hal_json
        - json
        - xml
      supported_auth:
        - basic_auth
        - cookie
    PATCH:
      supported_formats:
        - csv
        - hal_json
        - json
        - xml
      supported_auth:
        - basic_auth
        - cookie

Please point out if something is wrong with my code.

Got it resolved, the problem was, i was not passing the parameter comment type. Made the following changes to body parameter and it now works.

let body = [
        "entity_type": [
            [
                "value": "node"
            ]
        ],
        "entity_id": [
            [
                "target_id": self.nodeID
            ]
        ],
        "field_name": [
            [
                "value": "comment_x",  // Machine name of the field on the node
                "format": "no_html"
            ]
        ],
        "comment_body": [
            [
                "value": "How are you?"
            ]
        ],
        "comment_type": [
            [
                "target_id": "comment_x"  // Machine name of the comment bundle
            ]
        ],
        "uid": [
            [
                "target_id": self.UID
            ]
        ],
    ]


"View recent blog entries" only showing on admin's page but other users have blogs "View recent blog entries" only showing on admin's page:

http://www.effectiveanimalactivism.org/user/1

But other users also have blogs:
user/5
and /user/10

that don't show up on their user pages.

In the permissions page (under 'People' in Drupal 7), 'create new content' has to be checked for the users.


Deploying to live and available modules In Drupal 8 you can export configuration and move that to a production server. In core.extensions.yml there is an exported list of the enabled modules. If on development I have devel and other auxiliary modules installed these are added in that file but I do not want that to be part of the production environment.

Is there a switch to do that? How can master module from Drupal 7 replicated here?

I think there is not really a good option for this yet.

It's tricky, because you can't just override the config and have those modules enabled since they also provide their config (which would and install/uninstall processes that can't be skipped. In fact, providing config overrides for core.extension is explicitly prevented.

Maybe someone will come up with a good way to do this, I currently don't really know how that should work.


Administrator role missing I have installed Drupal 8.6.3 minimum profile and found out that there's no Administrator role under permissions section. Is this normal or am I missing something?

We have few people that needs to be using Admin roles, so without a Administrator role, I can't assign them to such a role.

Yes, that is expected, since the Minimal profile creates less entities than the Standard profile. You can see that by comparing the config/install directory in the first profile with the config/install directory in the latter profile.

As per creating the role from the user interface, that would be possible, but the created role would be a role like the others, while the Administrator role created from the Standard profile automatically gets all the permissions defined in a Drupal site. In fact, Role::hasPermission() uses the following code.

  if ($this->isAdmin()) {
    return TRUE;
  }
  return in_array($permission, $this->permissions);

For the Administrator role, $this->isAdmin() always return TRUE; for every role you create from the user interface, $this->isAdmin() would return FALSE.

If you need that role, and you cannot reinstall Drupal using the Standard profile, you can create a custom module, for which you create a config/optional/user.role.administrator.yml file with the following content.

langcode: en
status: true
dependencies:
  enforced:
    module:
      - yourmodule
id: administrator
label: Administrator
weight: 2
is_admin: true
permissions: {  }

(Replace yourmodule with the module name.)

When the module is installed, the role will be created. Since the file contains is_admin: true, the role will have all the permissions, automatically, like the Administrator role created by the Standard profile.

The alternative method that doesn't involve writing modules is importing the user.role.administrator.yml file in the site. The content of the file is similar to the content of the file I previously suggested, with the exception that there aren't dependencies.

langcode: en
status: true
dependencies: {  }
id: administrator
label: Administrator
weight: 2
is_admin: true
permissions: {  }

I would use the custom module method if there are other entities/bundles that you normally create when installing Drupal for a new site.
If instead you don't have the need to create other entities/bundles, importing a single file is quicker.

If you installed Drush, with drush config-edit user.role.administrator you can edit that file and set is_admin to true.


customer commerce profile = user profile is it possible to get all registered users into commerce profiles? /admin/commerce/customer-profiles

I mean when I create an account for user drupal will automatically create a commerce profile

You've got some ways to do this, I'd look first to Commerce Extra module which allows you to have an address in the user entity and prepopulate information in the commerce checkout with this.

If you want to actually duplicate the information and have a customer profile entity for each user registered, you can use Rules module for this (it is required by Commerce), you can then create a new rule, for instance in the "After saving a new user account" event that triggers an action "Create a new entity" of type commerce customer profile and then another action, "Save entity".
You can check Drupal commerce default rule "Create a new account for an anonymous order" for a similar concept.


Only user number 1 can add content Recently all users (except UID 1) lost the ability to add content.

When going to node/add we get the message "no content types created yet"

When going to node/add/page we get "Access Denied, you are not authorized to access this page"

There are people having similar issues like here - https://www.drupal.org/node/1073994

I have already checked the navigation menu to see if that was the issue, since it seems to be a known bug, but this was not the case. All the permissions are set correctly in the permissions UI and database too.

I am not sure if this is relevant, but the site was migrated from 6 to 7

Any insights would be appreciated!

This is indeed most likely an access issue. However, I don't think it's something with Apache Solr but more with some of the additional modules you might have enabled. Can you list them with the versions here?

Also, as mentioned above, disable apachesolr access and rebuild your permissions. Check if it is still the case?


How do I add the noscript tag? I've a drupal 8 website, where in every page, I would like to add a noscript tag for every script tag. In drupal 8, in html.html.twig, I saw the scripts variable in missing. So how do I do that in Drupal 8?

You can do it in a custom module (MYMODULE.module):

use Drupal\Core\Render\Markup;

function MYMODULE_page_attachments(array &$page) {
  $fallback = '<link href="fallback.css" rel="stylesheet" />';
  $noscript = array(
    '#tag' => 'noscript',
    '#value' => Markup::create($fallback),
  );
  $page['#attached']['html_head'][] = [$noscript, 'mymodule'];
}


Email sending doesn't work through Webform I'm trying to get drupal webform to send confirmation emails to logged in users after they validated a booking form. (Windows and IIS Server)

I monitored Drupal Log reports/dblog and got this:

Notice : Undefined index: und in eval() (line 22 in   C:\.....\modules\php\php.module(80) : eval()'d code)

Also, after submitting the booking form it gives this error: Impossible to send mails, please contact administrator if problem persists.

And to add, generally Mail sending works when tryin to reset my admin password.

Apparently I'm not the only one with this problem.

It appears you're running your site on Windows. Either IIS or Apache?

Sending mail on windows based servers is a bit different. It cannot used php's normal method for sending mail if it were on a linux server.

You must configure an SMTP server in either your PHP.ini, or leverage the SMTP Auth module and connect to an SMTP server.

PHP.ini setup:

http://www.quackit.com/php/tutorial/php_mail_configuration.cfm
https://stackoverflow.com/questions/112190/php-ini-smtp-how-do-you-pass-username-password


I need to use hooks without using theme and module I'm in a project that needs to add features to Drupal Core without using themes niether modules.

I have implemented a class that makes different things, but I need to use hooks or something similar. Maybe I'm mistaken, but hooks must be implemented throught a module or a theme. Can I do this kind of paranoia?

Thanks!!

Yes, hooks must be implemented in a module or theme.

The only other options would be:

Hack at the core functionality until it does what you want. This is bad for many reasons.
Use the PHP filter module, and hope that it's compatible with the place(s) you need to inject your custom code. This is even worse than the first method.

Moral of the story:

Drupal provides hooks in themes and/or modules to extend its functionality.

If you need to extend Drupal's functionalality, use hooks in themes and/or modules.


How can i add multiple instances of newsletter subscriptions? I want to display newsletter subscribe in different pages, in different ways. Hence once I have set newsletter : subscribe to home page, it does not apply to other page by default.

How can I can assign it to different pages in different positions?

Each block can be configured in different ways. You can by default give different paths to show or not show your block. Go to /admin/structure/blocks and click on "configure".

If you need more advanced settings, then have a look at the Context module. This allows you to define all kind of rules and conditions to show a block. Very powerfull.


Checking if module has the right output on multilingual pages with simpletest_clone I'm trying with simpletest_clone to check if my modules have the right output depending on the language.

Now my problem is, that when I do the following Code:

$this->drupalGet('de');
// check the output

$this->drupalGet('fr');
// check the output again for the french version

Drupal then checks for localhost/de/de and localhost/de/fr (de is the default language) instead of localhost/de and localhost/fr

How can I change that behaviour?

I would set the default langauge in code first instead.

// Get the list of languages
$languages = language_list();

// Set up the new language code
$new_lang_code = 'fr';

// Make sure the required language object is actually set
if (isset($languages[$new_lang_code])) {
  // Overwrite the global language object
  global $language;
  $language = $languages[$new_lang_code];
}

and then you just need to get the front page (and Drupal should add the prefix).

$this->drupalGet('<front>');

If front doesn't work you might need

$front_url = variable_get('site_frontpage', 'node');
$this->drupalGet($front_url);


drupalgap webapp setup into subdomain My main website is www.example.com. And I have 3 types content like: book,food,tutorial.

Now I want to serve all Book item from book.example.com subdomain. Is it possible to develop it with drupalgap using example.com node/content and same authentication?

[After installing drupalgap module, I download web-app drupalgap zip file, and set it to book.example.com but, CORS problem detected.]

anyone help please.

solving cors problem I just add configuration into my .conf file.

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "Content-Type, X-CSRF-Token"


What privileges should a MySQL user have? When I am creating a user for my Drupal in cPanel, it asks me to check all privileges. What privileges should be enabled, to make Drupal work correctly?

Currently, my user has all privileges except Drop permission.

For development you'll need essentially everything - including drop. Once you go live, drop is generally not needed.

That said, if you're allowing delete - for instance - then drop isn't much more drastic. If someone owns your server, deleting all the rows from your tables is pretty much as bad as dropping a table - either way, the only good fallback is proper backups.

Setup your database user to only be allowed to connect from the host Drupal is running on. And make sure if that host has ssh allowed, you're using keys, and not just username/password, and you should be pretty good.


When not given a link, use URL node For a slideshow with banners, i've added the fields overlay-text and link-to. The link-to is the URL you go, if you click on the banner. It's al done & working in Views & Views Slideshow.

The user adds a node and has to set the URL by hand in the field link-to. Sometimes however, the banner has to point to a different URL or node.

How can i set the URL of the node when the field link-to is empty?

You can use No results behavior on the field. Include the path field and use the field path token.

If there are no results, it picks the node URL.


Are there terms to distinguish between the different levels of Drupal Core? "Core" seems to cover over a multitude of things, encompassing all the modules that ship with the Drupal code base.  But there seem to be levels of "core"-ness, and I'm wondering if there is official terminology to distinguish between these. For example:

There is the code that is not part of any module.  Does "core" include this officially?  It's not clear to me.
There are required modules: without these (at least in Drupal 7) you can't really build a Drupal site.
There are all the default modules that are part of Core.  You can turn many of these off without a problem, but they're still considered "core".
There are modules that are turned off by default (PHP Filter) and which may even be considered a bad practice to use under normal circumstances (PHP Filter, again).

If I were naming these levels, I might call them

The Drupal Kernel
Deep Core Modules
(Normal) Core Modules ("Core Modules" would include 2 and 4 as well)
Outer Core Modules

But it seems like Dries may have an official terminology already.  Is there such a thing?

I'm not aware of any official definition of the various levels.

I will however, referring to your suggestions, explain a bit about what levels there are.

The Drupal Kernel is actually a component in Drupal 8, which is a Symfony Kernel
"Deep Core Modules" could be the include files that are not even modules. Some files, for example database.inc, bootstrap.inc and module.inc are so fundamental that core cannot function without them. (There are some more .inc files however that reasonably could become modules, I don't know why they are not)
Core modules then, core parts that are written in the same style as contrib modules, but are still so fundamental that core wouldn't work without them. There's a system module that manages a lot of low level administrative functionality. The node module is (in D7) still required. Field sql storage cannot be turned of either.
Outer Core Modules, are all the other things that are shipped with core because they are commonly used, but not necessary for Drupal to function. The forum, taxonomy terms, the user interface for the field system etc.

Again, I'm not familiar with any official terminology, other than all of it being "Core". When people work on core, I only hear references to the individual "components" of core, as specific in the Drupal issue queue.

When I hear "actual core", I think of levels 1 - 3.


Adding Adsense on a CCK field First of all I'm using drupal 6.19.
I'm trying to add adsense on my site unsuccessfully. =/
I want to put my adsense on a CCK field but isn't working.
When I put the code on a block everything works fine. But in a CCK field I'm in trouble.
Both, block and CCK field, are set to input format FULL HTML.
I don't know why doesn't work in the CCK field. Can anyone help me?

Try stripping the line breaks. Like they should be all going in one line.