Installation profiles: add module/theme search path? I'm trying to create a "base" installation profile with the modules and settings i need for every project which the specific project-profiles should derive from. It's no problem to run the install-part of my basic profile, but is there a way to use modules and themes that are stored in the 1st profiles folder?

Currently, there is no way to "inherit" that way between profiles. My team uses a small script that symlinks the modules directory from the base profiles into the modules dir of the subprofile, to solve this.

So the structure becomes

profiles/base-profile/modules
profiles/base-profile/modules/ctools
profiles/sub-profiles/modules/modules         <-- Symlink to base-profile/modules
profiles/sub-profiles/modules/modules/ctools  <-- From symlink
profiles/sub-profiles/modules/views


What are dependencies in the context of a user role in Drupal 8? In the process of wrapping my head around Drupal 8's configuration system (which is awesome, by the way), I came across this:

YAML file (from core/modules/user/config/install/user.role.authenticated.yml)

id: authenticated
label: 'Authenticated user'
weight: 1
langcode: en
status: true
is_admin: false
dependencies: {  }

Now of course I understand module dependencies, but what might be set here as a dependency for a user role configurable and what would it mean?

Thanks!

As Ivan Jaros said, all config entities can have dependencies on modules and other config entities, both automatically derived based on code (e.g, a field depends on its field storage and entity bundle it is added) and manually set (in an enforced sub-array with the same structure)

Dependencies ensure that the required dependencies are installed and they are installed in the right order. Which is important if you import a new node type with fields, display configurations, views that list them and so on.

User roles currently don't have automatically derived dependencies, but they actually should have. They should depend on the modules that provide the used permissions, which is a bit tricky since permissions don't give you that information especially not for dynamic ones that depend on node types, filter formats and so on. That's why the key is always empty for them.

We should open a core issue to try and track this better, that would allow roles to clean up permissions when e.g. a node type is deleted or a module is installed. But it's not a major problem since nothing happens if those permissions don't exist anymore.. it's just a string and if nothing asks for it, then nothing happens with it. The only problematic thing is that you a) end up with cruft in those config objects and b) the permissions could get active again when you e.g. delete a node type and add again with the same name. You might not expect your permissions configurations to survive that.


Are there any modules where you can import H2Database data into drupal 7 as nodes? I'm working with the java h2 database engine and there is data that i want to query/import everyday. Is there a module or how would I go about importing such data into drupal 7 as nodes?

Your best bet is likely to use the Migrate module and a custom php H2 database driver.

This is not easy.

You can follow this to get php working with PDO and Java H2. http://www.webdevelopersdiary.com/1/post/2012/07/jamp-an-ultra-portable-php-web-server-and-database-stack-in-java.html

From there you will need to write a class for the migrate module that extends the migrate source class


How to create a view that searches nodes and users at the same time? I'm creating a custom search to my site using Views.

I want to search both nodes and users at the same time, with exposed filters like this:

[ ] events
[ ] bands
[ ] products
[x] users

But when creating views I have to specify if I want to list nodes, or users, or files etc.

How can I search through two tables at same time?

You can't really do what you ask the way views is built, not without overriding a lot of classes etc which probably would be more complex than building it all by hand.

A simple workaround would be to create two views and thus have two forms. Then you can show the form for user search when user is selected and node search when one of the node types is selected. That would also allow you to create custom filters for the user/node search, like date posted or last login.

You can use some simple JS to control hide/display of the forms.


Where to translate SHOW DETAILS from a display view? I would like to find out where would I be able to translate the SHOW DETAILS/HIDE DETAILS menu options a DATATABLES FORMAT view.
We are using Drupal 7, and I have tried to find it in the Configuration options, with no success. Would this need to be changed in the back end of Drupal?

This string seems to be a part of the interface, so you can translate it through Configuration » Regional and language » Translate interface (/admin/config/regional/translate/translate).
You have to enter the exact capitalisation into the search as is written in code (it's case sensitive), not necessarily what you see on the screen (CSS can affect what capitalisation is used in display).
The string won't appear on this list unless you have visited a page with that string in another language (other than English) so Drupal picks it up and makes it available for translation.


how do i create a site that allows users to create and view events? I'm creating a site where users should be able to create events that are accessible by all users of the site on an "events" page.....whats the best way to do this?
thank you very much!

It is very simple to do this task.

You need to create a new content type. add to it corresponding fields and set to it create/edit/delete permission for anonymous and registered users in the permissions page.

As I see, your are a newer on Drupal. I advice you to go throught the documentation to learn about Drupal, its conception and how it works.


drush migrate:upgrade not behaving as expected I'm working with the Migrate Tools modules for the first time. Specifically, I'm trying to use the Migrate Upgrade module to import users and roles from an old Drupal 7 site to a new, Drupal 8 rebuild of that site.

Per these instructions, I'm running this command to configure the migrations:

drush migrate:upgrade --legacy-db-url=mysql://olduser:password@localhost/oldschema --legacy-root=http://olddomain.test:8888 --configure-only

When I run drush migrate:status upgrade_d7_user,upgrade_d7_user_role immediately after that command, here's what I see:

----------------------------------------- ---------------------- -------- ------- ---------- ------------- ---------------
 Group                                     Migration ID           Status   Total   Imported   Unprocessed   Last Imported
----------------------------------------- ---------------------- -------- ------- ---------- ------------- ---------------
 Import from Drupal 7 (migrate_drupal_7)   upgrade_d7_user_role   Idle     4       4          0
 Import from Drupal 7 (migrate_drupal_7)   upgrade_d7_user        Idle     197     196        0
----------------------------------------- ---------------------- -------- ------- ---------- ------------- ---------------

This isn't what I expect to see. It looks like it has already imported all roles and all users (except for the admin user), and has none left to process. I expect to see zero imported at this point, since I used the --configure-only flag, and I haven't yet issued the Drush command to actually run the migrations.

Looking in the Drupal backend, I don't see that anything has actually been imported.

If I go ahead and run these commands:

drush migrate:import upgrade_d7_user_role
drush migrate:import upgrade_d7_user

...then I see:

[notice] Processed 0 items (0 created, 0 updated, 0 failed, 0 ignored) - done with 'upgrade_d7_user_role'
[notice] Processed 0 items (0 created, 0 updated, 0 failed, 0 ignored) - done with 'upgrade_d7_user'

It seems like the Migrate Tools thinks that the imports have already been completed – but they haven't.

Any ideas? Has anyone run into anything similar before?

I have been restoring the new (target) site's database from a snapshot periodically, because I'm learning the migration process as I go. So maybe that has hosed something up.

The very first time I ran migrate:status, I saw what I expected – some records queued, but none imported yet.

And the first time I ran migrate:import, it did import the records as expected.

So it seems like something about that previous import got "stuck" somewhere in the system. But I've taken increasingly drastic measures to burn my development site to the ground and rebuild from scratch – to no avail.

Is there perhaps something being cached by the Drush CLI itself?

Appreciate any suggestions. Thanks.

I figured it out!

I just needed to run drush migrate:rollback. That put Drupal back into a state where it understood that the migrations hadn't actually been run yet.


Adding CSS class to flagged node teasers I have tried the following code corolla theme's template.php

/**
 * Implements template_preprocess_node().
 */
function corolla_preprocess_node(&$variables) {
  $flag = flag_get_flag('sold'); // Machine name of your flag.
  if ($flag && $flag->is_flagged($variables['node']->nid)) {
    $variables['classes_array'][] = 'node-flag-sold';
  }
}

This is supposed to add CSS class="node-flag-sold" next to "node". But looking through my firebug, there arenosuch classes added.

Please note, that my node--content-type.tpl.php is custom rewritten.  Do I need to add anything there?

The preprocess code looks reasonably correct.

Make sure you're printing out the $classes variable in your custom node--content-type.tpl.php

e.g, in the wrapper div here:

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

<!-- Node template content ... -->

</div><!-- /.node -->

If curious, $variables['classes_array'] is flattened into $variables['classes'] in template_process with

// Flatten out classes.
$variables['classes'] = implode(' ', $variables['classes_array']);

In D7, process functions are introduced, running after preprocess functions.


How can I disallow spaces in usernames? Drupal allows spaces in usernames, is there an easy way to stop this?

Also, where is the documentation on the username specs? What are the min/max lengths and which characters are allowed?

The best way to handle this is to implement hook_form_FORM_ID_alter for the user sign up and edit forms and append your own validator to check for spaces in the username field.

As for the length of a username, the minimum is 1 character and the maximum is 60 - as per the db schema.


BaseFieldDefinition change DB column type In a content entity definition, I've got the following:

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  $fields = parent::baseFieldDefinitions($entity_type);

  $fields['frames'] = BaseFieldDefinition::create('string')
    ->setLabel(t('Frames'))
  ->setDescription('A serialized representation of the given frames');

  return $fields;
}

This is creating the column type in the database as varchar, with a maxlength of 255. I need the column to be type text, as the length will be unknown, and often more than 255. Does anybody know how to create a BaseFieldDefinition that becomes type 'text' in the database when the content entity is enabled?

You can use BaseFieldDefinition::create('string_long') to get a LONGTEXT type field without the extra__format column.


Display specific nodes on specific pages How do I display specific nodes from a view on specific pages?

For example, I create a CCK field ("Display on node id:") for the content type Ads, and put there IDs of content type Basic page where I want display this Ads.

Is there to achieve this without additional modules?

Create a block display mode for that view (the view that display ads) and place that block on basic page node types.

In the view you should add a Contextual filter (under Advanced settings) and validate it as the node ID from URL. Then add a filter that selects only ads for that node ID.


Getting data into a template How do I add data into a table into my node--course.tpl.php?

I would like to mimic the table on this page where it has course ID and info:
http://cie.austin.utexas.edu/uex-cm/courses/acc-310f-foundations-accounting-online

to look like this:
http://uex.webhost.utexas.edu/coursedetails.cfm?OutID=3040

Should I use a view or a block?

For the first image if its content type you can create a view of that content type with fields
as shown in the table.


How do I remove variables from the variable table when my module uninstalls? I'm working on a Drupal 6 module that adds some variables to the variable table. How can I go about having those variables removed from the variable table when the module is uninstalled?

Keep track of your variables and add appropriate variable_del() calls within an implementation of hook_uninstall():

function foo_uninstall() {
  variable_del('foo_variable1');
  variable_del('foo_variable2');
}

As hook_uninstall() is an installation hook, it needs to reside in your module's .install file (e.g. foo.install).

You ought not to delete all variables prefixed with your module's name as namespace collisions will come back to bite you. For example, if your module's name is foo, you might think you should just poll the variables table for all variables prefixed foo_. But what if I write a module named foo_awesome? You'd delete my variables, too. That wouldn't be nice.


How to set the profile picture validation in profile 2 module in drupal 7? I am using profile2 module in my site. I want to hide the profile picture upload option at the time of registration. And after click on confirmation mail, i want to upload at least one profile picture means want to apply validation here. How to set the validation in profile picture that validation shows inside not at the time of registration. Please help. Thanks in Advance

Just create the template of your registration page and need not print the upload image field over there and when user will register your self print that field to the edit profile form page from where user can upload the picture ..

Thanks


Create a views "exposed filter" to compare two fields First of all:

I know that there's a static filter with Global: Fields comparison that would do it. But I need an exposed filter in views to fullfill my needs.

Let's say I have a table with 3 cols: "nid" | "changed" | "another datetime".

Now I want to have an exposed filter as a select list with options "none", "old" and "new".
If "old" is selected, show rows where "another datetime" > "changed".
If "new" is selected, show rows where "another datetime" < "changed".

I've been looking for a solution for multiple hours.

Solution 1

Make use of views php to do the compare with the help of https://www.drupal.org/project/views_php

In that case you have to write some code which is executed on each row, in the end it will work but it is very bad in maintaining. You do not have any integrated editor for error code checking etc etc. It is a solution but I do not recommend it.

Solution 2

Make use of the hook views_post_execute with parameter of the view name.

function YOURMODULENAME_views_post_execute(&$view){

For easy maintenance start with a switch

switch ($view->name){

    case "YOURVIEWNAMEA";
    case "YOURVIEWNAMEB";
    case "YOURCASEVIEW";

    foreach ($view->result as $row => $rowinfo) {

      // put here your code to do something with each result.

       // E.G Delete a value in the result of the view making use of unset statement
        unset ($view->result[$row]);

      }


How to Add more option for type radios use Ajax in Drupal 8 Hi I build Add more for radios  when click button load ajax. This ajax only add more options for radios . But not working , how to build used ajax add more options for type radios form ? Thanks

This code example my demo:

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class DemoForm extends FormBase{

    public function getFormId()
    {
        return 'DemoForm';
    }
    public function buildForm(array $form, FormStateInterface $form_state,$param = array())
    {
        $form['wrapper_data'] = array(
            '#type' => 'container',
            '#attributes' => array('id' => 'wrapper_data'),
        );
        $form['wrapper_data']['data_media'] = array(
            '#type' => 'select',
            '#title' => 'List Media',
            '#options' => array('aaa','bbb','cccc'),

        );
        $form['wrapper_data']['load_more_data'] = array(
            '#type' => 'button',
            '#value' => 'Load More',
            '#ajax' => array(
                'callback' => '::AjaxLoadMore',
                'wrapper' => 'wrapper_data',
            ),
        );

        return $form;
    }

    public function AjaxLoadMore(array &$form,FormStateInterface $formState){

        $form['data_media']['#options'] += array('bbbb'); // Want Add more options for radios

        return $form['wrapper_data'];
    }
}

Here is the complete code example:

<?php
/**
 * @file
 * File: src/Form/MyExampleForm.php
 * Contains \Drupal\mymodule\Form\MyExampleForm.
 */
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class MyExampleForm extends FormBase {

  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'example_form';
  }

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['wrapper'] = array(
        '#type' => 'container',
        '#attributes' => array('id' => 'data-wrapper'),
        );

    /* // or:
    $form['wrapper'] = array(
      '#type' => 'fieldset',
      '#title' => $this->t('Example title'),
      '#tree' => FALSE,
      '#prefix' => "
",
      '#suffix' => '
',
    );
    */

    /* // or:
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';
    */

    $form['wrapper']['data_media'] = array(
        '#type' => 'radios',
        //'#title' => 'Title',
        '#options' => array('aaa','bbb','cccc'),
        );
    $form['wrapper']['more_data'] = array(
        '#type' => 'button',
        '#required' => TRUE,
        '#value' => 'Show more',
        // @see: https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.3.x
        '#ajax' => array(
          // The callback to invoke to handle the server side of the Ajax event.
          'callback' => [$form_state->getBuildInfo()['callback_object'], 'ajaxLoadMore'],
          // or: //'callback' => [$this, 'ajaxLoadMore'],
          // or: //'callback' => '::ajaxLoadMore',
          // @see: http://api.jquery.com/category/manipulation/
          //'method' => 'replace', // May be: 'replaceWith' (default), 'append', 'prepend', 'before', 'after', or 'html'.
          // The HTML 'id' attribute of the area where the content returned by the callback should be placed.
          'wrapper' => 'data-wrapper',
          ),
        );
    $form['wrapper']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Confirm'),
        );

    return $form;
  }

  /**
   * Ajax handler for loading more radio options.
   */
  public function ajaxLoadMore(array &$form, FormStateInterface $form_state){
    // Add more options for radios.
    $trigger = $form_state->getTriggeringElement();
    if ($trigger['#value'] == 'Show more') {
      $form['wrapper']['data_media']['#options'] += array_merge($form['wrapper']['data_media']['#options'], ['bbbb']);
    }
    return $form['wrapper'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $trigger = $form_state->getTriggeringElement();
    if ($trigger['#type'] === 'submit') {
      if (is_null($values['data_media'])) {
        $form_state->setErrorByName('data_media', t('Please select the option!'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Your form has been submitted.'));
  }

}


hiding field -reference option limit Helloo !
I am using the D7 reference option limit module. I have two fields "primary" and "secondary" and I managed to reduce the choices of secondary based on the value of primary using this module. Both of them are required field in the user registration form.
I have a small question, when I set no value for primary, I get for the secondary field: No options are available for the current form values. Try selecting different values for the following fields: Primary.  This is the good behaviour that I want but I want to hide secondary when no value is set for primary instead of displaying this message..
Is that possible? In other words I want to keep secondary hidden until primary has a value.

have you try any alter functions to implement ?
if you can try with alter then try #states in hook_form_alter() to hide field, if primary field default value is empty/null.
here is e.g
/**
 * @param type $form
 * @param type $form_state
 * @param type $form_id
 * Implements hook_form_alter()
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'form_id') {
    // Hide secondary field.
    if (isset($form['secondary_field'])) {
      $form['secondary_field']['#states'] = [
        'visible' => array(
          'input[name="primary_field"]' => array('!value' => ''),
        ),
      ];
    }
  }
}

'input[name="primary_field"]' => array('!value' => ''), change this as per need i.e if its select list then 'select[name="primary_field"]' => array('!value' => ''), etc.
hope this will solve your issue.


What is the equivalent of a call to drupal_http_request()? In Drupal 7 I am using the following code.

$url = 'testdomain/url';
$response = drupal_http_request($url, array('method' => 'POST', 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8')));
if ($response->code == "200") {
  $result = $response->data;
}

What is the equivalent code I should use on Drupal 8?

Finally i find a code in https://api.drupal.org/api/drupal/core%21includes%21install.core.inc/8 (1375)

and its working for me :)

 try {
    $response = \Drupal::httpClient()->get($uri, array('headers' => array('Accept' => 'text/plain')));
    $data = (string) $response->getBody();
    if (empty($data)) {
      return FALSE;
    }
  }
  catch (RequestException $e) {
    return FALSE;
  }

Hope this will help for some one


How to call preprocess functions from my custom module I have created a custom module that declares a custom image formatter. Now I need to call the Core image module preprocess function 'template_preprocess_image_formatter'. How would I do that?

I tried to add it in the list of preprocess functions of my custom theme but it doesn't fire unless I clear the cache:

 /**
  * Implements hook_theme().
  */
 function foo_theme() {
    'image_formatter_foo' => [
          'variables' => ['item' => NULL, 'item_attributes' => NULL, 'image_style' => NULL],
          'file' => 'foo.field.inc',
          'preprocess functions' => [
             'template_preprocess_image',
             'template_preprocess_image_formatter_foo'
          ]
    ],
 }

Looking at template_preprocess_image_formatter, I would try the following code below.

Replace mymodule with the machine name of the module. This assume foo is the machine name of your image formatter.

mymodule_preprocess_image(&$variables) {
  /* processing logic */
}

mymodule_preprocess_image_formatter_foo(&$variables) {
  /* processing logic */
}

I also recommend reviewing Drupal 8's Core Image module as it has some of the files that call the hooks you need.

image.field.inc contains template_preprocess_image_formatter
template_preprocess_image


How do I use the Hierarchical Select module? I'm a total newbie in Drupal.

I have successfully installed Drupal 7 in my WAMP installation, downloaded the Hierarchical Select module, put it in the sites/all/modules folder, and enabled it.

How can I now use it? I don't see any option.

Solution

It seems that the read me file for Drupal 7 needs updating. Things have changed from Drupal 6 to Drupal 7. You will find Hierarchical Select available as a widget for the term reference field. To use it, select it at for the field you want to use it for. Also you should use alpha releases at your own risk. They are expected to have bugs.

README

You should read the README file!

From the Drupal 7 version:

  Installation

  1) Place this module directory in your "modules" folder (this will usually be
   "sites/all/modules/"). Don't install your module in Drupal core's "modules"
  folder, since that will cause problems and is bad practice in general. If
  "sites/all/modules" doesn't exist yet, just create it.

  2) Enable the module.

  3) If you want to use it for one or more of your vocabularies, go to
  admin/content/taxonomy and click the "edit" link for a vocabulary. Now scroll
  down and you'll find a whole range of Hierarchical Select settings. All
  settings are explained there as well.


Hide title in Inline Entity Form with Automatic Nodetitles module? Is there a way to suppress a node's Title and Status fields when used in the Inline Entity Form module's editing form? I keep having use cases for a very clean and slim "add one or more" subform to create lists of related entities.

You can use hook form alter in your custom module. For example

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_form') {
    $form['title']['#access'] = FALSE;
   }
 }

Or better use hook_form_FORM_ID_alter. For example

function my_module_form_node_form_alter(&$form, &$form_state, $form_id) {
    $form['title']['#access'] = FALSE;

 }


Feeds import from Restful Web Service module output I have a D7 website, which expose a node through the module Restful Web Service https://www.drupal.org/project/restws

It does exposed my website node in Json format.  The only issue I have, is the photo field, which has multiple images  but JSON output from RESTWS is only expose the photo file id, not the file name.

My question, is there're plugin for the Feeds module that I can use to convert the file ID to a file name, so the feed can import that.  Or is there other way that I can use to directly import the file fid to Drupal.

Here's a little info about my website:  The user can list their content on bronze plan content type, and then they decide to upgrade to silver content type, what I'm doing in the background, is export the bronze content type through Restful Web Service and re-import through feeds to silver content type.

I just want to post my plan for everyone to review and response.  After days of no response, it does mean I'm having a crazy idea.

I've re-think my solution and came up with writing my own custom module to do the data copy from one content type to another.  It was easy than I expected.  Copy of data from one content type to another is very easy if the both field type are the same.  It's a straight assign of field from one node object to another content type object.  That's it.


Comments for each image in a gallery I'm trying to setup a gallery where users can comment under each image. What is the best way to do this? Thank you.

Here is a simple setup:

You need two content types:

Gallery
Image

The gallery content type will contain a body (gallery description) field.

The image content type will contain:

Image field
A reference field

The reference field will reference a gallery content type.


How can I find the form ID of a form? How do I get the form id of my form? I've just begun to make my modules and I'm at a standstill. I got this code from someone else and am trying to customize it:

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form id for the node form') {
    $form['#submit'][] = 'my_custom_submit_handler';
  }
}

Finding FORM ID without installing module

Finding the Form ID is very easy no need to install modules and all

STEP 1: Open you from go to its edit page(OR inspect your form).

STEP 2: if its a node form find "node-form" in the inspect element

 check you are in the form element.

STEP 3: see attached image the highlighted green text is the ID of the form

STEP 4: IMPORTANT Finally if you want to use it in hook_form_alter() replace the hypen with underscore

For example: yourform_id_with_content_type_name_form

Like wise you can find id of any form in drupal all you have to do is inspect->find form element and search for the ID attribute and use it

Hope it helps :)


Using hook_theme() when there is a preprocess We had a outside company help us with our Drupal version of our site. They created the code below.

Since then we have hired another company that seems to be more professional about there code and standards.

The code below is the entire code of the module. The new company suggested that we "Implement hook_theme and create a template for alerts, move markup from
hook_preprocess_page to the template."

I understand a bit about Drupal modules, but I'm unsure how to accomplish what they are suggesting.

Can someone help me in this regard?

<?php

function foo_alerts_preprocess_page(&$vars) {
  $vars['alerts'] = '';

  if ($nid = foo_alerts_check_alerts()) {
    $node = node_load($nid);

    if (isset($_COOKIE['alert'.$node->nid]) && $_COOKIE['alert'.$node->nid] == 'closed') {
      return;
    }

    $html = '
nid.'">
';
    $html .= '
News Alerts:
';
    if (isset($node->field_link['und'][0]['url'])) {
      $html .= l($node->title, $node->field_link['und'][0]['url'], array('attributes' => array('title' => $node->field_link['und'][0]['title'], 'class' => array('alert-link'))));
    } else {
      $html .= '' . $node->title . '';
    }
    $html .= '';

    $html .= '

';
    $vars['alerts'] = $html;
  }
}

function foo_alerts_check_alerts() {
  return db_query("SELECT nid FROM {node}
    LEFT JOIN {field_data_field_dates} ON entity_id=nid
    WHERE type='alert' AND field_dates_value < NOW()
    AND field_dates_value2 > NOW() AND status = 1 LIMIT 1")->fetchField();
}

So, hook_theme is where you define your theme implementations and templates to use for them. In your case, that would look something like:

foo_alerts_theme() {
  $module_path = drupal_get_path('module', 'foo_alerts');
  return array(
    'alerts_theme_name' => array(
      'path' => $module_path . '/templates',
      'template' => 'alerts-theme-template-name',
      'variables' => array(
        'node' => NULL,
      );
    ),
  );
}

Your template file, named alerts-theme-template-name.tpl.php goes in the templates folder in your foo_alerts module folder. In your page preprocess you're going to pass in the node loaded from the alerts function to the theme function, so that would look like this:

function foo_alerts_preprocess_page(&$vars) {
  $vars['alerts'] = '';

  if ($nid = foo_alerts_check_alerts()) {
    $node = node_load($nid);

    if (isset($_COOKIE['alert'.$node->nid]) && $_COOKIE['alert'.$node->nid] == 'closed') {
      return;
    }

    $vars['alerts'] = theme('alerts_theme_name', array('node' => $node));
  }
}

That leaves all of the non-template logic still in the preprocess function, and returns the output of theme(), which will be the html from your template. Your template would then be something like this:

<div id="alert-bar" rel="<?php print $node->nid; ?>">

News Alerts:

    <?php if (isset($node->field_link['und'][0]['url'])) : ?>
      <?php print l($node->title, $node->field_link['und'][0]['url'], array(
        'attributes' => array(
          'title' -> $node->field_link['und'][0]['title'],
          'class' => array('alert-link'),
        ),
      )); ?>
    <?php else : ?>
      <?php print $node->title; ?>
    <?php endif; ?>

Does that all make sense? Do you see how the code the old dev team left you with got turned into this? If you have any questions, let me know and I'll try to explain better what I did.


Get bundle's default publication status I would like to retrieve whether the bundle of a node is supposed to default to published. I am able to successfully get the bundle of the node in question.

$bundle = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->load($node->bundle());

However, I am unable to retrieve information about default status of the bundle. When I use Devel's dsm() function in order to see the array for $bundle, the "field" [status], which I would have thought was the value I want, doesn't change. It remains 1. I tried changing the publication status of the node in question as well as changing the default value for the content type publication status, but neither of these affect this value.

How can I get the bundle's default publication status? What am I missing?

Edit: I am also now using $bundle->get('status') to get the specific field referenced above.

The default value is stored in the field's config, rather than the node type's. Currently it's not possible to get that value without having a node to work with.

This is alluded to in NodeTypeForm::form() (and also the save() method of the same class):

if ($this->operation == 'add') {
  $form['#title'] = $this->t('Add content type');
  $fields = $this->entityManager->getBaseFieldDefinitions('node');
  // Create a node with a fake bundle using the type's UUID so that we can
  // get the default values for workflow settings.
  // @todo Make it possible to get default values without an entity.
  //   https://www.drupal.org/node/2318187
  $node = $this->entityManager->getStorage('node')->create(['type' => $type->uuid()]);
}
else {
  $form['#title'] = $this->t('Edit %label content type', ['%label' => $type->label()]);
  $fields = $this->entityManager->getFieldDefinitions('node', $type->id());
  // Create a node to get the current values for workflow settings fields.
  $node = $this->entityManager->getStorage('node')->create(['type' => $type->id()]);
}

It goes on to set the options arrays for the checkboxes using that node:

$workflow_options = [
  'status' => $node->status->value,
  'promote' => $node->promote->value,
  'sticky' => $node->sticky->value,
  'revision' => $type->isNewRevision(),
];

So, for now at least, you'll probably need to do the same thing.


Moving drupal site to the root of the server I have finished my drupal site and about to launch it in the end. Now everything is in a subdirectory called www.mysite.com/drupal_test, to do that, I had to change one line in the .htaccess file:

uncomment #RewriteBase /drupal

and change to

RewriteBase /drupal_test

I realised that .htaccess and some of other files in drupal are hidden files. I just blindly uploaded it and can't really see it in the ftp.

Now, I am ready to move everything to the root. I suppose I have to change that line back. But will I lose all the hidden files if I move? I can re-upload .htaccess, but there so many other hidden file that I don't know, will I lose them?

Is there anything else I should do when I move the directory or is there a better/proper way to do so rather than dragging and dropping all the files to the root?

Sorry if the question is stupid, I only have one day left to do this and I am terrified by moving drupal sites.

I guess you can upload the new .htaccess file and change back the line #RewriteBase if you have modified only one line of the .htaccess file, there won't be any problem and even if the file exists there it will give you a option to replace.

Few things that you have remember while moving your site to root folder are:

Put the site into maintenance mode so that user's posts, comments etc. doesn't gets lost.
The #RewriteBase is uncommented when we use the drupal from the subdirectory. So if you are moving it to the root folder than I guess no need to modify this line. (Anyways you try you way also).
If you have modified/using the $base_url in setting.php than don't forget it to update as well.log
Clear the complete cache, and check the watchdog table data (dblog) at "/admin/reports/dblog" to make no page or anything is having issue.


How to set Time Limit on Comment Edit I need to set time limit to edit comment, like Stack Overflow strategy that sets 5 minutes time limit. The Time Limit on Comment Edit asked the same question and the Edit Limit was proposed.

In admin/people/permissions I allow authenticated users to Edit own comments and also Installed Edit Limit module. This is the configuration

Despite of letting the contents to be editable in 3 minutes, Users are still unable to edit their own comment right after sending their comments. What is the problem? Is there any other solution?

On my site, all I have to do to make this work is to enable the permission  "Edit own comments" for the role, and set the time limit.  If you've done this, it should work.  This is how it looks like when working:

The only thing I can suggest is that you go over your settings again.


How do I update the configuration of a module? I'm building a custom module in Drupal 8. It includes some YAML config files.
As I develop I need to change and add to the config, e.g. to add another field onto my custom entity.
At present the only way I've found to get Drupal to notice the changes is to uninstall the module and re-install it.
Is there a way to get Drupal to check that the config files provided by modules is the same as the active config, and if not, update the active config? How are module updates handled? In D7 hook_update_N would be used to add fields using PHP, but it looks like this should be handled by the CM in D8?
Things I've tried after updating the yml files in the module:

drush cr, config sync.

manually copying all the updated config files into sites/default/files/config_XXX/staging/ - but this gives this error "The staged configuration cannot be imported, because it originates from a different site than this site. You can only synchronize configuration between cloned instances of this site.".

manually importing the files one by one using the config manager. This works, but obviously there must be a more automatic way.

[EDIT] manually use the config_update module to inspect changes and 'revert' to the module's config. Again, this is manual.

EDIT: From Managing configuration - do's and don'ts

DON'TS
Try to change the active configuration on your site by changing files in a module's config/install directory. This will NOT work because Drupal will only read from that directory when the module is installed.

...but changes there are going to happen, unless modules are bound to whatever config they needed in their first ever release, and may never ever update or add config.
Thanks in advance.

As mentioned in the original question, and follow-up comments, there are a variety of contrib modules and manual methods to accomplish this.

To do it automatically, or in a custom fashion, I think hook_update_N() is still probably the most viable option.

For instance, this is an example from the Head 2 Head to update system.site to set the default_langcode:

  $config_factory = \Drupal::configFactory();
  $langcode = $config_factory->get('system.site')->get('langcode');
  $config_factory->getEditable('system.site')->set('default_langcode', $langcode)->save();

You can also read in config (recommended only for adding new config, not necessarily updating or overriding config that may have been customized):

  $source = new FileStorage($path);
  /** @var \Drupal\Core\Config\StorageInterface $active_storage */
  $active_storage = \Drupal::service('config.storage');
  $active_storage->write($name, $source->read($name));

where $path is the absolute path to the my_config.foo.yml file.


db_update not working as expected I am trying to develop a custom module; so far it works as it should. The only problem is I can't seem to get the MAC address to remain unchanged on update. It keeps getting the device ID number instead of the MAC field. How do I avoid the MAC address is changed?

function device_delete_request($uid = null, $macaddress, $device_id = null) {
  db_update('argon_user_stuff')
    ->fields(array(
      'id' => $device_id,
      'uid' => $uid,
      'macaddress' => $macaddress,
      'deletedmacaddress' => $macaddress,
      'updated' => REQUEST_TIME,
      'deleted' => REQUEST_TIME,
      'active' => 0
    ))
    ->condition('uid', $uid, '=')
    ->condition('id', $device_id, '=')
    ->execute();

    // Set the message and return to the user's profile page
    drupal_set_message('Device deleted');
    return drupal_goto("user/{$uid}/devices");

}

Is that mac address is a required field?
It may be possible mac address passing to this function not getting change, you may need to debug mac address before the function call.


Scope javascripts to be outside admin Now when we are almost there using purely YML files to include JavaScript, is it possible to include javascripts everywhere except for in the Drupal administration? Beta 4 does not allow the #attached property anymore, so this solution would be best suited in a YML setup.

Sure. Drupal 8 still allows #attached, the difference is just that you specify a library instead of a specific javascript file, but that is irrelevant for your question.

You can implement hook_page_attachments() and ask the route context if this is an admin route.

/**
 * Implements hook_page_attachments().
 */
function yourmodule_page_attachments(&$page) {
  // This returns TRUE for admin paths.
  if (!\Drupal::service('router.admin_context')->isAdminRoute()) {
    $page['#attached']['library'][] = 'yourmodule/yourlibrary';
  }
}


How get views advanced dynamic URL contextual filter to work with full taxonomy path? I've tried all settings, with joint paths etc...but I just can't get the filter working properly, I know it's a settings thing, watched a whole bunch of videos but can't put my finger on it!

This is for advanced contextual filter, the dynamic one that can change depending on URL, not the static one.

Like this:

Animals
-Pets
-Farm

Path is:

localhost/animals/pets/cats.htm
localhost/animals/farm/cows.htm

I would like the filter animals/pets to show cats.htm content

I would like the filter animals/farm to show cow.htm content

I can get the filter working with single taxonomies, but not with full path.

animals works, but not animals/farm and not animals/pets

Attaching an image with the screen where I should set this up

You must use 2 contextual filters

First one is: Contextual filter: Content: Has taxonomy term ID depth modifier

Second one is: Contextual filter: Content: Has taxonomy term ID depth modifier with the same criteria you did.

I put the view path to be the vocabulary name and tested contextual filters like:
//Hierarichay
      tag1
        tag2
        tag2

//Urls
    tag1/tag2
    tag1/tag3

The views gets results for the child tags every time {2, 3}.
If you didn't use the first filter it will consider the parent as argument.
Hope it solve your problem.


Drush is pointing to the wrong web site Currently drush points it commands to /domains/steve_public/sites/default. I actually want drush to point its commands to /public_html/sites/default.

Can anybody advise me to how achieve this? Do I need to do this?

You need to specify your Drupal root to Drush in one of several ways:

Pass --root=/public_html --uri=http://example.com as an option on the commandline.
Set $options['root'] = '/public_html'; and $options['uri'] 'http://example.com' in a drushrc.php (not a good option if you have multiple sites on the system)
Use an alias, and set 'root' => '/public_html', 'uri' => 'http://example.com' (per the article you quoted)
Change your current working directory to '/public_html/sites/default' before running Drush commands (only works if you don't do any of 1 - 3).


Add Legend to Text Format Fieldset I'm working on making a site I maintain WCAG AA compliant. One of the items I'm getting flagged for is "Every FIELDSET element must contain exactly one LEGEND element." This error shows up on every page that has a comment function. It turns out it is due to the Text Format option for the comment body:

I've tried DMPing $form from a form_alter hook, but I can't seem to find this field set anywhere, at least it doesn't seem to be in the comment-form form.

The ID of that form Item is edit-comment-body-und-0-format--2, which when I check my DPM output, there is an entry in comment-body/0/#format, but it's null.

Where can I add a legend to this field set?

I got this to work like this:

function mymodule_process(&$variables, $hook) {
  if($hook == 'comment_wrapper') {
    $variables['content']['comment_form']['comment_body'][LANGUAGE_NONE][0]['format']['#post_render'][] = '_mymodule_post_render_fieldset';
  }
}

function _mymodule_post_render_fieldset($content, $element) {
  $your_legend = '$0<legend>Your comment legend</legend>'; // $0 is the full matched string
  return preg_replace('/<fieldset[^>]*>/', $your_legend, $content);
}

Care to give this a try?


conditionally hide a field based on another field's value (without using templates) I have a content type which has a required field containing some personal information like an email address. This field is not on the user entity - it is on an arbitrary content type.

What I need to do is conditionally hide or show this value based on whether the user consents for this information to be shown publicly.

I know that this can be done by creating a second boolean field ("show information" or similar) on the content type, and then overriding the theme template. The problem is that I am using a number of different view modes (via displaysuite) and do not want to have to override them all individually. I've tried calling hide() in hook_node_view with no success. I also can't just hide the value with jquery/css, since this field contains personal information and I can't output it at all if the user doesn't consent.

Is there a way to do this using display suite or a custom module? Is there a common solution to this that I'm overlooking?

Implement hook_field_access($op, $field, $entity_type, $entity, $account).

To find out how the arguments are structured, var_export() them in your first implementation (or better yet, dpm() them).


Changed my theme name without disabling it. Can't re-enable, please help Like an proper idiot I changed my theme name using .info file without disabling it first in the admin area. Now, I cannot re-enable as it does not show in the Appearance part of the administration area.

I have already tried resetting to the default garland theme and clearing all the caches to no avail. Any idea on how I could fix this?

I am using Drupal 7 and Omega as the base theme.

You probably forgot to change folder name where theme is located.

Also see if you have changed all occurances of theme name in .info file.

It would be good also if you change name occurances in template files of that theme (template.php)


translate drupal commerce product titles in views I have enabled the necessary i18n and l10n modules and I have been able to translate content without any trouble. I am now trying to translate some drupal commerce products. Using the title module I replaced the title of the product with a title field.

The product translations are showing correctly on the product display and cart pages but I also created a view with some products. For some reason the product title doesn't get translated in the view. The add to cart button does get translated however.

How can I get my products to show the correctly translated title in my view like they do on the product display page?

Found a solution. I rewrote the results of the Commerce Product: Title Field and used the replacement pattern [title_field]. The translation then showed correctly.


how to do a conditional subquery with db_delete I currently am deleting by a manually constructed query, but there should be a better way to do this.

$query = "DELETE FROM {$table1} ";
$query .= "WHERE col1 = '$col1' ";
$query .= "AND table2_id in ";
$query .= "( SELECT id from {$table2} where col2=$col2 )";
db_query($query)->execute();

How do I do this using db_delete?

Table2 has a covering index, so this should be done in one query.

I think your current way is that fine for multiple table handle like that. From this Delete from Multiple Tables using db_delete link you can see that:

db_delete takes a single string parameter to define which table the query is to be run against. There's no scope to provide more than one table at a time.


Change CCK Nodereference View at runtime I have a CCK nodereference field, displayed as a dropdown, and populated by a view.

I'd like to change that view depending on user permissions.  Can I change the view programmatically before it gets rendered?

I can't do it in hook_form_alter() because CCK isn't available here.
So I set up an #after_build, and inspect here.  But this seems to late.  The #options have already been rendered and there's no view property to change.

Thanks for the sugs.  I prefer to do everything in code so this was my solution.  I just manually loaded the view given some argument, and parsed the results.

function module_form_nodetype_node_form_alter(&$form, &$form_state)
{
    // Manipulate form after build so we have access to CCK
    $form['#after_build'][] = '_form_afterbuild';
}

function _form_afterbuild($form, &$form_state)
{
    // Custom options list for this nodereference
    $arg = user_access('administer nodes') ? false : true;
    $form['field_fieldname']['nid']['nid']['#options'] = _GetOptions($arg);
}

function _GetOptions($arg=false)
{
    $viewResults = views_get_view_result('view_name', '', $arg);

    $options = array();
    foreach ($viewResults as $row) {
        $optionTitle = $row->title;
        $options[$row->nid] = $optionTitle;
    }

    // Sort options by alpha
    asort($options);

    return $options;
}


How can user select attributes for a product when clicking on an add-to-cart link? I'm trying to work out the best way of displaying an attribute selection form when a user clicks on an add to cart link (not on a product node). Ideally display a form in a shadowbox with attribute selection and quantity fields and a submit button. I feel like this option must exist somewhere, but I haven't found it.

Any pointers for me?

Very old one but why not answer?

Use Ubercart Cart LInks module (included in Ubercart Core). I think it allows links that operates on the cart, like empty cart or add a product what I guess includes product attributes.

Here it's explained, but is very old page, check module documentation.

http://www.ubercart.org/node/1427


Contextual filter on taxonomy view using URL I have a taxonomy

Bubble
Clouds
Flower

I also have a pages where I need to be able to pull a taxonomy term (and it's fields) into the page.
if the site path is abc.com/features/bubbles

I need to be able to access blubbles and it's fields.

I've created a view of taxonomy terms that lists all my terms.   I can not get the contextual filter correct to display just bubbles.

Any help is appreciated.

Create a view, Create a page display and set it's path to features/%

Then add a contextual filter: Taxonomy term: name.

That's it! when you visit the page /features/blubbles page, if there is a taxonomy term named blubbles, the views will display the fields you have added. You may add a validation criteria (while adding the contextual filter) to limit terms to an specific vocabulary.

However you might want to consider using panels too. After enabling panels, page manager and views content panes modules, you can create a page and set it's path as features/%term (notice the arg is %term not %) set it's type as String.

Add a display to your view of type content pane
Add the contextual filter, taxonomy term: name.
In configuration section of the views display there is a 'argument input', open it and set type of argument from panels argumen
In the opened configuration popup, select second argument as the name is second parameter in your path. you may select from panels context too if you can configure the panels accordingly.
Go to panels configuration page, add content to one of regions, select views panes not regular views!
Visit the panels page, done.

This way you have more control over your page. you can create another views, such as a view directly showing nodes, filtered by a taxonomy. you can send the term name just like you sent in the views above.
In the first view it's not a good idea to show nodes if you are only planning to display the term fields only once.

This question : Contextual filter with a block view is about views blocks and contextual filters. I still suggest using pages. views content pane will play role if a block for you.


how to create Views exposed filter with fields from custom table I have one of custom table with fields named title and id. Now I want to add the title field in views exposed filter as drop down.

How to create exposed filter for this?

Could anyone explain where I can find this?

It should depend on how you are exposing the field to views, make sure views know about field  and filter handler, so as an example in your hook_views_data() your title field should be exposed in following way -

// name field
$data['exposed']['title'] = array(
    'title' => t('Title'),
    'help' => t('title for record'),
    'field' => array(
        'handler' => 'views_handler_field',
    ),
    'filter' => array(
        'handler' => 'views_handler_filter_string',
    ),
 'sort' => array(
        'handler' => 'views_handler_sort',
    ),
);


Moving drupal to a subdirectory I'm trying to move a Drupal site to a sub-directory of the same domain. I'm very experienced with WordPress but not experienced with Drupal sites. How would I move a website from http://example.com to http://example.com/old-website/ ?

I can't figure out what would cahnge so that I can migrate the site.

Any and all help is appreciated!

Thanks!

Austin

Just move the files, you don't need to set a base URL like in Wordpress.

If you do run into any problems, uncomment rewritebase in htaccess


Is it possible to use Drupal with CouchDB? I'm very big fan of CouchDB. I want to try Drupal, but it doesn't have built-in CouchDB support, and i guess it is not easy to add one, because Drupal's DB layer was designed for SQL-based databases. I found only one attempt to add CouchDB support but it is experimental. Is there any successful cases of using Drupal with CouchDB? Or i should ultimately give up on this issue?

There is also MongoDB support, but i just wanted to know all variants.

There are a few things to keep in mind.

Even though Drupal support multiple databases (mainly MySQL,  PostgreSQL, and now anything supported by PDO), this is only true of the core files.  There are contributed modules that use database specific syntax and/or functions.  In addition, there are some functions that show subtle differences when run on different database servers (for example, see Does db_affected_rows() works well with PostgreSQL?).

The modules for non-SQL databases are primarily for offloading some core tables from the primary database. You still need an SQL database when using these.

Personally, I don't mess around with any of these other databases. I may start experimenting with MongoDB, but I can't really use it with client's projects as its support on commodity hosting is limited. Setting it up for them would eat into their budgets, and clients would rather have me do Drupal work than IT work.


How to disable the title field on the node edit form? How can I hide or disable the title field on the node edit form?

If I do so from the content type Manage form display tab (admin/structure/types/manage/CONTENT_TYPE_MACHINE_NAME/form-display), then I get some integrity constraint errors in the log.

So I don't want to show default title field in Node edit form. If I hide the title field normally like other fields. Got white screen after node creation. And log says title field can't be null .... and so on ...

You can use hook_form_alter() function to alter any form (including node edit form) and disable Title field. Check sample code below:

use Drupal\field_collection\Entity\FieldCollectionItem;

function [MODULE_NAME]_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'node_[CONTENT_TYPE]_edit_form':
      $form['title']['#disabled'] = 'disabled';
      break;
  }
}

If you're altering only one form you can check hook_form_FORM_ID_alter() function and change FORM_ID with node_[CONTENT_TYPE]_edit_form where CONTENT_TYPE is your node type form.

EDIT :

To automatically set node title without allowing user to see title field, you can use Automatic Entity Label Module. The module is in dev version for D8, but we can give it a try if functioning properly.

If don't want to use Automatic Entity Label module, you can try doing same with custom code, check sample code here


Possible to have variables in migration configuration? We are running a continuous migration (using migrate_plus) from a JSON API which supports last_modified_since as a query parameter. I would like to run this job every hour, and use the time of the previous run as parameter.

What would be the best way to achieve this? I tried tried overriding the variable by adding to the $config array in settings.php, but that is probably not even supposed to work.

Yes you can! However, depending on the plugin you are using, it might be picky about what you put in the variable. Here are two examples of variables being used in a migration config:

A file import

source:

  plugin: csv
  track_changes: true
  path: 'public://migration/csv/image_download.csv'
  header_row_count: 1
  keys:
    - image

  fields:
    image: 'Image'
    media_name: 'Media name'

  constants:
    uri_file: 'public://photos'

process:
  uri_file:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/uri_file
        - media_name

  uid:
    plugin: default_value
    default_value: 1

  filename: display_name

  uri:
    plugin: download
    source:
      - image
      - '@uri_file'

In the above, both constants/uri_file established in the "source" step of the migration, and uri_file passed as @uri_file to the download plugin in "process" step are variables.

The documentation for the migrate_plus process plugin "merge" has another good example:

source:
     plugin: d7_node
   process:
     temp_body:
       plugin: iterator
       source: field_section
       process:
         target_id:
           plugin: migration
           migration: field_collection_field_section_to_paragraph
           source: value
     temp_images:
       plugin: iterator
       source: field_image
       process
         target_id:
           plugin: migration
           migration: image_entities_to_paragraph
           source: fid
     paragraphs_field:
       plugin: merge
       source:
         - @temp_body
         - @temp_images
   destination:
     plugin: 'entity:node'

In both these example, the vars are used in arrays. That's just what the plugin expects, not something inherent to using variables.


jquery date picker in views exposed filter changes the date values I have a node type "tasks" and created a view so that current logged in user can see his/her assigned tasks. I have used a "time ago" formatter in the field "deadline" which shows the remaining time to the deadline correctly. I have also created a filter for "deadline" and expose this filter. The selected options are as follows

The filter is correctly working if I choose "Select" in "Date selection form element" under settings for the "deadline" filter as can be seen below

However, when I change the "Date selection form element" to either "Plain" or "Popup", the duration in "Due In" field changes by a day that means if today is 5th March and the task is due on 6th March 2014 by 14:00, the "Due In" field will show 13 hours xx minutes (see image below)

I really don't understand what is the problem. Any suggestions?

This is a known issue (bug) of Views. You can find details here: Exposed grouped filter for date not working.


html text or custom image to the user profile page? On my user profile page, how do i add some extra html code or custom php code to the user profile page? as i would like to add a custom generated image based on userid in the profile page.

Please advice.

you can also add a block to the "content area" to be shown below the user profile (restricted to user/* pages). In the block you an use short PHP snippets.


Does Drupal 8 core by default collect visitors data? I am searching a lot since last few days but not getting an answer. I am in process of preparing Privacy Policy of site. I am not providing any user registration or user login facility but anonymous user can post comments. Now, question arises after I read following Q&A on DA,

Don't collect IP addresses in Drupal 7

Now, since I have no intention to collect any user information(have not enabled statistics module), then I can simply write, "I do not collect any user information". Again, question comes, what if the code is collecting IP address/Hostname without our knowledge.

So, if there is a way to know what information are collected, and how saved then we can be sure about that, and can state in privacy policy or If Drupal core is not collecting any data, then also we can be sure about that  and write "We do not collect any visitor's data". Is there a way we can know?

Note: Please let me know, if this question is going toward Privacy policy(away from drupal), I will move this to SO. But, again it is related Drupal CMS code, so I thought to ask here first.

UPDATE:

Have raised the issue at Drupal core: Legal privacy policy statement of Drupal core

and it you see the comment there is a link to other issue: Privacy Concerns as GDPR Compliance, which says there is already work going on and regarding this module creation is underway, module will be General Data Protection Regulation.

Please add comments in issue, if you want to add some suggestion.

The answers and comments in the linked question for Drupal 7 are still valid, with one exception. Drupal 8 gets the client ip address from Symfony\Component\HttpFoundation::getClientIps(). This returns the client ip from the header REMOTE_ADDR, unless you set up a trusted proxy. In this case you would have to configure this proxy to obfuscate the visitor's data.

In all other cases it should be enough to overwrite part or all of the ip address in a Symfony middleware.


How should I store a simple, time dependent, repetitive data type in drupal Im interested in collecting simple data series over time with Drupal. for instance, lets say a user wants to input a monetary amount the spend on a given item each day, and then track that over time. It seams like overkill to log the information as a node, or even an entity for that matter. What is a good way to store data of this nature?

I think Webform is what you are looking for. You make a form that user(s) can fill in and submit.

You can track the submissions over time, export them etc. There are lots of features you can do with webforms.

This is not a complete how-to for your question but you can take it as a start point. This way you don't create a node for each submission, but the form itself will be a node of type Webform.


Performance -> Caching In Configuration > Development > Performance, in the Caching area, [Cache pages for anonymous users] and [Cache blocks] are unchecked. When I check them and save, the page reloads and both boxes are again unchecked. Is this wrong? Shouldn't they "remember" the state?

In general, yes, the form should update with the values you set.  However, there are few different ways you can override form settings.

The two in question are cache and block_cache.  You need to search the files for lines that look like:

$conf['cache'] = FALSE;
$conf['block_cache'] = FALSE;

The integer 0 or the string '0' or "0" may be used instead.  Checking the settings.php for the site, and any custom modules.


Drupal private messages database table design I am trying to get the raw message data from a Drupal instance running the Privatemsg module.

I have tracked the message data down to the pm_message and pm_index tables but I am struggling to understand the database structure / design.

I am trying to get the author and recipient users for a message, however in the majority of cases the pm_message.author and pm_index.recipient are exactly the same user. How do I get the author and recipient of a message from the database?

I think this maybe due to me not understanding threads in database design (can't see how thread_id is created or relevant), sample query I am running to get the data:

SELECT
author, recipient, body, timestamp
FROM pm_message, pm_index
WHERE pm_message.mid = pm_index.mid

In general with Drupal you want to avoid directly querying the database if you didn't create the tables yourself. Instead try to use functions provided by core or the module to get the data for you. The table structures are often complicated and may change without notice, but the functions for accessing those tables generally adapt to the changes (this is more true of core than contrib modules, but is frequently true of both).

In the case of Privatemsg the Drupal 7 version (and probably 6) provide several useful functions to pull the message data (see the main module file).  For example you can load an entire thread with privatemsg_thread_load:

/**
 * Load a thread with all the messages and participants.
 *
 * This function is called by the menu system through the %privatemsg_thread
 * wildcard.
 *
 * @param $thread_id
 *   Thread id, pmi.thread_id or pm.mid of the first message in that thread.
 * @param $account
 *   User object for which the thread should be loaded, defaults to
 *   the current user.
 * @param $start
 *   Message offset from the start of the thread.
 * @param $useAccessDenied
 *   Set to TRUE if the function should forward to the access denied page
 *   instead of not found. This is used by the menu system because that does
 *   load arguments before access checks are made. Defaults to FALSE.
 *
 * @return
 *   $thread object, with keys messages, participants, title and user. messages
 *   contains an array of messages, participants an array of user, subject the
 *   subject of the thread and user the user viewing the thread.
 *
 *   If no messages are found, or the thread_id is invalid, the function returns
 *   FALSE.

 * @ingroup api
 */
function privatemsg_thread_load($thread_id, $account = NULL, $start = NULL, $useAccessDenied = FALSE) {

There are also several functions that generate the query objects for pulling the module's data like privatemsg_sql_list:

/**
 * Query definition to load a list of threads.
 *
 * @param $account
 *  User object for which the messages are being loaded.
 * @param $argument
 *  string argument which can be used in the query builder to modify the thread listing.
 *
 * @see hook_query_privatemsg_list_alter()
 */
function privatemsg_sql_list($account, $argument = 'list') {


Viewing statistics for content types I am trying to use the Google Chart Tools module to display graphs with data regarding content types inside a view (Views module). For example, lets say I have a content type called Car that has a field called Color. I would like the graph to display, say, the number of Cars that are blue, red and green.

Is there a way to do this using only the the Google Charts, Views, and Core drupal modules or do I have to download a seperate module? Is there another Charts module that would do what I am asking for more easily than Google Charts?

Step 1: Getting started

To create charts in Drupal, you can (also) use the Charts module. It comes with a sample view which will give you a chart for each of your content types.

Just clone and refine that view, and check how close you are to make it fit your needs. Refer to Create charts using Views (and its subpages) for more details.

For a sample of such chart (derived from the delivered sample view), have a look at this demo sample.

Step 2: Create the tabular format of the view

A common mistake when creating charts, is that the data to be charted is (not yet) correct. So you really need to first work on getting the tabular format of the view created correctly. That's also what's recommended in the Bonus tip within Steps to create charts using the views UI, i.e.:

  You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first. ...

Step 3: Add the chart to your view

Do not try to start this step if you didn't first complete the prior step.

Just use the views display format "Charts", and select the various options that fit your needs. Refer to Steps to create charts using the views UI for detailed instructions about this.

Disclosure: I'm a (co-)maintainer of the Charts module.


How do I delete a vocabulary programmatically? In Drupal 7 there was taxonomy_vocabulary_delete($vid), but this doesn't seem to be there in Drupal 8.

What's the equivalent code for Drupal 8?

I believe I have figured this out. You have to load the vocabulary using the Vocabulary entity class, then call the delete method on it. So something like this:

Vocabulary::load($vid)->delete();


Krumo output with debug() When debugging I prefer using the Devel module because of the clickable Krumo output.

However when disabling the Devel module on production unremoved calls to e.g. dsm() can cause a WSOD because of calls to undefined functions.

By using the built-in debug function this does not happen but it will miss the nice krumo output.

Is it possible to get krumo output with the debug() function / or otherwise prevent the WSOD on production sites when using devel functions?

Use a custom code and define your own debug function that uses dsm if available or debug if not:

function my_debug($data, $label = NULL, $print_r = FALSE) {
  if (function_exists('dsm')) {
    dsm($data, $label);
  }
  else {
    debug($data, $label, $print_r);
  }
}

But keep in mind that you should avoid any debug code in production.


How can I write into a Flag's custom field programmatically? I successfully managed to save a flag programmatically in Drupal 8 thanks to this help but I cannot manage to save data into a custom field I added to the flag entity.

The following code saves the flag but the field stay empty.

$entity = \Drupal::entityTypeManager()->getStorage('node')->load($entity_id);
$flag_id = 'bookmark';
$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);

/* Here is where I'm trying to set my custom field value */
$flag->set('field_my_custom_field', $link_name);

$flag_service->flag($flag, $entity);

I cannot find any info into the documentation. Any help will be much appreciated.

I fix it with this code.
You should save the output of the function

$flag_service->flag($flag, $entity);   //Wrong method

in a variable like it

$id_flagged_entity = $flag_service->getFlagging($flag, $entity);

and set the title at this entity

$id_flagged_entity->set("field_my_custom_field", $link_name);
$id_flagged_entity->save();


Problem when using Feeds to import nodes which have a image field I'm using feed to import nodes from a csv file. I'll try to reproduce.

Everything works fine if I do this:

1) I create the importer. For Mapping Settings I set:

ID -> Node ID
TITLE -> Title
BODY -> Body

This importer will import the csv data to the cuadros content type

2) I import this csv file with no problem at all:

ID;TITLE;BODY
83;without title;text
1084;White;text

But I get a message error if I include a image for the node

1) I create the importer. For Mapping Settings I set:

    ID -> Node ID
    TITLE -> Title
    BODY -> Body
    PHOTO -> Images

Images is a image field of the node.

2) I put the 2 images files in: localhost/mysite.com/sites/default/files/photos/

3) I import this csv file

ID;TITLE;BODY;PHOTO
83;without title;text;http://localhost/mysite.com/sites/default/files/photos/245c-w1000-h800.jpg
1084;White;text;http://localhost/mysite.com/sites/default/files/photos/261-w1000-h800.jpg

4)I get the error message you can see below.

Just in case it was a permission problem I set the files folder and all its content to 777, but problems stil persist

 The specified file temporary://filel1sCPA could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.
The specified file temporary://fileqPBtxM could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

Invalid enclosure http://localhost/mysite.com/sites/default/files/photos/245c-w1000-h800.jpg
Invalid enclosure http://localhost/mysite.com/sites/default/files/photos/261-w1000-h800.jpg

problem was that I had to use the default folder for the image fied, which is images. I had set photos as the folder for the images.


When using views to create a list of nodes, how can I eliminate the link from the node title? I am using views to create a list of nodes. I am using the "Unformatted" style, with the "Node" row style.

This is perfect for my need except that it automatically creates a link from each node title to the node page. I would like to not have those links.

How can I most easily do this? Would the best way to be to switch to "Field" row style and simply include the fields I want, styled the way I want? Or is there a simpler way?

When you select node style, it uses your node.tpl.php file to create the node, so if that has a link in the title, it's gonna be there.  You can choose the "style" of node, eg, teaser or full, to change this behavior, and include or not include links and comments, etc.  Or, as you ask, go to Fields and have a lot more flexibility.


How do I create a filter based on the current user's role in a search_api based view? I would like to filter a search_api based view using the current user's roles as input.
I don't see a contextual filter for the current user in my search_api based content view at all.
How can I accomplish something like the "Published or has role" feature of this contrib module? This one seems to only work on non-search_api views.

Thanks to @prkos reminding me that this is a regular node access setup issue. This was solved when I found this issue in the search_api queue about incompatibility with "View All Unpublshed content"


node_save is not same as saving a node manually I've removed many terms from a vocabulary and now I see this error when I see a node referencing the deleted term(also the attachment):

EntityMalformedException: Missing bundle property on entity of type taxonomy_term. in entity_extract_ids() (line 7693 of D:\xampp\htdocs\gij\includes\common.inc).

I know it is an issue( like this) which goes away if I edit and save the node manually but does not work out if I run this code from Drush:

$node = node_load($nid);

 if ($node !== FALSE) {
  print "Saving the $full_path\n";
  node_save($node);
  }

Why this difference?

Try one of this options:

Explicit field deletion:

$node = node_load($nid, NULL, FALSE); // Force to load
if (!empty($node->nid)) {
  $node->field_taxonomy_term = NULL; // Reset the field
  node_save($node);
}

Submit the node form programmatically:

$node = node_load($nid, NULL, FALSE); // Force to load
if (!empty($node->nid)) {
  $form_state['node'] = $node;
  $form_state['values']['op'] = t('Save');
  drupal_form_submit($node->type . '_node_form', $form_state, $node);
}

Edit all nodes on bulk with views bulk operations:

Install https://drupal.org/project/views_bulk_operations
Add a new view page of content (node) and set fields as display.
Add field "Bulk operations: Content"
Configure the fields: SELECTED BULK OPERATIONS: "Save content" (check)
Save the view and go to the views path.
Select all items and the "Save" operation and execute it!
Done!


Print Menu block Title and the menu In admin/structure/menu I created a menu
In admin/structure/block I created a 'menu block' with above menu

With below code I am able to render the menu in page--front.tpl.php

<?php
 $block = module_invoke('menu_block', 'block_view', '3');
 print render($block['content']);
?>

But how do I render the Menu block Title?

Your implementation is right but you are missing the print subject, you only print the content of the block.

if you debug the $block variable you will find 'subject' as key with value or without value based on the block if it has a title or not.

So your code should be like this in order to print the title.

 $block = module_invoke('menu_block', 'block_view', '3');
 print render($block['subject']);
 print render($block['content']);


Clean way of building simple taxonomy browser of arbitrary depth I have spent days trying to determine a clean way to do the following:

Display a list of all top-level terms in a vocabulary with links to their child terms
Upon clicking a link, be taken to a list of the children of those terms.
Ad infinitum until the lowest-level term, for which a list of nodes tagged with that term will be displayed.

This seems like it would be pretty commonly-needed functionality but I can't find any solution that can handle arbitrary depth, particularly if not all term trees  descend to the same depth.

An ideal solution would be one that uses Views 3, Contexts, EntityFieldQueries, or anything else that's well-supported in Drupal 7.

I'm able to do almost exactly what I want by making a simple view with three node:term relationships (term, term's parent, and term's parent's parent) and user those for sequential contextual filters. The only problem with this is that if there's a node with a termpath of too little depth, it gets listed as "uncategorized" and generates a dead link. Instead of doing that I'd like it to link to the next child term available.

I figured out a way to do this with only the Views module. It's not perfect — it doesn't generate a nice URL and breadcrumb with the taxonomy lineage the way that my solution for a taxonomy of a single depth would do.

Static Depth Browser

For a taxonomy of static depth (where all terms have the same depth of child terms), you would do the following:

Create a view of nodes
Add relationship to taxonomy term (Term)
Add relationship to taxonomy term parent, accessible via Term (Parent)
Add relationship to taxonomy term parent, accessible via Parent (Parent Parent)
Repeat step 4 as many times as necessary for your taxonomy's depth.
Add contextual filters for each one and make sure they're in the proper order. Set to display a summary when filter is not in URL.
You'll probably want to override the breadcrumb and title for each filter.
???
PROFIT

Variable Depth Browser

For a taxonomy of variable depth (where some term trees have deeper levels of nesting than others), it's a bit more complex:

Add a new top-level term (Foo) to your vocabulary and put all other terms under it.
Create a view of terms with a page that displays term names
Add contextual filter: Taxonomy term: Parent term
When the default value is not in the URL, provide default value
Set default value to your top-level term name (Foo)
Specify validation criteria

Validator: taxonomy term
Criteria: your vocabulary name
Filter value type: Term name converted to term ID

Click the "+Add" button at the top of the Views panel to add an Attachment to the view.
Add to this attachment only (override) Relationship: Taxonomy term: Content with term
Add to this attachment only (override) display: fields: node titles linked to nodes, and remove (from this attachment only!) display: fields: term name
Add to this attachment only (override) contextual filter: Taxonomy term: Name
When filter value is not available, provide default value: Raw value from URL: Path component: 2 (or more if your Page path has >1 component)
Attachment settings: Attach to: [name of the page display you just made]
???
PROFIT

Screenshots of Views' UI for reference:


Send custom user fields to twig template I'm writing my first Drupal 8 theme.

Now for a block I need all some custom fields of the user. So that I can use it in my theme.

I create a theme file with collectionmanager_preprocess_html method.

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\Entity\User;

/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 *
 * Adds body classes if certain regions have content.
 */
function collectionmanager_preprocess_html(&$variables) {
// Load the current user.
$user = User::load(\Drupal::currentUser()->id());

// get field data from that user
$firstname = $user->field_first_name->value;
$lastname = $user->field_last_name->value;

$variables['custom_firstname'] = $user->field_first_name->value;
$variables['custom_lastname'] = $user->field_last_name->value;
}

If I'm correct I can access the variables in twig with {{custom_firstname}}. But it show always a null value. Can someone help me with this? I can't find my issue on this. The variable $firstname and $lastname contains the correct values.

collectionmanager_preprocess_html() prepares variables for html.html.twig template. For page.html.twig the of the function name should be collectionmanager_preprocess_page(). The same pattern should be used for other theme hooks (view, block, field etc).


how to find that there is a "Promoted to front page" node and load it in page.tpl.php? because front page has no arg(1) (node id)  I cannot load promoted node[s] in page.tpl.php .
all I want to do is print something in one part of front page if a specific content type node in about to load in node.tpl.php.
I search it alot but find no answer.

You mean a custom function?

I did a lot of this for a current project where we needed short little lists of nodes with different criterion all over.  I found Views bulky and overkill in some places, so I added small functions to template.php.  They're really just simple SQL SELECT statements.

For example:

function home_channel_list($title, $tids, $limit){

    $query = "SELECT t1.nid, MAX(t1.vid), t1.title, UNIX_TIMESTAMP(t2.field_pubdate_value) AS pubdate
                FROM {node} t1
                    JOIN field_revision_field_pubdate t2 ON t1.nid = t2.entity_id AND t1.vid = t2.revision_id
                    JOIN field_revision_field_channel t3 ON t1.nid = t3.entity_id AND t1.vid = t3.revision_id
                WHERE t3.field_channel_tid IN(".$tids.")
                    GROUP BY t1.nid ORDER BY pubdate DESC LIMIT ".$limit."";

        $result = db_query($query);

        // Container div and title
        print '

'.$title.'
';

        // Article list
        foreach ($result as $record) {
            $mypubdate = format_date($record->pubdate, 'custom', 'F j, Y, g:iA');
            print '
nid.'">'.$record->title.'
';
            print '
'.$mypubdate.'
';
        }

        // Clear and close the container div
        print '

';
}


What does the 'export' key mean in a schema definition? The code below is from the message module.  What does the 'export' section mean?

function message_schema() {
  $schema['message_type'] = array(
    'description' => 'Storage for user-defined message templates.',
    'export' => array(
      'key' => 'name',
      'identifier' => 'message_type',
      'default hook' => 'message_default_message_type',  // Function hook name.
      'primary key' => 'name',
      'api' => array(
        'owner' => 'message',
        'api' => 'message',  // Base name for api include files.
        'minimum_version' => 1,
        'current_version' => 1,
      ),
      'load callback' => 'message_type_load',
      'save callback' => 'message_type_save',
    ),
    'fields' => array(
      // Although the "name" should be enough as the primary key, the numeric ID
      // is required for the internal use of entity API.
      'id' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Numeric message type ID.',
      ),
      'name' => array(
        'description' => 'The unified identifier for a message type.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'description' => array(
        'description' => 'Description for this message.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'primary key' => array('id'),
    'unique keys' => array(
      'name' => array('name'),
    ),
  );

These properties are used for implementing ctools export/import APIs.

See How to make configuration objects exportable with CTools.


Display taxonomy field in node display I created a vocabulary where terms have an image as additional field.
I want to show the image instead of the term name in the node page. How can I do this?
In Drupal 6.x, I would load the term and display it, but I guess in Drupal 7 with field API there must be a better way to do this.

You could define your own formatter with hook_field_formatter_info() and then select that in the Manage display screen of the content type/view mode you want to be displayed like that.

For reference, have a look at what taxonomy.module is doing: taxonomy_field_formatter_info(), taxonomy_field_formatter_prepare_view() and finally taxonomy_field_formatter_view().


Nivo Slider lists up the images instead of sliding I download this module with drush dl nivo_slider
Then enable and automatically download libraries with drush en nivo_slider
Then clean cache with: drush cc all
Then enable in block.

Then Firebug said: TypeError: $(...).nivoSlider is not a function
$('#slider').nivoSlider({

and chromium said:
Uncaught TypeError: undefined is not a function nivo_slider.js?ne2hej:11Drupal.behaviors.nivoSlider.attach nivo_slider.js?ne2hej:11(anonymous function) drupal.js?ne2hej:76b.extend.each jquery.min.js?v=1.9.1:3Drupal.attachBehaviors drupal.js?ne2hej:74(anonymous function) drupal.js?ne2hej:412c jquery.min.js?v=1.9.1:3p.fireWith jquery.min.js?v=1.9.1:3b.extend.ready jquery.min.js?v=1.9.1:3H jquery.min.js?v=1.9.1:3

I'm using later version of Drupal 7

I think there's an installation priority issue with Nivo Slider module and Libraries API module or Nivo Slider library files.

Since you installed all required modules and placed Nivo Slider library files in the right location as explained in the installation steps:

  To install Nivo Slider:

  Download the latest version of the Nivo Slider jQuery plugin and
  extract it to sites/all/libraries or sites/sitename/libraries as you
  require.
  The extracted folder must be named nivo-slider. Enable Nivo
  Slider and all of the modules that it requires.
  Configure the jQuery
  Update module to use jQuery 1.7 or higher.

Now you need to disable Nivo Slider module by running this command drush pm-disable nivo_slider, then you need to uninstall Nivo Slider module by running this command drush pm-uninstall nivo_slider, then install Nivo Slider again by running this command drush en nivo_slider.

Don't forget to clear Drupal cache after you finish uninstalling and installing the module; just in case.


Can't change add to cart button value I can't change 'Add to cart' button value (site http://zoo812.ru)

Now it is value="Добавить в корзину", I want to change it to value="buy"

I inserted

function ivanco_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
    $form['submit']['#value'] == t('Buy');
}

in template.php, but it does absolutely nothing.

String overrides also doesn't work.

There is no js code linked with it nor any other mentions about it in theme files.

You see, there is Catalog View, and each item's displayed with Evo.

I can do this with JS of course, but it wont be elegant..

I've used this code and worked fine:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['submit']['#value'] = 'CUSTOM BUTTON VALUE';
    //dpm($form);
  }
}


Get Instagram realtime count likes Here is how the application is structured:

A cronjob runs every 3 hours making the Instagram Recent Media call -https://api.instagram.com/v1/tags/myhashtag/media/recent?access_token=ACCESS-TOKEN
If any new images have been posted on #myhashtag, then it creates a new article on the instagram content type
Finally a view(gallery) is built based on the images in this new content type. It displays the image's 'like' counter.

It was built this way to add moderation of images, so that when an image is unpublished, it wont show up in the gallery. The publish and unpublish aspect works through a tool page where there is an additional flag to remove from the queue as well.

Question is: Since the gallery view is based on the values stored on an instagram node in contenttype.
Is there a way to update the value for the likes count field without having to make a call to the API everytime any user goes to the gallery page?
 Otherwise the 'like' counts stored on the article become outdated.

Let me know if I can provide more info.

I don't know anything about the Instagram API, but if you want to keep the like counters up to date you will need to make API calls at some point.

If you expect many viewers then as you say, you probably don't want to make that call every time a user goes to the gallery, I would suggest adding another function to cron that iterates through your currently active Instagram content and refreshes the like counter.


PHP filter field behavior with Rules - can't use curl_exec I am on Drupal 7. I am trying to use Rules to execute custom PHP code. I am using PHP filter in order to achieve that. Inside that PHP filter I will use curl. The idea is to communicate with a remote API.

I already have one Drupal website running this code I want to use and it works like a charm. On this website I am using Rules, PHP filter and curl.

The issue is that I am porting the EXACT same code to a new website using the same set of tools (Rules, PHP filter, curl), but I can't save my code into PHP filter.

The field will allow me to save this

$data = array(
'User'          => 'someuser',
'Password'      => 'somepassword',
'Subject'       => 'Something',
'Message'       => 'Something',
'StampToSend'   => $account->created,
'MessageTypeID' => 1
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://someurl.com");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

When I add the last line "$response = curl_exec($curl);", then Drupal won't save my Rule. No error messages, no messages in the Drupal logs, no anything. It will just fail to save the field. I can save all the code above, and Rules with PHP filter will accept it. When adding the curl_execute line, it simply won't save.

Any ideas on what I could do? Thank you!

I solved the issue by moving the code to a custom module, then everything worked. My best guess is that the PHP filter is somehow interpreting the code and filteirng out stuff it considers innapropriate.


Why _block_load_blocks() does not work? _block_load_blocks() returns an empty array. block_list($region), which uses _block_load_blocks() returns nothing as well. Why?

There should be at least a block, as the "Main page content" block is always associated with a region. You always need to select a region for that block, as the "-None-" option is not available when selecting a region for it.

The list of blocks can be altered from modules. If a module is removing the "Main page content" block from the list, it doesn't appear in the list, and the list would be empty, if there aren't any other enabled blocks. _block_load_blocks() contains the following code.

$block_info = $result->fetchAllAssoc('bid');
// Allow modules to modify the block list.
drupal_alter('block_list', $block_info);


Cannot alter clientside validation error messages for fields added with the field UI module I am adding some custom fields to a registration page using the field UI module. I'm also using the clientside validation module to display error messages on required fields. I am able to change the error messages for the default fields I have not added using the field UI, but not for the fields added with the field UI. I have tried many different ways of targeting the fields to no avail. I'm using Drupal 7.

I can see the custom rule is actually being set when I kpr($js_rules):

$js_rules['field_first_name']['messages']['required']
<span data-thmr='thmr_13' class='devel-themer-wrapper'>Please enter your first name.</span

...but the default error message still shows. I have a feeling this is due to the <input> element's name attribute being field_first_name[und][0][value], but I was even  unsuccessful in targeting this rule using that string in the _clientside_validation_set_required() function.

The difference between the default fields and my custom fileds are the custom fields values are very heavily nested within multiple arrays.

However, I'm unsuccessful in changing the input element's name attribute using any of the following:

$form['field_first_name'][#name], $form['field_first_name'][#field_name], $form['field_first_name']['und'][0]['value'][#field_name], $form['field_first_name'][#name], etc.

My custom rules:

_clientside_validation_set_required(
  $element['#name'],
  $element['#title'],
  isset($element['#required']) ? $element['#required'] : FALSE,
  $js_rules,
  t('Please enter your company email.')
);

Which works for the drupal default email field. However, this (or any of the many ways I've tried referencing the element's name) does not change the error message for my custom "first name" field:

_clientside_validation_set_required(
  $element['#field_name'],
  $element['#title'],
  isset($element['#required']) ? $element['#required'] : FALSE,
  $js_rules,
  t('Please enter your first name.')
);

Update

It turns out it IS the name attribute. When I hard code the name as field_first_name using theme_textfield(), my custom error message shows up. The problem with this is it prevents the proper values from being written to the database. Is there a way to escape the brackets in field_first_name[und][0][value] in order to use that as the first argument of _clientside_validation_set_required()?

I was able to set the rule by referencing the nested #name and #value keys:

_clientside_validation_set_required(
      $element['field_first_name']['und']['0']['value']['#name'],
      $element['field_first_name']['und']['0']['value']['#title'],
      isset($element['field_first_name']['und']['0']['value']['#required']) ? $element['field_first_name']['und']['0']['value']['#required'] : FALSE,
      $js_rules,
      t('Please enter your @field_name.', array('@field_name' => strtolower($element['field_first_name']['und']['0']['value']['#title'])))
    );


Why/How I could remove index.php in the URL I have added a RewriteRule to force https on one domain at the end of my .htaccess file

RewriteCond %{HTTP_HOST} ^www.mydomain\.be [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}

It is working fine except that after that, I get a /index.php/ inside all URL

If I add RewriteEngine on before like the following:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.mysite\.be [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}

Then my /index.php/ problem is solved...

I am happy with that, but I don't understand why

Note: Those lines are added at the end of a regular drupal .htaccess. I mean no change in it except that I have uncommented the all to "www" rule (before my https rule at the end)

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

There are no special apache2 conf as welll

I suggest you look at the .htaccess file supplied with Drupal, beside index.php. In the standard one, it has rules for both redirecting http: to https: (line ~104) and for rewriting URIs to index.php (line ~136)

Some servers are configured with these rules in the main config file because relying on .htaccess results in slower response from Apache (it reads the main files on startup but .htaccess per request).

So:
- Remove any additional rules you have added (i.e. revert to "out of the box") and check for expected behaviour;
- Uncomment the protossl conditions in .htaccess and check again;
- Optionally, move some of these into the .conf file for faster response.