How do I programmatically change a system message? Hey there I want to change or hide a drupal message from the CommentForm class.

In my entity_insert() hook I set a new message.

I have an idea of how to do it but still no idea of where to do it.

idea:

  whether unset the $_SESSION['messages'] and set it with my message
  after I unset it.

  Or

  drupal_get_message($type, TRUE).

problem my message will be set before the one I want to exclude. So if I unset the message array my message will be gone, too.

So my Question is where to put those in myModule?

I also tried to hook in the specific form and add a submit handler but that doesn't work.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_comment_form_alter(&$form, FormStateInterface $form_state) {
  $form['actions']['submit']['#submit'][]  = 'my_module_comment_form_submit';
}

/**
 * Submit handler.
 */
function my_module_comment_form_submit(&$form, FormStateInterface $form_state) {
  $message = $_SESSION['messages'];
}

Ok I've figured it out.
But that solution is pretty ugly in my opinion.

I do this in a hook_preprocess.

/**
 * Implements hook_preprocess_HOOK().
 */
function my_module_preprocess_node(&$variables) {
  $user = Drupal::currentUser();
  $entity_id = $variables['attributes']['data-history-node-id'];
  $entity_type = $variables['elements']['comment']['#entity_type'];
  $bundle = $variables['elements']['comment']['#bundle'];
  $comment_type = FieldConfig::load($entity_type . '.' . $bundle . '.comment');
  $maxCommmentUser = $comment_type->getThirdPartySetting('my_module', 'edit-limit-per-user', FALSE) + 1;
  $limitUser = $comment_type->getThirdPartySetting('my_module', 'edit-limit-per-user', FALSE);
  $currentCommentUser = my_module_get_user($entity_id);
  $maxCommentNode = $comment_type->getThirdPartySetting('my_module', 'edit-limit-per-node', FALSE) + 1;
  $limitNode = $comment_type->getThirdPartySetting('my_module', 'edit-limit-per-node', FALSE);
  $currentCommentNode = my_module_get_node($entity_id);
  if ($maxCommentNode) {
    if ($maxCommentNode <= $currentCommentNode && !$user->hasPermission('bypass comment limit')) {
      drupal_get_messages('status', TRUE);
      drupal_set_message(t('The Node you want to comment has reached its maximum of @maxcommentnode comments', ['@maxcommentnode' => $limitNode]));

    }
  }
  if ($maxCommmentUser) {
    if ($maxCommmentUser <= $currentCommentUser && !$user->hasPermission('bypass comment limit')) {
      drupal_get_messages('status', TRUE);
      drupal_set_message(t('You have commented @maxcomment times, please edit or delete some of your older comments', ['@maxcomment' => $limitUser]));
    }
  }
}

I was seeking a similar solution and found this great post describing using a hook_preprocess_HOOK(), in this case, hook_preprocess_status_messages() - https://stackoverflow.com/questions/38788080/remove-default-message-in-drupal-8

For my purpose to override a message, I use a simple strpos in the logic:

/**
 * Implements hook_preprocess_HOOK().
 *
 * @param $variables
 */
function mymodule_preprocess_status_messages(&$variables) {
  if(isset($variables['message_list']['status'])){
    $status_messages = $variables['message_list']['status'];
    foreach($status_messages as $delta => $message) {
      if (strpos((string) $message, 'The message that I am expecting') !== FALSE) {
        $variables['message_list']['status'][$delta] = "Some different message text";
      }
    }
  }
}


How can I create a Drupal/IFTTT trigger or action? I am looking into the service IFTTT ("IF This Then That"), which is like a trigger/action for the internet. For example, I could tell it that IF I post a new image to flikr, THEN post a link to it on Facebook.

I am wondering if anyone has managed to integrate this into drupal, so, for example, I could automatically post across social media networks when I create new content on a drupal site.

There is a module for that.
Rules and/or Gigya

probably more around.


Create a new Menu in Drupal 8 programmatically Is it possible to create a new Menu in Drupal 8 programmatically using a custom module?

I am creating a custom module, and one of the requirements of the module is that it creates a new menu under Structure > Menus.

Most of the tutorials teach how to add a menu link to an existing menu. For example, Creating menu links, Add a menu link, etc.

In short, I need a way so that the end result is a menu below "User Account Menu" in the image, and then I can add my menu links to it, using above tutorials.

Thanks.

Menus are configuration; you can include one in your module by adding a file named <module_root>/config/install/system.menu.foo.yml to your codebase (replacing foo with the desired menu ID).

The contents of the file will be something similar to one of the same configs installed by the core system module, e.g.

langcode: en
status: true
dependencies: {  }
id: foo
label: 'Foo menu'
description: 'Links related to foo'
locked: true

When the module is (re)installed, the menu will be created.

You could also technically use the API in a hook_install or similar:

$menu = \Drupal::entityTypeManager()->getStorage('menu')
  ->create([
    'langcode' => 'en',
    'status' => TRUE,
    ...
  ]);

but the yml method is a bit cleaner, and I think recommended (can't find a source right now though).

As an aside, the menus are listed in alphabetical order. I don't think it would be straightforward to change that, menus have no concept of weight in relation to one another so you'd have to wedge that in somehow if you really need your menu at the bottom of the list.


Create custom module but page not found I'm new on Drupal. I try to follow a tuto in order to build my own module.

Drupal 8 (latest version) is installed on MacOS.
For example, I use it through URL : http://localhost/drupal/admin/content

My module is defined like this :

Drupal

code
modules

hello_world

hello_world.info.yml
hello_world.links.menu.yml
hello_world.routing.yml

src

Controller

HelloController.php

...

File content : hello_world.info.yml

name: Hello World Module
description: Creates a page showing "Hello World".
package: Custom
type: module
version: 1.0
core: 8.x

File content : hello_world.routing.yml

hello_world.hello_world:
  path: '/hello'
  defaults:
    _controller: '\Drupal\hello_world\Controller\HelloController::helloWorld'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

File content : hello_world.links.menu.yml

hello_world.admin:
  title: 'Hello module settings'
  description: 'example of how to make an admin settings page link'
  parent: system.admin_config_development
  route_name: hello_world.hello_world
  weight: 100

File content : HelloController.php

<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloController.
 */

namespace Drupal\hello_world\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 * Defines HelloController class.
 */
class HelloController extends ControllerBase {

  /**
   * Display the markup.
   *
   * @return array
   *   Return markup array.
   */
  public function helloWorld() {
  $output = array();

  $output['hello_world'] = array(
    '#markup' => $this->t('Hello World!'),
  );
  return $output;

  }

}

Regardless "clear cache", I have a page not found !

I try the urls :

http://localhost/drupal/hello
http://localhost/hello

But results are the same. What should be the right url ?
And why I'm getting "page not found", where is the issue ?

Creating a module does not automatically enable it.

I tried your code in a clean Drupal 8 installation and /hello show the page as expected.

Try running drush en hello_world to enable you module and you should be ok.

If that is not the case, then you can use drupal route:debug to see a complete list of your site routes, so you can know if your route is registered.


How to get friendly URLs to work in a headless implementation? I'm planning to implement a headless Drupal 8 with a SPA using React. I've been looking through articles on this subject but have found that most of them are just describing how I can pull data off from Drupal's API services.

In a regular Drupal site, when I create a blog post, the system will create a friendly URL like "www.mydomain.com/articles/my-post-title". When I'm creating the frontend through a view library such as React, that URL is likely not going to work because that will route the user away from my SPA site but to the Drupal page instead.

I understand that the routing part in React is usually handled by a library such as react-router. However, I don't understand how should the friendly links of pages and blog posts created by Drupal be mapped over in react-router.

If I want the friendly links Drupal create to work with my React frontend, how should I approach this in my headless implementation?

if you use drupal headless its mostly up to the front end framework to implement friendly urls

for react you will probably use routes but since this is beyond the scope of this forum the question might also be deemed as irrelevant


How to reveal the admin password when logged in with one time login link? I just started on a project and there is a prod and dev server. I have access to the dev server and I'm able to do a force login via 'drush uli admin' but I do not have access to the prod server to do the same thing. Is there a way to reveal the admin password on the dev drupal when logged in as admin?

The short answer is: no.

A Drupal password is saved to the database after getting hashed, and the hash is not reversible in any sense that you're hoping for.

An alternative solution would be to try to reset the password to something you know.  Drupal has a description of an SQL approach if you can't use the "reset password" function.

If you don't have command line access you can try using a PHP method to reset it.  However, that is really a last resort kind of situation because of the security implications.  Super last resort.


Usernames in git commit messages on Drupal.org I recently changed my username on drupal.org, and as a result is now different from my git username.

When you attribute a patch someone else using the commit author, you use the anonymous email address, which is based off of the git username (which also shows up in that user's profile page.

When you can commit directly to a project, there is a standard format for commit messages:

  Issue #[issue number] by [comma-separated usernames]: [Short summary of the change].

Are these supposed to be the git username or the drupal.org username?

The usernames are the usernames for the Drupal.org accounts, not the git usernames.

The reason is simple: Everybody can provide a patch, even the users who don't have a git account. As far as I recall, everybody can have read access user to a Drupal.org git repository. You can create a patch that solves an issue; once the issue has been resolved, or the feature request implemented, the git commit will report the usernames of those who contributed with a patch.

The other reason for using the Drupal.org usernames is that not every users see somebody else's git username, and it is more practical to use what is visible in the issue where the patch is being discussed.


Do non-enabled modules affect performance? Does having Drupal modules present, but not enabled have any effect on the performance of a Drupal site?

To put it another way, would removing disabled modules on a Drupal site have a positive affect on performance?

Generally no it will not affect performance - except for when you are viewing your Modules selection page (admin/build/modules or admin/modules). Disabled modules are not loaded into memory and never executed.


Is there a module or easy way to break up nodes into multiple pages? Is there a module or easy way to break up nodes (ie blog posts) into multiple pages?

The paging module will help you with that


PHP 5.4 and Drupal 7 I have heard that PHP 5.4 is faster than PHP 5.3.

Would it be ok for Drupal 7 to run under 5.4, or various contributed modules may start to break the site?

Anyway, If I use APC opcode cache, maybe 5.4, would not offer any benefit at all?

Thanks

I have begun running Drupal 7 on PHP 5.4 myself with only minor problems in the form of notices and warnings.

On top of 7.12, you will need these two patches to fix the issues causing PHP to complain:

http://drupal.org/files/menu-link-save-1338282-15-d7.patch

http://drupal.org/files/database-query-clone-1414412-11-d7_0.patch

One of these patches has already been applied to -dev, so will be in 7.13, and the other is likely going in soon. In all cases that I can immediately think of, the bad practice causing 5.4 warnings has been bad use of array keys.

The first version of this looks like this:

$some_key = function_call();
return $some_array[$some_key];

Some times, the function call will return an array or an object, neither of which is a valid array key. In PHP 5.3, what actually, and silently happens, looks like this:

$some_key = function_call();
return $some_array[(string)$some_key];

PHP 5.4 however, warns that this may not be what you want. The second version is exactly the same, but the other way around.

$some_key = 'a_valid_key';
$may_be_a_string = function_call();
return $may_be_a_string[$some_key];

which yields an error message like

  Illegal string offset 'a_valid_key'

whenever $may_be_a_string is actually a string, not an array, since the only valid string indexes are integers.

As the problems are easy to understand and the fix is (mostly) easy to apply, I've found that in several cases, -dev versions are already updated, or patches posted in the queue, that are likely to quickly go in due to their simple nature.

After some testing, I don't feel like 5.4 is "dangerous" to run in production, and I have begun running my small and personal sites on it already. I would encourage other to do the same, so we can avoid the historically slow uptake of new PHP versions.

At the time of writing, APCs latest version, 3.1.9, does not work with 5.4. I have successfully built and used it from git though.

Using APC will likely reduce the performance benefit of upgrading the PHP version, but not remove it.


2015: What am I missing to get a simple hit counter block by page? I've tried every recommendation I can find; I've enabled statistics and advanced statistics and can see that hits are being counted. I can display lists by what nodes are the most hit, etc; but I just want to display the results for the given node I'm on. How can I do this? I suspect the solution is in using contextual filters for a view, but I can't get this working, either. Help appreciated.

Drupal 7.

I couldn't figure out how to do it with contextual filters, so I guess I still don't understand things on that front. However, a custom block with just a couple lines of PHP did the trick. All directions from:

How to get visitors count of a page created using views

As per that post, custom code was:

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


How can I theme an image inside a field formatter I'm trying to change the output of an image field so that I can display it using a Javascript image gallery. I have the basic field formatter set up, but I'm having trouble finding the correct place to override the theme that displays the <img> tag itself.

I'm overriding the viewElements function of the core ImageFormatter:

class ImageGalleryFormatter extends ImageFormatter {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items) {
    $elements = parent::viewElements($items);
    foreach ($elements as &$element) {
      $element['#theme'] = 'imagegallery_format';
    }

    $elements['#attached']['library'][] = 'imagegallery_formatter/light-gallery';
    return $elements;
  }

}

There I can set my custom Twig theme for each element, but that theme only writes the stuff directly around the <img> tag, not the tag itself. The theme provides access to an {{ image }} variable that renders the actual image. I tried accessing the variables inside the image like {{ image.uri }}, but that didn't work. I know the information I need is in there as I dumped the image variable in Twig and can see the array, but I can't access it from here.

From the Twig debug output I know that 'core/themes/classy/templates/field/image.html.twig' is the theme I need to override, but I can't find a way to do that from my module. I read the source of the core ImageFormatter viewElements function, but I don't see the image variable there and don't understand how I can modify it.

How can I override the theme that renders the <img> tag of an image field in my field formatter?

I'm no expert on field formatters in D8, but are you opposed to using a preprocessor? If not, have a look at template_preprocess_image_formatter. It looks like that is where you would prepare your own variables for use in the image formatter template. Cheers -


Add bulk groups with a new module I want to do (in Drupal commons version 6.25) some kind of bulk OG-Management.

On How to programmatically assign/add new groups to the OG in Drupal Commons 6.25, Fuzzy76 says:

  Doing this through PhpMyAdmin will probably be very cumbersome. You would need to add records to node, revisions, any CCK-tables (if your group nodes have CCK fields), og, og_uid (for group memberships) as a minimum. For addding content to your groups, you would need to add to node, revisions (CCK-tables if necessary) and og_ancestry.

  It is a bit easier creating a group programmatically:

$groupnode = new stdClass();
$groupnode->type = 'gruppe'; // Group node type
$groupnode->status = 1;
$groupnode->uid = $owner_uid;
$groupnode->title = $title;
$groupnode->body = $body;
$groupnode->og_selective = $group_acces_level;
$groupnode->og_register = OG_REGISTRATION_NEVER;
$groupnode->og_directory = OG_DIRECTORY_CHOOSE_FALSE;
$groupnode->og_private = variable_get('og_private_groups', OG_PRIVATE_GROUPS_CHOOSE_FALSE);
$groupnode->{_integration_cGroupType}[0]['value'] = $cGroupType_content; // CCK field

node_save($groupnode);

if ($groupnode->nid) {
  og_insert_group($groupnode);

  // Set space (if spaces_og is used)
  //$ogspace = spaces_load('og', $groupnode->nid, TRUE);
  //$ogspace->controllers->variable->set('spaces_preset_og', $spacepreset);

  og_save_subscription($groupnode->nid, $owner_uid, array('is_active' => 1, 'is_admin' => 1));
} else {
  dpm('OG creation failed :(');
}

Can anybody help me to port over the code (above) to a module?

If you have a naming pattern for the groups, you could use the Automatic Nodetitles module or the Automatic Entity Label module to give the groups a default name and use the Devel module to generate the groups.

Also since groups are nodes, you could use one of those node import modules to bulk upload the groups from an excel sheet.


Adding image styles path in page.tpl i have image upload field in my theme-settings.php

$form['fsos_settings']['intro']['hero']['heroImage'] = array(
    '#type' => 'managed_file',
    '#upload_validators' => array(
    'file_validate_extensions' => array(0 => 'png jpg jpeg gif'),
),
    '#upload_location' => 'public://image/home/',
    '#description' => t("Upload an image."),
    '#default_value' => theme_get_setting('heroImage'),
);

I can print this in my page.tpl.php using the following code

<img src="<?php print file_create_url(file_load(theme_get_setting('heroImage'))->uri); ?>"/>

But i want to use Image Styles (heroimage) for the size. How can i get the image styles URL instead of the original URL

Heres an example using theme_image_style()

$mypath = (file_load(theme_get_setting('heroImage'))->uri);
print theme_image_style(
  array(
    'style_name' => 'heroimage',
    'path' => $mypath,
    'attributes' => array(
    'class' => 'YOUR_IMAGE_CLASS'
    ),
    'width' => NULL,
    'height' => NULL,
   )
 );
}

I'll be honest, I cant remember why I set height and width to NULL, off the top of my head it helped fix some bug! Hope it helps!


Using hook_menu() and hook_permission() to control access How does one limit "what" can access a page. I understand how to use hook_permission() to set user permission based on a role to control access to hook_menu() items. However, what if I have a hook_menu() item that is to be used solely by the system itself? For example, say I have a registration page in a custom module: module/register - Anyone can access that page. Then, say I have an ajax call that is to be made when the user performs some action on the page. So, I register another item in hook_menu(), call it module/register/ajax - I do not want anyone to be able to browse to module/register/ajax but I want to be able to do an ajax call to that page. What is the best way to accomplish this?

I have used AJAX callbacks but this is not a case where a form is being submitted. This is just a pure AJAX call from JavaScript on an event after the page loads.

Quick and dirty, you could do something like this:

function YOURMODULE_menu() {

  $items=array();

  $items['YOURMODULE/register/ajax'] = array(
    'page callback' => 'YOURMODULE_register_ajax',
    'access callback' => 'YOURMODULE_access_ajax',
    'type' => MENU_CALLBACK,
  );

  // other $items here...

}

and then define you own access function for ajax like this:

function YOURMODULE_access_ajax() {

  if (user_is_logged_in() && $_SERVER['REQUEST_METHOD']=='POST') {
    return TRUE;
  } else {
    return FALSE;
  }

}

which will grant access to the path only if the user is logged in and is using POST to access it.  The key here is when you surf around, you are using GET, but when using AJAX, most of the time at least, you are using POST.  Now, if you wanted to get more fancy other than just if the user is logged in, you could do more with user_access() in there instead of the simple user_is_logged_in().

IF however, you are using GET for your AJAX, you can in your page callback check the parameters and if they don't validate, return MENU_NOT_FOUND; or return MENU_ACCESS_DENIED; instead of the drupal_json() stuff.


How do I store the values submitted in a form in the session? I want to submit a form and store the submitted values in the session. In Drupal 7 I just used $_SESSION['key'] = $value; but how do I correctly implement this in Drupal 8?

In D8 the session data is provided by a symfony session object, which is attached to the request. See this comparison of D7 against D8:

Drupal 7:

function mymodule_session_counter_increment() {
  if (!isset($_SESSION['mymodule_count'])) {
    $_SESSION['mymodule_count'] = 0;
  }

  return $_SESSION['mymodule_count']++;
}

Drupal 8:

class MymoduleSessionCounter {
  function increment(Request $request) {
    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);

    return $value;
  }
}

Change record: Access session data through the Request object

Session management has not changed. You don't need to do anything, because Drupal starts a session for each request automatically and you can use it right away.

Examples how to get the session:

Procedural

In procedural code get the request from the static wrapper \Drupal:

$request = \Drupal::request();
$session = $request->getSession();
$session->set('mymodule_value', $value);

Controller

In a controller you can pull the request from the route argument stack by including a typed request parameter. An example from UserController:

  public function resetPass(Request $request, $uid, $timestamp, $hash) {
    ...
    $session = $request->getSession();
    $session->set('pass_reset_hash', $hash);
    $session->set('pass_reset_timeout', $timestamp);
    ...
  }

It's not necessary to define the route parameter in the route definition. The request is always available.

Form

In a form method get the request from getRequest():

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $session = $this->getRequest()->getSession();
    $session->set('mymodule_form_value', $form_state->getValue('value'));
  }

Private Tempstore

The private tempstore is not a replacement for sessions. It depends on the session id and it's not possible to use it without a session. So you can store the values directly in the session as well. Drupal core uses the private tempstore for big amount of data and only for authenticated users who already have a session. For anonymous users it's not easy to get a private tempstore started, because drupal uses dummy session id's until it starts a real session. If you start a private tempstore in custom code it has the wrong session id.


How do I programmatically set the view title? In D8, I have a need to dynamically set the title of a views page display.

I've tried implementing both hook_views_pre_render and hook_views_post_build and setting the value of $view->build_info['title'], but Drupal seems to be ignoring it when setting the page title.

It seems like the code in Views where the title is set is in Drupal\views\Plugin\views\display\Page::execute()

The #title property on the render array in that method IS receiving my overwritten value from one of my hooks, but it's still ignore and is using the manually specified title on the display config.

What is going on!?

If someone else is looking for an answer, Here is how I achieved this.
I implemented hook_views_pre_render and in this hook, I implemented a method of views class setTitle. This allowed me to set the page title. Here is the complete code.

function MYMODULE_views_pre_render(ViewExecutable $view) {
 if ($view->id() == 'ABC') {
  $view->setTitle('MY CUSTOM TITLE');
 }
}

Hope this helps.


Injected javascript in google DFP module drupal 7 Currently I am setting up the Google DFP module and I have been trying to work out how the JavaScript is working. In the module there is a section for injecting JavaScript which is what Google DFP will give you to place in the head tag on the website. When I place the JavaScript in the form where it tells me to place it, when I load the page up it shows some of the JavaScript at the top in the body (using the DFP module).

So I experimented around with this and took the JavaScript out. I was expecting the adverts to stop displaying, however they kept displaying after taking out the JavaScript and deleting the cache and I am confused as to how it is displaying the correct adverts.

Sadly I can't give a link to the website because I am using eclipse to test things out.

The module I am using is: Doubleclick for Publishers (DFP)

What I would like to know is how is this working? The JavaScript isn't there so how does it know what adverts to get? The only thing the module knows is the network ID and the advert tags using the [dfp_tag:slot] token.

you can take a look at these functions (_dfp_js_global_settings and _dfp_js_slot_definition) that are used to inject inline javascript in the page, I believe that javascript loads the ads remotely and inject them in their spots


How do I change XML tag names? I've created views as XML data document using Views Datasource which looks like:

<?xml version="1.0" encoding="utf-8"?>
<node><node>
<title>My title</title>
<field_feed_description>My description</field_feed_description>
</node></node>

How do I now change generated XML name tags?

For example I want to rename field_feed_description name into something else.

On the Views UI tick the Create a label checkbox and enter in your element name in the Label textfield. The value of Label will be used for the element name.


"Jirafe credentials are not set" warning from Commerce After install Commerce Kickstart 2.7, there is a warning:

  Jirafe credentials are not set. Get your credentials at Jirafe

What is Jirafe and Jirafe credentials?

Jirafe is an analytics, alerting, and automation platform that is deeply integrated into ecommerce, marketing, and other platforms.

The Jirafe module integrates Jirafe with Drupal Commerce, and allows the following features:

  View your visits, orders, revenue, conversion %, AOV (average order value), and RPV (revenue per visit). This information can give you a great summary of your business at a glance. See how your visitors become customers at 5 critical points in your application. Easily see when visitors leave your site, so that you know what areas of your site to improve.

As you are using Commerce Kickstart, the module is already enabled. To configure You just need to:

Click on the Reports tab of your administration menu, or access admin/commerce/jirafe
Enter your credentials (Application ID and Token) that you get from jirafe and click Save


Mark a location on a map (Google Maps/OpenLayers) on a node creation or edit page - but with which module? I have a custom content type, and I would like my users to mark a location on a Google Maps/OpenLayers map, save these coordinates, and on the frontend, show the location's map and the GPS coordinates.

So the user has the opportunity to just simply click on the map somewhere, and mark a location. BUT if the user wants to, he/she can also type an address, and geocode it.
(In this post, the OP just wants the latter opportunity.)

I would also like to have a page where the different locations are listed, which are related to the given nodes. Plus maybe some search opportunities.

Geolocation Field seems correct, but I'm a bit confused whether the other modules are better for this task, or what's the difference between them.

The possible modules:

Address Field,
GMap (unfortunately stating "GMap is considered a legacy module.")
Geocoder,
Geofield,
Geolocation Field
Get Locations,
Location,
OpenLayers,
OpenLayers Locator (that's a buggy feature as an own experience),
etc...

(For example, Get Locations looks promising because of the many opportunities. But OpenLayers too... Geolocation Field seems like a little simpler, but also with less opportunities (concentrating on just marking a place on the map). By the way, I don't really understand Get Locations field's module page, firstly it states that it has "Support for Geolocation (Drupal 7)", but later there's the following sentence: "Please note - Do not install the Location module or the Geofield, Addressfield or Geolocation modules at the same time as Getlocations_fields, this will not work.")

I had a good experience with Geolocation Field.

I used this module on dealing website to show location of store. It lets you mark location via node creation/edition form and have display formatter to rendering the address as PNG or Google map.

It was simple and good enough.


How can I style fields in custom content type I am using Drupal 8 and I've made a custom content type, and I've figure it out, that I can "style" this content type with page--mycontenttype.html.twig and with adding this code in mytheme.theme:

function mythemename_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page__'.$content_type;
  }
}

But with this I can only style page of custom content type, and not the fields of it. I try with this but it's not working:

{{ node.field_body.value }}
{{ node.field_title.value }}

The body and title have no prefix field_, this should work:

{{ node.body.value }}
{{ node.title.value }}

But is not the preferred way to style the fields on the page level. If you access the field values in the database, which you basically do when you access the node object, you get the raw value, only escaped by twig for security reasons. Without the formatting, that is integrated into drupal for each field type, and that you can easily extend with additional modules.

To style the fields of the custom content type go to:

admin/structure/types/manage/mycontenttype/display

If you can't find all the options you need for your fields in the ui, you can make a copy of the field twig and apply the changes there.

field--field-myfield.html.twig


Modal form file upload is not working I am trying to use ctools modal form to edit node form. This form is containing a file field. The Form is rendering properly. When I try to upload a file on clicking upload button, file field has been deleted from the page. I tried to debug via firebug to see the response, it was correct as we get without modal form.

I added the following code in modal callback.

ctools_include('node.pages', 'node', '');
ctools_include('modal');
ctools_include('ajax');

$form_state['build_info']['args'] = isset($form_state['build_info']['args']) ? $form_state['build_info']['args'] : array($node);
form_load_include($form_state, 'inc', 'node', 'node.pages');

I took the reference from Ajax upload in Ctools Modal Window but it still having problem.

Make sure you're implementing the right Drupal API syntax which requires $form_state to be the reference to the original array, so it can be properly modified through certain hooks.

For example if you're using form_load_include() in hook_form_alter(), make sure you're following the right API syntax which is:

hook_form_alter(&$form, &$form_state, $form_id)

(note the &) otherwise form_load_include() can't perform alterations of your current state of the form ($form_state).


Using "Or" opertor in EntityFieldQuery could you help me to fix my problem?
note:
each user have two field (fields are taxonomy reference)

I want to get two fields with OR condition
the output of my code returns in the shape of AND result

here is my code :

 $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_software_abilities', 'tid', $abilities, 'IN')
    ->fieldCondition('field_other_abilities', 'tid', $abilities, 'IN');
    $result = $query->execute();

I read an article about using addtag and hook_query_tag_alter()
but I can't use it

EntityFieldQuery does not support 'OR' operators. There is a workaround presented here 'OR' Queries with EntityFieldQuery  where an 'OR' operator is added.


Zen sub theme: page--node--name.tpl.php not working! I'm hoping someone can help me because I'm at my wits end!  I'm using the zen theme - then created a sub-theme and now I can't seem to get the custom templates to be recognized by the custom content type name (page--node--custom_content_name.tpl.php).

I've created a new template.php in my sub-theme and placed text that I've found in other blogs and forums to help make it recognize the content type so I can use it in the tpl.php name but nothing seems to work.  If I use the dev module it only says that I can name them page--node--1.tpl.php, which would be fine if we weren't going to be adding more content on an ongoing basis.

Right now I have so many tpl.php just so that I can show people what the pages will look like - it's crazy!! What am I doing wrong?!
Help!!

Drupal doesn't provide content type based template suggestions for page.tpl.php but for node.tpl.php. That means you can use a template like node--custom-content-name.tpl.php.

However, if you want to have a page.tpl.php for your content type, you need to tell Drupal about your template suggestion. Put this code in your template.php file:

function YOURTHEME_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
    $content_type = $variables['node']->type;
    $variables['theme_hook_suggestions'][] = 'page__' . $content_type;
  }
}

You should name your template file like: page--custom-content-name.tpl.php.


Which module should I use to manage translations in D7? I want to develop a multilingual site with support for which I followed this site. But after doing the initial steps I am not getting the translation management.

I downloaded the Hindi translation package, internationalization, locale modules have been installed. Unable to install the internationalization views as it's not compatible with Drupal 7.x

Translation management is also not supported

So how can I translate my site to any other language?

I'm using Drupal v7.34.

Excerpt from the Translation Management project page:

... provides complete workflow management for multilingual Drupal sites.
Content managers can manage all translations from one central page. The module shows which contents need translation and notifies translators about what they need to do.

Be aware however that this is a D6-only module, not at all suited for a D7 site.
For D7 there are basically 2 alternatives available:

Translation Overview, mentioned as a recommended add-on on the i18n project page also. From its project page:

... provides a table listing the site's nodes and showing what's been translated into each language. It also lets you assign priorities for translating nodes into the various languages.

Translation Management Tool, considered as the successor of the previous module, and "the" module to move forward with in D8 also. From its project page:

... provides a tool set for translating content from different sources. The translation can be done by people or translation services of all kinds. It builds on and uses existing language tools and data structures in Drupal and can be used in automated workflow scenarios.
This module does not make i18n or any other language module for Drupal obsolete. It does only facilitate the translation process.


PHPUnit errors occur when running drupal-check I am trying to run drupal-check on the social_auth_dropbox module (vendor/bin/drupal-check -ad web/modules/contrib/social_auth_dropbox) and I'm facing this error:

Warning: Class 'PHPUnit\Framework\MockObject\Matcher\InvokedRecorder' not found in /Users/Documents/sample/my_site_name_dir/web/core/tests/bootstrap.php on line 197
0/11 [░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 0%
Fatal error: Declaration of Drupal\Tests\BrowserTestBase::setUp() must be compatible with PHPUnit\Framework\TestCase::setUp(): void in /Users/Documents/sample/my_site_name_dir/web/core/tests/Drupal/Tests/BrowserTestBase.php on line 39

The first warning could make you think PHPUnit isn't installed, but since drupal-check is able to tell you that the declaration of Drupal\Tests\BrowserTestBase::setUp() is not compatible with the declaration of PHPUnit\Framework\TestCase::setUp(), that is not the case. If PHPUnit weren't installed, drupal-check would report more missing classes.

PHPUnit is installed, but it's version 9.0.0 or higher version, where:

The PHPUnit\Framework\MockObject\Matcher\InvokedRecorder class doesn't exist (but it's defined in PHPUnit 8.0.0)
The PHPUnit\Framework\TestCase::setUp() method is defined as setUp(): void, while PHPUnit 7 defines it as setUp() (The difference is enough to cause the fatal error.)

So, in short:

The installed version of PHPUnit is at least 9
The Drupal version you installed still requires PHPUnit 7

Notice that, so far, only Drupal 9.x has been updated to PHPUnit 8, and in future it will support PHPUnit 9. Previous Drupal versions still need PHPUnit 7, and eventually they will be updated to support PHPUnit 8.


Notify a user if a node has a comment or status updated I'm trying to build a simple ticketing system with Drupal 8.6. I'm able to create a content type for these tickets and the comments will be the responses to the ticket. Also I have a status field for open, pending, and closed. I want to be able to email all the users on the ticket if the node is updated or commented on. And I have another user reference field for "assigned ticket to".

What modules would I need that work with 8.6 to get this kind of funtionality? I prefer no modules, but I'm not sure if core itself supports this type of thing.

I recently did something similar, for reacting when the node is updated i used hook_node_presave(). Here's an example on how to send an email when the node is updated and the status is changed from "open" to "pending".

function my_module_node_presave(NodeInterface $node){
  if($node->getType() == 'your_content_type_name' AND $node->isNew() == FALSE) {
   $status_original = $node->original->get('status_field')->value;
   $status_updated = $node->get('status_field')->value;

 if ($status_original !== $status_updated AND $status_original == 'open' AND $status_updated == 'pending') {
   send_mail();
  }
 }
}

For creating the send_mail function or whatever you'd like to call it i used the following resource and modified the code where necessary: How to send a mail programmatically in Drupal 8. Also, i used the SMTP Authentication Support module to send the emails using a gmail account: SMTP Authentication Support. The configuration page of the module is on admin/config/system/smtp.

For checking if a comment has been posted you can use hook_ENTITY_TYPE_insert() and replace "ENTITY_TYPE" with "comment" and inside the hook you can call again the send_mail function.

I did not quite understood how you are storing "all the users on the ticket", but it would be the case of getting the users email address with getEmail();


Ad-hoc content access restriction is there a way to restrict content access to a specific subset of users upon node creation without having to create a specific user role and/or organic group?

For instance having a list of users to refer to upon node creation, and allowing ONLY them to view/visit/edit the node.

As mentioned above, the Node Access User Reference module does exactly that. You specify a list of user and grant them actions upon the node. Awesome.


Create node and node reference from URL at one time I have content type "article", in some cases I need to orginise group of parent and child nodes and to do this I use Node Reference from URL module. Also I need to include parent node in this group of articles because some views and node URL depend on completed field "node reference". So, how it works now:

I create a parent node and leave the node reference field empty as the parent node doesn't exist now;
Save this node
Back to edit page and choose my new parent node from the list of avalible nodes in node reference field;

What I would like to do is to create parent node and fill node reference field at the same time.

I guess that Rules module could help me but It too powerfull module and I do not need it for my website. Is there a more simple solution?

Depending on which relationship module you're using there are different options.

If you're using Entity Reference there's the Inline Entity Form module:

  Provides a widget for inline management (creation, modification, removal) of referenced entities.
  The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.

If you're using the References module there's References Dialog:

  This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog. This allows for a workflow where the user can create all the references to a node at the same time as she is creating it, a process which sometimes get's a bit backwards, when a user for instance needs to create all the facts for an article.

Both will allow you to create a referenced node at the same time as creating the referee.


How do I display an error message on a basic page when the user does not have permissions to see the nested view inside the basic page? I have a basic page, and inside of that basic page I have a view "newsletters". The view "newsletters" has permissions set on it based on role, so only admin and subscribers can see it. How can I display "You must be a subscriber to view this content" on the basic page when the user does not have permissions to view "newsletters".

Currently, if the user cant see "newsletters" my basic page just shows an empty page. I want it to display "You bust be a subscriber to see this content".

I tried creating another view "redirected page" that is only visible to anonymous users but it is not showing up for some reason.

The reason I made a basic page with a view nested inside it is because I wanted users who don't have permission to view the page to still see the link in the menu bar.

You can create a basic Block with your text message and set up Visibility to only Anonymous users, and to show on your basic page.

This way anonymous will see the Block, authenticated will see the Views block.


Programmatically Render a Node Edit form with a custom Form Display Mode I'm attempting to make a page for users to edit data for a specific content type, but I only want them to have access to some of the fields not all. To do so I created a custom form display mode for content. I have a custom controller that is meant to display this form with a custom display mode. Here is the code meant to render it.

    public function showCustomForm() {
        $node = \Drupal::entityTypeManager()->getStorage('node')->load('123');
        $edit_form = \Drupal::entityTypeManager()->getFormObject('node', 'my_custom_form_display_mode_id')->setEntity($node);
        return \Drupal::formBuilder()->getForm($edit_form);
    }

And I get the error

  Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException:
  The "node" entity type did not specify a
  "my_custom_form_display_mode_id" form class. in
  Drupal\Core\Entity\EntityTypeManager->getFormObject() (line 184 of
  /var/www/mydomain/http/web/core/lib/Drupal/Core/Entity/EntityTypeManager.php).

I was using this How do I load a form with a specific form display (form mode)? as an example. But still had no luck.

How would I programmatically load a node edit form with a custom form display mode?

The error message says you did not specify a form class, but what it really wants to say is, that you did not specify a form operation with the name of the form mode:

mymodule.module:

function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('my_custom_form_display_mode_id', 'Drupal\node\NodeForm');
}

The form operation needs a form class. This can be the same as for default, which you find in the handlers section of the annotations in the Node class.


Why isn't my programmaticlly created field showing up to be added to a content type I'm trying to create a field that I can add to content types via my module, here is how I'm doing it:

/* Create the field to hold RSVP info */
function kade_rsvp_enable(){
    if(field_info_field(FIELD_REQUIRE_RSVP)) return; //field already created

    $field = array(
        "field_name" => FIELD_REQUIRE_RSVP,
        'cardinality' => 1,
        'entity_type' => 'node',
        'type' => 'list_boolean',
        'description' => 'Enable RSVP for this event?',
        'label' => 'Enable RSVP',
        'widget' => array(
            'type' => 'options_onoff',
        ),
        'settings' => array(
            'allowed_values' => array(
                '0' => 'No',
                '1' => 'Yes',
            ),
        ),
    );

    field_create_field($field);
}

And the field is getting created when the module is enabled. Here is the var_dump of the field_info_field for it's id:

array(20) {
  ["entity_type"]=>
  string(4) "node"
  ["description"]=>
  string(27) "Enable RSVP for this event?"
  ["label"]=>
  string(11) "Enable RSVP"
  ["widget"]=>
  array(1) {
    ["type"]=>
    string(13) "options_onoff"
  }
  ["settings"]=>
  array(2) {
    ["allowed_values"]=>
    array(2) {
      [0]=>
      string(2) "No"
      [1]=>
      string(3) "Yes"
    }
    ["allowed_values_function"]=>
    string(0) ""
  }
  ["entity_types"]=>
  array(0) {
  }
  ["translatable"]=>
  string(1) "0"
  ["storage"]=>
  array(5) {
    ["type"]=>
    string(17) "field_sql_storage"
    ["settings"]=>
    array(0) {
    }
    ["module"]=>
    string(17) "field_sql_storage"
    ["active"]=>
    string(1) "1"
    ["details"]=>
    array(1) {
      ["sql"]=>
      array(2) {
        ["FIELD_LOAD_CURRENT"]=>
        array(1) {
          ["field_data_field_require_rsvp"]=>
          array(1) {
            ["value"]=>
            string(24) "field_require_rsvp_value"
          }
        }
        ["FIELD_LOAD_REVISION"]=>
        array(1) {
          ["field_revision_field_require_rsvp"]=>
          array(1) {
            ["value"]=>
            string(24) "field_require_rsvp_value"
          }
        }
      }
    }
  }
  ["foreign keys"]=>
  array(0) {
  }
  ["indexes"]=>
  array(1) {
    ["value"]=>
    array(1) {
      [0]=>
      string(5) "value"
    }
  }
  ["id"]=>
  string(2) "23"
  ["field_name"]=>
  string(18) "field_require_rsvp"
  ["type"]=>
  string(12) "list_boolean"
  ["module"]=>
  string(4) "list"
  ["active"]=>
  string(1) "1"
  ["locked"]=>
  string(1) "0"
  ["cardinality"]=>
  string(1) "1"
  ["deleted"]=>
  string(1) "0"
  ["columns"]=>
  array(1) {
    ["value"]=>
    array(2) {
      ["type"]=>
      string(3) "int"
      ["not null"]=>
      bool(false)
    }
  }
  ["bundles"]=>
  array(0) {
  }
}

However, it doesn't show up when I go to add it to a content type

What am I doing wrong?

You also need field instance to add that field to a content type.

  field_create_instance() : Creates an instance of a field, binding it
  to a bundle.

  // Create field.
  $field_name = 'field_rsvp';
  if (!field_info_field($field_name)) {
    $field = array(
      "field_name" => $field_name,
      'cardinality' => 1,
      'entity_type' => 'node',
      'type' => 'list_boolean',
      'description' => 'Enable RSVP for this event?',
      'label' => 'Enable RSVP',
      'widget' => array(
        'type' => 'options_onoff',
      ),
      'settings' => array(
        'allowed_values' => array(
          '0' => 'No',
          '1' => 'Yes',
        ),
      ),
    );
    field_create_field($field);

    // Create the instance.
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => 'article',
      'label' => 'Enable RSVP',
      'description' => 'Enable RSVP for this event?',
      'required' => TRUE,
    );

    field_create_instance($instance);
  }

If you created a new field say for article content type, then you can see that field for other content types in the Add existing field field as mentioned in the comment by tenken


How do I add custom pages or view pages to search index? Suppose I have a custom page built in a custom controller. Or similarly, a view page the displays the list of nodes, such as the classic "admin/content" page.

I want certain user roles to be able to find this page when they search the site. The search does not have to index the entire view/page content, but rather a select parts of the content.

Is this possible to do using core hooks? If not, then perhaps using search api hooks?
I am thinking of hooking into the indexing process, and then, retrieve the pages I want to index and send them along. But I am not sure how to do this in a abstract manner where the implementation would work using core database search or search api with solr.

Note Drupal 7 or 8 ideas would be much appreciated.

Yes, it's possible to provide a custom search index for either the Core/Search API module. Both modules are using the D8 plugin API to create their own plugin types for providing new indexing.

In Core, the SearchPlugin plugin type allows you to define the methods that you will need to implement for all aspects of search. To see how this works, look at the core UserSearch & NodeSearch plugins to see how it interfaces with queries and indexing.
For SearchAPI, there are many different plugin types for interfacing with its different aspects of search. For brevity, you should start looking at the SearchApiDatasource plugin type to start providing a new indexable source.

In regards to an "abstract manner where the implementation would work using core database search or search api with solr," you're going to have to get clever with OOP and the plugin classes you're providing in your module if you want to do something like that. You're better off implementing each first, then abstracting later (if it provides benefits).


Wiki-like "create this page" with page manager? I want to make it easier for editors to create new pages with page manager.  Is there a way to provide a "create this page" functionality for non-existent paths, so that editors can insert a new path in existing pages and proceed to create and edit the new page, just like editing a wiki?

I am wondering if I can implement this feature by using a menu tab like this to redirect unhandled path to the page manager's creating page.  Helps are very much appreciated.

You should achieve that by using the following extensions:

wikitools
freelinking

You should have a look at this screencast:
http://www.youtube.com/watch?v=KHsjjHzYOSg

It is done with Drupal 7, however, wikitools is still in alpha for Drupal 7.


Field values sometimes do not show up in grid view or node view for non admin users I have a view that is sorted by the number of times a user visits a node and clicks the play button (the play button is a menu item of the node).  Every time the play button has pressed the value of an integer field inside the node is incremented and this value is used to sort my view.  I also display the value "Times Played" both in the view and the node.  When I look at the view as admin everything looks good, like this:

But when I look at the view as a normal user the view is still sorted correctly but some of the nodes don't show the value for "Times Played", here is that screenshot:

Also, when I view the actual node page as an admin I see always see the correct value for "Times Played" but when I visited it as a normal user I get the same behavior I see in the view.  Any idea what could be going on here?  Is this some strange permissions issue?

Did you try to embed view in your template file?   $embed = views_embed_view('name_of_view','display_id'); . You need also to check permissions


Drupal 7.8 customising user.module I am going to build a site using Drupal 7.8. I have some knowledge in PHP, but it is my first time I use Drupal, so I would like to ask your help regarding some basic functional questions I have

I want to have 2 tabbed blocks in my first page. One for "log in" and another for "sign up".
To create this blocks:
For "log in" block it s easy: I will use the out of the box functionality as is (removing create new and request password).
For "sign up" block I would like to remove and add some fields.
Is there any way to find inside user.module the fields used for "username","password","email" etc. and try to use them in my own module?
What are the minimum requirements to use these fields? In other words, if I find the name of these fields, can I use only the names on my module, or I have to override a form/function that maybe contains these fields?
I want to use these fields, but finally for the submission in the database I 'd like to use the default submit functionality. How that could be done?
3.And one last and very newbie question! Forms are implemented using functions or can be stand alone?
So to use an existing form, I have to find in which function it s declared or I have to override only that form?
I know that these are basic questions I should already know but after searching in google, I didn't manage to find a clear solution that works. Could you please help?

You can also use fields to add additional fields to a user or user the profile2 module. There's a good chance, that you don't even have to code a line ;-).

If you need: You can change any form in Drupal with hook_form_alter. This way you can add more functionality to the sign up form.


twig for loop access value using array i have a for loop

{% for row in rows %}
    {{ row.content }}
{% endfor %}

will print out like this

 one

 two

 three

 ...

but what i want to is access the values using a key so i can pull the values individually so i can do some thing like this

 one

 one

 one

basically print the value anywhere i want on a div of my choice. Is it possible ?? please help

this is for a views template

In views-view.html.twig is not appropriate to style your row and fields.

To style them first you need override template "views_view_'format_style'" (format style specified when you edit/create a view). Here you can style row and access 'fields' variables (use kint(row) to see them).

Something like:

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {{ kint(row) }} {# devel #}

 {{row.content['#node'].getTitle()}}
 {# access fields #}

    {{ row.content }}

{% endfor %}

For style fields its better override field template.

For example field--node--body--article.html.twig:

{% set mode = element['#view_mode'] %}
{% if label_hidden %}
  {% for item in items %}
    {% if mode == 'full' %}

{{ item.content }}

    {% elseif mode == 'teaser' %}

{{ item.content }}

    {% endif %}
  {% endfor %}
{% else %}

{{ label }}

    {% for item in items %}

{{ item.content }}

    {% endfor %}

{% endif %}

source : In Drupal 8 view.html.twig file how do I access the view content such as individual field title and/or field content?

http://twig.sensiolabs.org/doc/tags/for.html


How to implement a set of images / diagrams in a website? I am an experienced PHP developer but am just finding my feet with Drupal.  I am creating a personal website using the Bootstrap theme and want to upload some images/diagrams as part of it.  They will be publicly available.

My question is, should I just create a directory in the web root, ftp the images there, and put raw <img> tags in my pages?  Or should I install a module and get it to do the work for me?

I am very happy to use the first (i.e. manual) method, but I'm thinking that there might be hidden advantages in letting a module handle it for me.  For example, if a module does the uploading, it would presumably have particular css classes that it would apply to the <img>.

At this stage I will be the only one creating content.

To answer your question, I think it depends on how you plan to use those images ...

Option 1: use individual images to beef up specific content pages

In this case you just upload those images to a folder such as sites/default/files, and then you could just use them (refer to them) with a typical img tag. To make sure that these images will actually also be rendered (when viewing the page), make sure that the "text format" used in the node does allow the img-tag. Typically for a node using the "Filtered HTML", it could well be that the img-tag is not allowed (yet) as one of the available HTML tags. In that case, your HTML code does include an 'img" tag, but when viewing the saved node the image is not rendered (visible). To resolve it, within admin you must enter the img-tag as one of the allowed HTML tags for the text format used in the node.

Option 2: visualize them in the format of a Gallery

Talking Drupal #083 is a great podcast about this topic, and includes a lot of recommended modules in this areas. Just to mention a few of them (mentioned on the linked page):

  Gallery formatter - https://www.drupal.org/project/galleryformatter
  Views Slideshow - https://www.drupal.org/project/views_slideshow
  Flexslider - https://www.drupal.org/project/flexslider
  Node Gallery - https://www.drupal.org/project/node_gallery
  Multiupload  Filefield Widget - https://www.drupal.org/project/multiupload_filefield_widget
  Multiupload Imagefield Widget - https://www.drupal.org/project/multiupload_imagefield_widget
  Field Focus - www.drupal.org/project/imagefield_focus
  pl upload - https://www.drupal.org/project/plupload


Is this a good way to make fields accessible for an empty entity object? I have a function, my_entity_create(), which returns an empty object for my entity with properties: isnew, name, etc...

I want my fields attached to this empty object so I can set their values.  I accomplished this by calling the function below and adding the results to my object in my_entity_create().  Now I can set $my_entity_obj->field_my_field['und'][0]['value'] = 'some value'.  I save it with entity_save() and it works.

My question:  is there a better way to do this?  I'm trying to learn to do things 'the drupal way'... or just the best way if there is not a drupal best practice for a certain task.

function _get_fields_for_bundle($bundle)
{
    $result = db_select('field_config_instance', 'f')
        ->fields('f', array('field_name'))
        ->condition('entity_type', 'my_entity_type')
        ->condition('bundle', $bundle)
        ->execute()
        ->fetchAllAssoc('field_name');

        return array_keys($result);
}

I too was looking for an answer to this question, however you question has provided me with the best answer so far.

My implementation of your solution was to call your function in my entity create function and then loop over the values attaching the fields as empty arrays:

function MY_ENTITY_create($values = array()) {
    $entity = entity_get_controller('MY_ENTITY')->create($values);
    foreach(_get_fields_for_entity('MY_ENTITY') as $field) {
        $entity->{$field} = array();
    }
    return $emtr_safe_check;
}

function _get_fields_for_entity($entity) {
    $result = db_select('field_config_instance', 'f')
        ->fields('f', array('field_name'))
        ->condition('entity_type', $entity)
        ->condition('bundle', $entity)
        ->execute()
        ->fetchAllAssoc('field_name');

        return array_keys($result);
}

As my entity does not have a bundle, but my module does define several different entities I modified your function slightly to handle loading fields for different entities with bundles of the same name.

I would still be interested to see other peoples solution to this problem.


passing a user id to user_is_logged_in function I want to use the user_is_logged_in function to determine if a user is logged in but i want to determine if that user is logged in from a cron job/ module.

Essentially i have an array of user id's that i want to loop through to see if the corresponding user is logged in and if so execute some code.

My question is how does one pass an integer to the function to get a true or false from the function? all examples i have seen use the function on a page where the user is viewing to show them content or send message to them. Nothing i can see shows how to use it from a script.

Hope this makes sense.

Madmilner

If you look at the docs you'll see the function comment:

  Determines if the current user is logged in.

Emphasis mine.

So the function simply isn't supposed to do what you want to use it for, you'll need to write something custom

It's pretty easy though, see Get all logged in users in Drupal for some inspiration.


Is there any way to hide author information from custom article rather than content type? I know that I can hide author information in below path in Drupal 8:

Home>Admin>Structure>Types>Article>Display settings

but I want to know is there any setting or selective options to hide author information per custom article or post, rather than all post of custom content type?

No, but it would be easy to implement:

Add a Boolean field called show_author_info or something
Create a node template for that content type in your theme (or for nodes in general if you don't need to specify a type)
Add a conditional to the template to only output the author information if the node has a positive value for that field


Autocomplete on a custom field on the registration form no longer working thanks for reading.

I have a database table containing organisation names. When a user registers on the website, they use a text field I added, which autocompletes with existing organisation names, as a way of attaching them to existing organisations. This used to work fine, but doesn't seem to now, presumably after one of the updates. Now it simply doesn't load anything when typing in, though the little circle appears to indicate that it is connected.

Here's the code:

$items['org/autocomplete'] = array(
  'page callback' => '_org_autocomplete',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK
);

...and...

function _org_autocomplete($string = '') {
  $matches = array();
  $query = db_select('org_orgs', 'c'); // I've checked that the table exists, contains data, and is of this name - that's fine
  $return = $query
    ->fields('c', array('name'))
    ->condition('c.name', '%' . db_like($string) . '%', 'LIKE')
    ->range(0, 10)
    ->execute();

  foreach($return as $row) {
    $matches[$row->name] = $row->name;
  }
  if ($_SERVER['HTTP_REFERER'] == url('user/register', array('absolute' => TRUE))){
    drupal_json_output($matches);

    // The if statement surrounding this line prevents users
    // from viewing the full list by going directly to the
    // /org/autocomplete URL. In removing the if statement, I can
    // test to see if it works at the URL, and it does just fine

  }
}

I've checked that the table exists, contains data, and is of this name - that's fine. The if statement surrounding the drupal_json_output() line prevents users from viewing the full list by going directly to the URL. In removing the if statement, I can test to see if it works at the URL, and it does just fine.

function org_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['field_organisation']['und'][0]['value']['#autocomplete_path'] = 'org/autocomplete';
  // Though no results appear, the 'org/autocomplete' path
  // is confirmed as the correct path because changing it to
  // anything else removes the little autocomplete circle.
  $form['field_organisation']['und'][0]['value']['#description'] = 'If your organisation appears in the above predefined dropdown menu, please select it.';
  $form['#validate'][] = 'org_form_validate';
  $form['#submit'][] = 'org_form_submit';
}

Though no results appear, the 'org/autocomplete' path is confirmed as the correct path because changing it to anything else removes the little autocomplete circle.

Do you have any ideas of what's gone wrong, or if not, what I can do to investigate?

Additionally, in searching for the solution, I found this drupal update: http://drupal.org/node/1901518 Could this be the cause? And if so, what can I do to correct it?

Thanks

What you say suggests it's this line that's the issue:

 if ($_SERVER['HTTP_REFERER'] == url('user/register', array('absolute' => TRUE))){

so there's presumably some difference between the referrer URL and the one generated by the url() function. You might add lines above it to record the two values using watchdog: that would confirm you are reaching that point in the code and help diagnose the issue.


Add a read more link to product list I have a view with a grid displaying rendered entity of product list for my product display index. Is it possible to add a read more link to the product list display with a link to the product. I have tried to create this in several different ways, by creating a link in the content type fields, however that would require manual completion. I appreciate that if I was using fields in views I could add the link there. I'm hoping there is a solution to adding to the product list. I have also looked at adding it manually to node.tpl.php, but I am unsure of where to define the variable instead of $teaser. Many Thanks in advance.

Fixed, I added all of the required fields from product list to teaser, then modified the css accordingly.


Difference between field_data and field_revision tables? I have a lot of custom functions; I just want to make sure I'm doing this right.
If I want the most recent version—the live version—of a node, I go to the field_data_field_xyz table, right?

My understanding is the field_revision_field_xyz keeps all older versions, correct?

That is correct: Working with Field SQL Storage.

  Database tables:

  {field_data_[field_name]} Standard data storage for a field.
  {field_revision_[field_name]} Standard revision storage for a field.


How to create user like drop-down filters for a custom module in admin side Drupal 7 admin panel, when clicked on people, a form with drop-down filters is visible.

user filters http://www.imagesup.net/?di=914041271981

How can we create above filters in our custom modules ?

I have tried goggling, but when searched filter in Drupal, it returns text filters which replaces text.

I have a custom module in which list of items are show, I want to filter items based on different fields.

Any help would be appreciated, thanks !!

Well you have 2 options:

Declare your custom tables with Views. This can be tricky, and take some trial and error, but gives more flexibility going forward.
Declare a custom page in your module (using hook_menu). Then just build a form with the search options you want and build a query. See the Examples modules if you're not sure how to build a page.


drupal 7 webform add classes to submit button I am trying to add classes to my webform. In

hook_webform_element

I can do this

if ($element['#type'] == 'checkboxes') {
  $wrapper_classes = array(
    'form-item',
    'webform-component',
    'large-16 medium-8 small-24 columns',
    'webform-component-' . $type,
  );
}
else {
     $wrapper_classes = array(
    'form-item',
    'webform-component',
    'large-8 medium-8 small-24 columns',
    'webform-component-' . $type,
  );
}

But I do not seem to have access to the submit button. I need to add a couple of classes and also only do it on a certain form so suppose I need the $form_id.

You can do this hook_form_alter(). As all the form element are available in hook_form_alter.

function mymodule_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'webform_client_form_YOUR_NODE_ID') {
        $form['actions']['submit']['#attributes']['class'][] = 'newclass';
    }
}


How to detect Panelizer use in template_preprocess_html()? In Drupal 7, you could look for $node->panelizer or use page_manager_get_current_page() to check if the current page uses a panelizer layout. How do you do that in Drupal 8?

I'm trying to add a body class if the current page contains a specific pane.

I'm not sure if this is quite what you're after, but these hooks will fire if your page is using panelizer.

/**
 * Implements hook_preprocess_panels_pane().
 */
function YOURTHEME_preprocess_panels_pane(&$$variables) {
  // If this triggers then you are in a panels pane.
}

OR

/**
 * Implements hook_panels_pane_content_alter().
 */
 function YOUR_MODULE_panels_pane_content_alter($content, $pane, $args, $contexts) {
  // If this triggers then you are altering panels content.
}

If you want to check for panelizer in the node you could try something like this:

$node = \Drupal::routeMatch()->getParameter('node');
if ($node->hasField('panelizer')) {
  // Do stuff
}


Add a class to a Drupal table cell containing ['data'] In Drupal 8,  rendering Tables is still a lot like Drupal 7.  You build out  multi-dimensional arrays of rows and columns in PHP that Drupal transforms into a <tr> and <td>s respectively.  There is still this confusing Drupalism known as 'data' that lets you add render array elements as cell data (not to be confused with data attributes).

I've been given a site where the developer chose to use 'data' to render the contents of the cell, but I cannot figure out how to add a class to the <td> around the data.

I've read the source code and documentation for Table.php and I'm aware of the new #wrapper_attributes  but I cannot crack this.

I've tried at least four ways to add the class, and none work.

$table['row-' . $row_id] = [

  // Option 1: Class appears on <tr> tag
  '#attributes' => [
    'class' => ['option-1-row-attributes'],
    'id' => 'row-' . $row_id,
    'no_striping' => TRUE,
  ],

  // Option 2: Class appears on <td> tag of first column.
  'item' => [
    '#markup' => $row['my_item']->label(),
    '#wrapper_attributes' => [
      'class' => ['option-2-markup-wrapper-attributes'],
    ],
  ],

  // In the following section, the only item that works is
  // the class on the <a> tag.
  'edit_operation' => [
    'data' => [
      '#type' => 'link',
      '#url' => Url::fromRoute('my_module.my_route', ['item' => $row_id]),
      '#title' => $this->t('Edit'),
      '#attributes' => [
        // Option 3: Class appears on the anchor tag
        'class' => ['use-ajax', 'option-3-link-attributes'],
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => 700,
        ]),
      ],
      // Option 4: Has no effect.
      '#wrapper_attributes' => [
        'class' => ['option-4-data-wrapper-attributes'],
      ],
    ],
    // Option 5: Update: This appears to be the correct solution!
    // Class appears on the <td>.
    '#wrapper_attributes' => [
      'class' => ['option-5-wrapper-attributes'],
    ],
    // Option 6: Has no effect.
    '#attributes' => [
      'class' => ['option-6-attributes'],
    ],
    // Option 7: Has no effect.
    'class' => ['option-7-attributes'],
  ],
];

After writing out the question in general terms, I've gone back to test again, and have determined that Option 5 in the OP with '#wrapper_attributes' at the same level of the 'data' element does work.  I believe Drupal 8 was aggressively caching the table, because my changes were not showing up even after a drush cr.

The rules for adding classes to tables via backend PHP is:

Table class requires #attributes.
TR row class inside TBODY requires #attributes.
TD cell class inside TBODY requires #wrapper_attributes.
TR row class inside THEAD/TFOOT requires 'class' and 'data' containers.  Neither #attributes nor #wrapper_attributes work here.
TH/TD cell class inside THEAD/TFOOT requires 'class' and 'data' containers.  Neither #attributes nor #wrapper_attributes work here.
There is no way to add a class directly to a
 or
 tag without overriding a twig template.

Here is the most common example for adding classes to the
 &  tags inside the main
, as well as to the main
 tag itself:

$table = [
  '#type' => 'table',
  '#attributes' => [
    'class' => ['table-class'],
  ],
  'row1' => [
    '#attributes' => [
      'class' => ['tr-class'],
    ],
    // Table data cell using 'data' for renderable elements.
    'column1' => [
      'data' => [
        '#type' => 'link', // Or any other renderable thing.
        '#attributes' => [
          'class' => ['link-class'],
        ],
        // Other elements required to render the link go here...
      ],
      '#wrapper_attributes' => [ // Watch out!
        'class' => ['td-class'],
      ],
    ],
    // Table data cell using '#markup'.
    'column2' => [
      '#markup' => '' . $this->t('text') . '',
      '#wrapper_attributes' => [
        'class' => ['td-class'],
      ],
    ],
  ],
];

Note that the 'class' container will accept either a string or an array, but I suggest always using an array.

From here, the story gets more complicated.  If you need to add classes to the TR or TD/TH tags inside a THEAD/TFOOT area, the rules change completely.  Neither #attributes nor #wrapper_attributes work inside #header and #footer sections and trying to use them produces very strange effects.

The bare minimum structure for tables with header/footer data columns in Drupal 8 is this:

$table = [
  '#type' => 'table',
  // Produces

  '#header' => [
    'Header 1',
    'Header 2',
    'Header 3',
  ],
  // Produces

  'row1' => [
    'Body 1',
    'Body 2',
    'Body 3',
  ],
  // Produces

  '#footer' => [
    'Footer 1',
    'Footer 2',
    'Footer 3',
  ],
];

You must change the actual structure of the data and introduce two levels of additional multi-dimensional arrays, in order to leverage the 'class' array index which requires then also introducing the 'data' array index.  This applies both to the row element and the data cell elements, as seen in the following example:

$table = [
  '#type' => 'table',
  // This example works the same way for '#footer'.
  '#header' => [
    // First, introduce an extra level to the array to provide a
    // place to store the class attribute on the
 element inside
    // the
.
    [
      'class' => 'thead-tr-class',
      // Next place the columns inside a 'data' container, so that
      // the 'class' can be used.  '#wrapper_attributes' will not
      // work here.
      'data' => [
        // The following line produces data inside a
        // without any class.
        'Header 1',

        // The following lines produce data inside a
        // with a class: th-class.
        [
           'class' => 'th-class',
           'data' => 'Header 2',
           'colspan' => 2
        ],
      ],
    ],
  ],
];

The above example #header example produces:

      Header 1
      Header 2


Is it possible to only update one panel (or block) as a result of a the URL clicked elsewhere? Is it possible to only update the content in a particular panel as a result of a URL clicked elsewhere? (i.e no other pages get refreshed.)

I have created Views with context filters and would be using them in Panels and would prefer for the whole page not to have to be refreshed.

I'm particularly interested in how to retain the zoomed position of a OpenLayers map, but general advice welcome. (I would consider my OpenLayers use as being a 'side' case of my general question. I think the permalink co-ords option may help me here.)

If you want your links to stay unaffected, you need to:

Attach onclick javascript event to all links. In it, send AJAX query to server.
On server side detect when links are clicked on page supporting dynamic loading (referer is a good start). Send HTTP 204 status code to prevent full page reload. Do not avoid it by returning false from event mentioned in point 1 - if you will, address bar will not match content.
In response to ajax query, server should return what IDs are supposed to get replaced, and with what.
Javascript on page needs to accept and process data from point 3.

Little explanation: HTTP 204 from server tells the browser that http request is legit, but no data from the server is needed. Normally when you want to alter url in browser window, at least part before #, browser reloads page. This is to prevent theft page from impersonating bank page and so on. So you need server-side solution to actually allow address change without reload - target server will not impersonate itself. Or if it will, it's his right to do so.


When to use Views vs. a hardcoded query? I recently took over maintainership of a little module called Suggested Terms and received a feature request to replace the build-in queries with views.

I'm trying to weigh the pros and cons of using Views vs. a built-in query, and I don't really know whether it's worth introducing a dependency on another module, what the performance impact will be, etc.

What guidelines determine when a situation is best suited to Views, vs. using custom queries?

As posted in the issue thread he's asking about caching, which Views can give you -- or as @Chapabu mentions one could cobble together yourself.

1 thing Views does give you is an ability to Alter query or presentation of results relatively easily with hook_views_pre_execute or hook_views_query_alter to tweak the standard module to make it more customizable.

I could see some merits going this route. You could also supply the default listing as a default View provided by the module. Allowing other modules to copy/override it later in code ...


How to programmatically reference entities? I am trying to reference an entity within my hook, so that every time a new entity is inserted, I create another entity referencing the first entity. I have not yet found a working way to reference an existing entity in my "field_content" when creating a new entity.
My code looks like the below excerpt:
function ost_notifications_entity_insert(EntityInterface $entity) {
  if ($entity->bundle() == 'deadline' || $entity->bundle() == 'message') {
    $new_entity = \Drupal::entityTypeManager()->getStorage('node')->create([
      'type' => 'notification',
      'title' => $entity->label(),
      'field_content' => "referenced entity goes here"
    ]);
    $new_entity->save();
  }
}

As pointed out by 4k4 in the comments, the most robust way is assign an entity object to the field like so:
$new_entity = \Drupal::entityTypeManager()->getStorage('node')->create([
  'type' => 'notification',
  'title' => $entity->label(),
  'field_content' => [
    'entity' => $entity,
  ],
]);

For posterity, you can also do it by setting the field column (target_id) directly, but this is only useful if you have a saved entity. The first example will work for both new and existing entities.
$new_entity = \Drupal::entityTypeManager()->getStorage('node')->create([
  'type' => 'notification',
  'title' => $entity->label(),
  'field_content' => [
    'target_id' => $entity->id(),
  ],
]);


How to redirect user to an url when node is flagged? My problem is related to the Drupal 8 versions of these two modules: rules and flag.

What I want to achieve

Some node types on my site are offering a global flag as a link (for e.g. "report error" flag)
If the user clicks on it, he should be redirected to a special contact form. The flagged node URL should be submitted to an entity reference field automatically on the contact form too.

How I solved it in Drupal 7

In Drupal 7 there was a rules event "node is flagged" to trigger the redirect action. The flagging URL I could pass via Drupal 7 module "entity reference prepopulate" (which functionality is merged into core reference field in Drupal 8).

In Drupal 8 the rules event "node is flagged" seems not to exist.

Any idea how to realise a behaviour like described above in Drupal 8?

THX in advance,

Phil

You need to use the event, After saving new flagging

Add Condition of Flag, and enter flag machine name

Add action of Page redirect, enter the url where you want to redirect. Ex: /node/1

Important

In your flag settings, you need use a link type of Normal link, because it won't work with AJAX


How to automatically uninstall a module before running a Nightwatch test? I'm able to run Nightwatch without any problem but I would like to uninstall the Recaptcha module before running my test since the Recaptcha is preventing me from autosubmitting without passing the test.

I'm importing my DB in the phpunit.xml file in the core directory.

May be there are some hooks I could use?

I ended up using the Node exec command to call drush like this:

module.exports = {
  '@tags': ['picostat'],
  before: function(browser) {
    const { exec } = require("child_process");
    exec("drush pmu recaptcha")
  },
  'Check a dataset was likely created correctly.': (browser) => {
    browser
      .drupalRelativeURL('/node/add/dataset')
      .waitForElementVisible('body', 2000)
      .assert.containsText('body', 'Create Dataset')
      .setValue('#edit-title-0-value', 'Test Dataset')
      .click('#edit-field-dataset-input-method-file')
      .click('#edit-field-dataset-header-false')
      .setValue('input[name="body[0][value]"]', 'Test dataset body')
      .end();
  }
};


How to uninstall MailChimp Please help me uninstall MailChimp.

I disabled all MailChimp component modules, then I clicked uninstall. I got no error messages.

I then deleted the MailChimp folder from Sites/All.

Finally I ran phpMyAdmin and searched for MailChimp. I then deleted everything having MailChimp in it, BUT MailChimp still appears (though disabled) when I click modules.

I'm trying to get rid of MailChimp because it does not work and because SimpleNews does not work. I'm think that they are fighting each other.

I'm using Adquia Dev Desktop on my Win 7 computer with Open Outreach distribution.

Thanks!

The module will continue to be listed on the /admin/modules page as long as Drupal detects it on your filesystem within /sites/all/modules, /sites/default/modules, or another folder under /sites if you're running a multi-site setup. Just because the module is listed there doesn't mean it is enabled and running on the site.

Uninstalling modules is usually done the way you described it in the first line of your post. You go to /admin/modules to disable modules, then onto /admin/modules/uninstall to uninstall them. If the developer of the module did it correctly, you shouldn't have to do anything more than that. You will still see it listed in the modules page because it is still on your filesystem

I wouldn't recommend manually deleting anything out of the database unless you know exactly what it is that you're doing. You could mess things up When you disable and uninstall modules through the Drupal interface (or Drush), there are certain hook functions that get called which should remove data from the database.

What I would do is first is locate the module folder containing MailChimp. Ensure that you only have it in one place. If you had the module in different folders and only delete one, it will still be listed on the admin/modules page.

If you don't see it in those folders, re-install it. Then properly disable and uninstall it again the way you described WITHOUT touching the database yourself. This will probably undo any damage you could have caused in the database and ensure  that the data in the database is properly cleared out. Afterwards, delete the module folder from the filesystem and it should be gone.


Unable to save field collection order of collection that includes entity reference anymore I have a Drupal 7 site using field collection and entity reference. The collection includes one entity reference and a boolean checkbox. It is used to related "news" nodes to a page. The checkbox determines if it should show up in a carousel/slider.

We use this collection on a landing page and set it to an unlimited number of these field collections.

This used to work just fine. No idea what changed over the holidays but I came back in today with a message from the client about it. I got on the line with him and he showed it to me. I tried from my admin login and had the same problem.

No errors on the server or in watchdog. I checked apache, php, and mysql error logs. No errors on the page. This is hosted on Acquia for now.

I have cleared cache from the admin and drush. No luck. I am having the same problem with other nodes of this type. We do not use this for any other types of nodes though.

Any ideas as to what could be going on? This did work at one point. And it is clearly not saving these changes.

Actually found that this was caused by a JS error on the page. That explains everything. Fix the JS error, fix the problem.


Show 3 different Views displays for same exposed filter block or link Views displays? So, I have a View which uses exposed filters which has the exposed form style set to block.

In my first view display, I have one page display which shows the content as teaser view for all results. The teaser of the content type is styled with a custom template (node--my-custom-type.tpl.php).

I then made 3 tabs using the "Quicktabs" module and put my view page as one of the tabs, and 2 generic PHP blocks as placeholders for the other 2 tabs.

I setup a Page in "Panels" (Page Admin) so that I can have the block above and the quicktabs content below. I might change the layout later on but for now it works fine.

My 3 tabs are therefore:

List

This the View Page (Teaser view of the content type)

Map

Currently a block placeholder but should be linked to the same View Page results

Other

Currently a block placeholder but should be linked to the same View Page results

Now, I want to know how can I set the Map and Other tabs to be different View displays for my View that are linked to the same exposed form in my first views display?

Furthermore, the Map and Other tabs would need to just get the custom field: field_id and append the values of all the results to an iFRAME - so I really just need to output PHP and nothing else, no fields or anything.

I suppose I could do this via another custom themed display for the content type... e.g. adding another teaser display type named custom-teaser?

However, how would I "link" all the results between the displays using the same exposed filter block?

UPDATE 17/2/13:

So I tried the "Attachment" display, however that just added the field_id to my "List" tab and I don't want the field to appear on that tab.

UPDATE 4/6/13:

I haven't looked into fixing this issue for a while, but getting back to it now.

So I want the end result to be:

A page with exposed filter and 3 tabs that show each different "view display"

Tab 1: Show results as Gallery (custom CSS styling)
Tab 2: Show results on a Map (results have IDs, would need to get the IDs and pass them to the Map as an array or string as a comma separated list)
Tab 3: Show results on another map using different fields

The results should all correspond to the same exposed filter and should be updated when you update the filter. I currently use Quick-Tabs but I can change to something else to make the tab effect.

You can use only one exposed form of one of the displays. The other exposed forms should be set "as block", so they are not shown (as you will not set them active in the block configuration). As exposed forms work via GET-params, you simply can use the same "Filter identifier" for filters that shall share the same value.

An exposed filter in display2 with identifier type will use the same value as the exposed filter in display1 with the same identifier type.

This way you can control all three displays by only using one exposed form.


Does Drupal work with PHP 7? I have working development project of Drupal 7 using PHP 5.x. I changed the PHP version to PHP 7 using nginx webserver. It does not work and I have got the following error message:

 Fatal error: Uncaught Error: Undefined class constant
 'MYSQL_ATTR_USE_BUFFERED_QUERY' in
 C:\xampp-2\htdocs\d738\includes\database\mysql\database.inc:46 Stack
 trace: #0 C:\xampp-2\htdocs\d738\includes\database\database.inc(1689):
 DatabaseConnection_mysql->__construct(Array) #1
 C:\xampp-2\htdocs\d738\includes\database\database.inc(1479):
 Database::openConnection('default', 'default') #2
 C:\xampp-2\htdocs\d738\includes\database\database.inc(2570):
 Database::getConnection() #3
 C:\xampp-2\htdocs\d738\includes\cache.inc(348):
 db_escape_table('cache_bootstrap') #4
 C:\xampp-2\htdocs\d738\includes\cache.inc(329):
 DrupalDatabaseCache->getMultiple(Array) #5
 C:\xampp-2\htdocs\d738\includes\cache.inc(56):
 DrupalDatabaseCache->get('module_implemen...') #6
 C:\xampp-2\htdocs\d738\includes\module.inc(723):
 cache_get('module_implemen...', 'cache_bootstrap') #7
 C:\xampp-2\htdocs\d738\includes\module.inc(892):
 module_implements('system_theme_in...') #8
 C:\xampp-2\htdocs\d738\modules\system\system.module(2502):
 module_invoke_all('system_theme in
 C:\xampp-2\htdocs\d738\includes\database\mysql\database.inc on line 46

This error means that Drupal 7 is using obsoleted MySQL functions and it is not support with PHP any more!

However, I don't think Drupal still uses this obsoleted PHP extension. So I have a strange error as I think!

Search and edit your php.ini file, you must search this line:

;extension=php_pdo_mysql.dll

remove the ; and save the file, then restart your webserver.


How to find out who and when created taxonomy term Is it possible to know who and when created taxonomy term? Is that information stored anywhere?

I can't find it.

No, not in Drupal core. Unlike the Node entity, the Taxonomy term entity does not define a field that stores a field denoting ownership. You'll need to add your own field to your taxonomy terms to give them an ownership property.


How to create a custom markup for a views-block? I'm trying to understand the templating system of Drupal 8, allready did some basic stuff. My next step is trying to create a template to mark up a list generated by a view.

Here's what I've done so far:

I created:

A Content Type, with 3 fields: Title, Body, Link
Some (5) content entries with this Content Type
A View (Block) that lists all of the entries of this Content Type.

In Block layout I placed the View-block in a custom Region (werk_items)
(configured in the my-theme.info.yml file.)

Than I created a page template (page--node--23.html.twig) that includes this region, like so

{{ page.werk_items }}

When I go to the corresponding URL all works well and all of the content is displayed.

Now my question is: How to extract the variables to create a custom markup for the view content?

If you want to create custom markup/template for that particular view of content type then create file and name it as views-view-fields--[view-name]--page/block.html.twig and save it in template directory of your theme.

Now to get the variable just goto the content type -> manage fields. There you will find the machine names of fields. those are the variable you need to place in html structure like this
{{ fields.field-machine-name.content }}
 Hope this helps :)


Best approach to create a troubleshouting section? I am looking to create some kind of troubleshooting section on a website. Sort of like the Windows help with some sections, questions and answers.

I was thinking of doing this with a regular Book, and write a small form module which allows me to track the page with a "Was this information helpful or not?" question.

But are there possible alternatives, either existing modules or an approach which works best?

If you go down the book route then you can always use the flag module for the "Was this information helpful".

There is also the FAQ module which doesn't quite fit your use case but might be worth checking out just in case.


Sidebar formatting issues The Drupal 6 website I am working on is giving me some problems with the sidebars.

Here, my 'general info' sidebar is incorrectly showing 'home' sidebar info.

To the right is my 'divisions' sidebar which displays correctly [except for the >> next to probate, can't seem to find a fix for that issue]

I've tried to go through general info and compare the node hierarchy with that of divisions, making sure the settings are similar. I did not seem to find anything that would fix the issue for me.

Also if anyone could help me with why the ">>" 's show up seemingly randomly ( see 'Human Resources', 'Juvenile Delinquency Court', and 'Records management') These nodes do not have children.

First sidebar issue
Second sidebar issue

I checked your css file and it shows because of below css line, That arrow is activated for last li item, just delete or comment the lines.

#leftNav ul ul ul li.last a {
    background-color: rgb(190, 205, 222);
    background-image: url("img/blue/icon-leftnav.gif");
}

Probably you have to edit under themes folder or modules menu folder.

Go to your themes folder sites/all/themes/yourtheme/blue.css and search for url("img/blue/icon-leftnav.gif") or line 13 and comment the line and then clear the cache.


Create a drupal 6 views slideshow from a single content type that has both, image and video fields I need a little direction. I've created a content type that has both, images and videos attached to a node. I need to create a single frame slideshow that riffles through the mixed media. Currently, I'm using the Embedded Media Field as well as the ImageField to upload the content. I'd like to keep that within the same content type if possible. For the most part, the slideshow is working, yet it displays both fields together.  I want a single slide per media type.  I've excluded one type, but adding the field programmatically has been a little challenging.

The only way I've been able to somewhat achieve this is by creating individual nodes for the video and image content.  I then use views to filter for both types. Clumsy for the content editor, but I guess it works.


Bulk Update Meta Tags? I was wondering if it is possible to bulk update the meta tags for a particular content type? I have set the default to this: [node:field_description]. But all of the content is in the site. I'd prefer to not go through every node to paste that in the Meta tags Description field.

Is there a bulk operation to put that placeholder token into all the nodes of a particular content type?

Using this module: https://drupal.org/project/metatag The Metatag module on Drupal 7.

You may use combination of Metatag, Views and Editable Fileds.

Configure node types to use own fields for meta tags like
keywords, description, abstract, etc. and create it. use Field
Permission to restrict access to this fields.
Configure Metatag to    use newly added fields for filling metatags
on Metatag admin page    or node type page.
Create view with table    display, add    metatag-fields. Choose
formatter "Editable" on    each field    settings.
Set path for this    view like admin/config/search/metatags/massedit. Save view and now you    can mass    edit
any fields.

Also you can try Editable Views module.