No schema for my_module.global error on unit test

Turns out that it is related to the my_module.schema.yml. Looks like every YAML file under my_module/config/install must have a corresponding schema in the my_module.schema.yml file in order to set up a unit test, even if this is not actually required for the module to work. It needs to look something like this (assuming the config/install file name is my_module.global.yml):

my_module.global:
  type: mapping
  label: 'My label'
  mapping:
    property:
      type: text
      label: 'Property label'

If unsure which properties need to go there, running the unit test without them will give a list as part of the error. I'm sure there is a better way to find this, but that's the way I found so far.

Edit – the whole schema verification mechanism can be turned off: In drupal/core/lib/Drupal/Core/Test/TestSetupTrait.php, $strictConfigSchema needs to be set to FALSE.


It's bad practice from a general development point of view (look up "separation of concerns")
It can break caching, or render it useless/pointless.
One bit of code should do one thing, and do it in a such a way that is testable.

In my opinion, your logic for scraping should be in its own class, a class that does nothing but scrape. Then your preprocess function should make use of that class, and prepare the variables for the template.

You don't have to do any of this, of course, it's up to you what best practices you want to follow. If you're new to development, take it from me that modularising your code now will probably save you a lot of time when you come back to in 2 years and something doesn't work.


If I understood correctly, this snippet would get you the number:

use Drupal\Core\Database\Database;

$query = \Drupal::database()->select('node__field_order_reference_number', 'f');
$query->fields('f', ['field_order_reference_number_value']);
$query->orderBy("revision_id", 'DESC');
$query->range(0, 1);
$last_order_reference_number = $query->execute()->fetchCol()[0];

If you need to further understand the database schema related to your field, you could try these commands:

mysql> show tables like '%order_reference_number%';

+----------------------------------------------+
| Tables_in_drupal8 (%order_reference_number%) |
+----------------------------------------------+
| node__field_order_reference_number           |
| node_revision__field_order_reference_number  |
+----------------------------------------------+
2 rows in set (0.00 sec)

mysql> describe node__field_order_reference_number;

+------------------------------------+------------------+------+-----+---------+-------+
| Field                              | Type             | Null | Key | Default | Extra |
+------------------------------------+------------------+------+-----+---------+-------+
| bundle                             | varchar(128)     | NO   | MUL |         |       |
| deleted                            | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id                          | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id                        | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode                           | varchar(32)      | NO   | PRI |         |       |
| delta                              | int(10) unsigned | NO   | PRI | NULL    |       |
| field_order_reference_number_value | varchar(255)     | NO   |     | NULL    |       |
+------------------------------------+------------------+------+-----+---------+-------+
7 rows in set (0.23 sec)

mysql> select * from  node__field_order_reference_number;

+--------+---------+-----------+-------------+----------+-------+------------------------------------+
| bundle | deleted | entity_id | revision_id | langcode | delta | field_order_reference_number_value |
+--------+---------+-----------+-------------+----------+-------+------------------------------------+
| page   |       0 |        17 |          28 | en       |     0 | 123                                |
+--------+---------+-----------+-------------+----------+-------+------------------------------------+
1 row in set (0.00 sec)


How to count the number of posts by a author?

If you are using D7 I think you will have to enable aggregation for you view, and then set the group by for you field (Content:nid for example) to Count.


How could I create multiple private sites within one Drupal site?

This seems like a perfect use case for Organic Groups.

  Enable users to create and manage their own 'groups'. Each group can
  have subscribers, and maintains a group home page where subscribers
  communicate amongst themselves.

I'm not going to go in depth with setup or anything, as OG is a beast of a module, but the benefits are immense, and should allow you to do exactly what you need. It's the same module that provides the groups.drupal.org functionality :)

A quick Google search will provide a wealth or information, as will a browse of the organic-groups tag.

Also check these out for a brief overview of OG:

Organic Groups for Drupal 7 (Lullabot)
An Introduction to Organic Groups with Drupal 7 (YouTube/Lullabot/Drupalize.me)


Then better apply strip_tags() on the processed text $node->body->processed. You might also want to apply Html::decodeEntities(). Still take care you configure the text format restrictively, because outputting the text in a non standard way can be a security risk increasing with features you allow. And you don't get security updates for custom code.


Rules Fetch entity by property using fixed User Role

Answering my own quesiton. I guess I should have found this sooner. But writing it down here helped me process the vocabulary I needed to search for.

I do indeed need to switch to direct input mode. In fact if you switch to direct input mode it will give you a list of roles to select. However direct input mode is not available on initial creation.

To fix simply save as some value (I used site:user:role). Then edit the rule again and direct input will be available. It appears to be a bug listed here: https://www.drupal.org/node/2168961

Thanks and hope this helps someone else.


How to set different logout times for roles?

We can achieve that using the Automated Logout module. combination of the Javascript Timer module.
Using the Automated Logout module we can set different timeouts for user roles and using Javascript Timer we can display remaining session time (countdown timer) for a logged in user.
Automated Logout

This module provides a site administrator the ability to log users out after a specified time of inactivity.
It is highly customizable and includes "site policies" by role to enforce logout.
Features

Different timeouts based on role
Disabling of timeouts based on role
Permission for users to set their own timeout
Includes some JS mechanisms to keep uses logged in even if multiple    tabs are open or if the user is working on a form for a long period
of time.
Includes developer hooks to allow users to remain logged in depending    on your own project specific requirements
Optional integration with Javascript Timer Timer


How can I theme "Error generating image." error 500's in Drupal 7?

You can't.

This is hardcoded in http://api.drupal.org/api/drupal/modules--image--image.module/function/image_style_deliver/7.

You would need to completely override this page callback to change what it does. You could do this with hook_menu_alter() but that means that you would need to make sure that you also apply any upstream changes to that function to your own copy.

Can't you just leave the images there instead of deleting them? And if they are just a temporary resource, maybe exclude them from search with robots.txt?


Attributes in table in custom content type form

You will need to override the node form template for your invoice content type with a custom template in your theme. More info -> Theming Node Forms in Drupal 7 and here

In your template you'd build a layout for your fields and output form fields in place like this

<?php print drupal_render($form['fieldname']);?>


Conditional drupal_add_css and _js are adding code to every page

If you are adding drupal_add_css or_js in phptemplate_preprocess_node,

First fetch all the added css in one variable and assign this for $styles value
Same like css you need to do for js also.

Here with see the sample code below

function phptemplate_preprocess_node(&$vars, $hook) { $node = $vars['node'];
if ($node->type == 'mytype') {
    drupal_add_css(path_to_theme() . "/css/mytpess.css");

    drupal_add_js(path_to_theme() . "/javascripts/jquery.masonry.min.js");
    drupal_add_js("$(document).ready(function(){
                      $('.node').masonry({
                        itemSelector: '.field-type-flexifield'
                      });
                    });",'inline');
 }
$css = drupal_add_css();
$scripts = drupal_add_js();
$vars['styles'] = drupal_get_css($css);
$vars['scripts'] = drupal_get_js('header', $scripts);
}


how to pass multiple view fields to an action via vbo in D7?

You sort of can already.
Create the component with three arguments. It will pass the selected node to the first argument. On the second page of VBO you'll have two more fields to fill in. You can enter tokens here e.g. [yourrelationfield1] for fields of your view.


How to fix floated elements extending height of non-floated elements within a single zen theme region?

So, the simplest approach ended up being adding another region to the theme. I made sure to add the region within the content region div to facilitate alignment, this gave me a container to float the block divs altogether with the clear: both declarations messing with the internal layout of the content region.


How to create a Views custom exposed filter with predefined range of date values (today, next 15 days, next month)

I've written a custom module exactly for this purpose but haven't released it as it ended up being a little less abstracted than I'd like.

The way you do it is by writing a Views filter handler (which is surprisingly easy). Without giving the whole game away and leaving a little homework for you: please read on. Let me know how you go.

You'll need a line in your .info file.

files[] = inc/views_relative_date_filters.inc

Register it with the Views API in the .module file.

/**
 * Implements hook_veiws_api().
 */
function views_relative_date_filters_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'views_relative_date_filters') . '/inc'
  );
}

Register the Views handlers inc/views_relative_date_filters.views.inc

function views_relative_date_filters_views_handlers() {
  return array(
  // ...
  );
}

function views_relative_date_filters_views_data() {
  $data = array();
  // ...
  return $data;
}

And finally write the filter itself in inc/views_relative_date_filters.inc

class views_relative_date_filters extends views_handler_filter {
  // You'll need an options form (just use the parent)
  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
  }

  // You can use a views_form or an
  function exposed_form(&$form, &$form_state) {
    // Return a Form API select element
    // ... all, this-day, this-fornight, this-month
  }

  // The query to get your results based on your time period
  function query() {
    $this->ensure_my_table();

    // Get the value of the submitted filter
    if (isset($this->value[0])) {
      $value = $this->value[0];
    } else {
      $value = 'all';
    }

    // A switch on the $value
    switch( $value ) {
      case 'all';
        return;
      case 'this-month':
        // Modify your query with where conditions, groups, joins, whatever
        // ...
        break;
      case 'this-fortnight':
        // Modify your query with where conditions, groups, joins, whatever
        // ...
        break;
      case 'this-day':
        // ...
        break;
      case default;
        break;
    }
  }
}


How to read a Entity reference node's fields?

<?php

/**
 * We define a new function in our MODULE and will simply use it where needed.
 *
 */

/**
 * @param (object) $node
 * @param (string) $field_name
 * @return false|null|integer
 *    The target id. FALSE on error. NULL when no reference found.
 */
function _MODULE_get_node_reference($node, $field_name) {
    $target_id = null;
    if (!isset($node->type)) {
        return false;
    }
    // In case of any exception we simply return false.
    try {
        $entity_wrapper = entity_metadata_wrapper('node', $node);
        if (isset($entity_wrapper->{$field_name})) {
            $target_id = $entity_wrapper->{$field_name}->value();
        }
        // maybe we are in the middle of a DB transaction. In that case entity_metadata_wrapper() would not work
        if (empty($target_id)) {
            // So, we try using Fields API. This always works.
            $items = field_get_items('node', $node, $field_name);
            if (isset($items[0])) {
                $target_id = $items[0]['target_id'];
            }
        }
    } catch (Exception $e) {
        return false;
    }
    return $target_id;
}

?>


Here are some quick code examples that I have used to add or remove user roles in Drupal 6. This can be very helpful if you are building a module for a specific site that has to manipulate user roles. Using this technique is not the most flexible solution as it limits itself to the roles configured on a specific site (based on role id and role name). However, you could easily add a database table and an administration section and make this more flexible if needed.

Here is an easy way to add a role:

//you will need to enter the uid of the user here, I am just using user 1

$user = user_load(1);

//first we check if the user has the role in question (using the rid of the role)

if (!isset($user->roles[7])) {
    //if not we add the role and set the role name based on what is entered
    //in the drupal role administration section
    $user->roles[7] = 'role name seven';
}

Here is an easy way to remove a role:

//you will need to enter the uid of the user here, I am just using user 1

$user = user_load(1);

//first we check if the user has the first role in question

if (isset($user->roles[8])) {

  //if so, we unset the role
  unset($user->roles[8]);

  $edit = array('roles' => $user->roles);
  user_save($user, $edit);
}

Here is an easy way to do a role swap:

//you will need to enter the uid of the user here, I am just using user 1

$user = user_load(1);

//first we check if the user has the first role in question

if (isset($user->roles[8])) {

  //if so, we unset the role
  unset($user->roles[8]);

  //now we check to see if they have the role we want to swap for
  if (!isset($user->roles[7])) {

    //if not we add this role
    $user->roles[7] = 'role name seven';
  }

  $edit = array('roles' => $user->roles);
  user_save($user, $edit);
}

check this link for more info my post
 How to remove all roles from a user?


Panels and Page Manager in Drupal 8 are under heavy development, so probably it's a temporal problem.

In Drupal 7 Page Manager is a submodule of CTools, but in Drupal 8 is a standalone module. The reason for this is Page Manager tasks (configuring UI) are very important but Panels wants to remain independent from the UI. This makes sense, as each module focus on its duty (Panels on doing its magic, Page Manager in configuring Panels through the UI).

To be more accurated Panels in Drupal 8 can be implemented. Currently, Page Manager and Panelizer implement panels.

So now they are not working together, but eventually they should, that's the target.


Access denied for user anonymous while accessing custom table data

Following up with an answer from our comments...

Here's an example custom service resource:

custom_data.module

function custom_data_services_resources() {
  $resources = array(
    'custom_data_resources' => array(
      'actions' => array(
        'getdata' => array(
          'help' => t('Gets custom data.'),
          'file' => array(
            'type' => 'inc',
            'module' => 'custom_data',
            'name' => 'custom_data.resource',
          ),
          'callback' => 'custom_data_getdata',
          'args' => array(
            array(
              'name' => 'data',
              'type' => 'array',
              'description' => 'The data dude.',
              'source' => 'data',
              'optional' => FALSE,
            )
          ),
          'access callback' => 'custom_data_access',
          'access callback file' => array(
            'type' => 'inc',
            'module' => 'custom_data',
            'name' => 'custom_data.resource',
          ),
          'access arguments' => array('access user profiles'),
          'access arguments append' => TRUE,
        ),
      ),
    ),
  );
  return $resources;
}

custom_data.resource.inc

function custom_data_getdata($data) {
  return array('foo' => $data['bar']);
}

function custom_data_access($permission) {
  return user_access($permission);
}

After that, just enable the custom resource under your endpoint's configuration and clear all of Drupal's caches. Then you can make a POST to:

?q=[my-endpoint]/custom_data_resources/getdata.json

If you need to send along custom arguments, I usually recommend a single array parameter, that way you can easily expand upon it and send as many variables/properties you need along with the payload:

{ "bar": 123 }

Which will then return to you:

{ "foo": 123 }

Don't forget to attach a header to your request with a name of X-CSRF-Token and value retrieved from: ?q=services/session/token


Alter Block render array and add another block's content

Here is an updated function taking into account some of the various types of blocks that we can attach blocks to.

function MODULE_block_view_alter(&$data, $block) {
  if (!empty($block->block_attached_block)) {

    // load the attached block from the database
    $attached_block = db_select('block', 'b')
      ->fields('b')
      ->condition('b.bid', $block->block_attached_block)
      ->execute()
      ->fetchObject();

    // render the block
    $block_content = _block_render_blocks(array($attached_block));
    $build         = _block_get_renderable_array($block_content);

    // create attached block render array
    $block_attached_block = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('block_attached_block'),
      ),
      'block' => $build,
    );

    // attach the block
    switch ($block->module) {

      // menu block module blocks
      case 'menu_block':
        $data['content']['#content']['block_attached_block'] = $block_attached_block;
        break;

      // views module blocks
      case 'views':
        $data['content']['#markup'] .= drupal_render($block_attached_block);
        break;

      // block module blocks
      // webform module blocks
      case 'block':
      case 'webform':
        $data['content'] .= drupal_render($block_attached_block);
        break;

      // all other module blocks
      default:
        $data['content']['block_attached_block'] = $block_attached_block;
        break;
    }
  }
}

Thanks Clive for getting me started on the right path.


Theme template.php functions after bootstrap

While what you are doing could work, this is not what you want to do. If you want to render your menus outside Drupal you should do it a more  robust way to implement this using Drupal best practice etc.

One way would be to

create a public URL that returns the menus. This could return just the data or markup.
Have you custom code consume the API, so you fetch the data via http instead of manually trying to bootstrap Drupal.

You also need to ask yourself why this custom code lives outside Drupal. If you can bootstrap Drupal etc, the code might as well be part of Drupal via a module.

Boostrapping Drupal yourself is possible but a lot of crazy bugs can show up. Drupal depend on a lot of various stuff like $_GET / $_POST and other stuff that you might forget to handle. Also if you update Drupal this code can easily break as you are using internal functions which can change in various ways.


Redirect anonymous users to login when they try to access home page for omega sub theme

Implement a hook_init().

function YOURMODULE_init(){
  global $user;
  if($user->uid == 0){
    drupal_goto('user/login');
  }
}

This will work but if you have cache / reverse proxy cache enabled then you might need to consider about a JS solution too.


how to update the order total in checkout page?

You need to use hook_form_alter().

First, for integrity purposes, write a validator that will ensure all amounts are correct, and if not - update them & show form to user again.

Second - use AJAX. Drupal allows only for one callback, so your new one will have to take care of calling the original one in the first place, and you may have some problems if you will need to replace more than one form element, but it can be done.


Apply page template suggestion to a specific view by a hook?

First of all, the code is never run, because you have the hook page in the function name and check for the hook views_view. Secondly the variables in a page hook don't contain variables from the view, so you have to get them from the route:

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

  $view_id = \Drupal::routeMatch()->getParameter('view_id');
  if ($view_id === 'movies') {
    $suggestions[] = 'page__movies';
  }

}


How to get all node entities tagged with a specific term?

You can use loadByProperties() to get all node entities that reference $term_id:

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'field_tags' => $term_id,
]);


Create a new image style of any size you want to open the image in colobox.
Now browse to manage display of your content type.
Select the formate 'Colorbox' for image field.
Add newly created image style for Colorbox image style, please follow below screenshot.


Only admin can see products page for Drupal Commerce

Go to Admin menu > People > Permission:
Check 'Authenticated User' for:

'View any product of any type' from 'Product' group
'Access checkout' from 'Checkout' group


Custom block build function to display wysiwyg body text

Assuming you store the block configuration via a text_format form element as in https://drupal.stackexchange.com/a/278811/47547
src/Plugin/Block/ExampleBlock.php
<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides an example block.
 *
 * @Block(
 *   id = "mymodule_example",
 *   admin_label = @Translation("Example"),
 *   category = @Translation("mymodule")
 * )
 */
class ExampleBlock extends BlockBase {

  public function blockForm($form, FormStateInterface $form_state) {
    $body = !empty($this->configuration['body']) ? $this->configuration['body'] : [];
    $form['body'] = [
      '#type' => 'text_format',
      '#title' => 'Body',
      '#format' => isset($body['format']) ? $body['format'] : 'full_html',
      '#default_value' => isset($body['value']) ? $body['value'] : '',
    ];
    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['body'] = $form_state->getValue('body');
  }

You would output the wysiwyg content via processed_text:
  public function build() {
    $build = [
      '#type' => 'container',
      'label' => ['#markup' => 'Body: '],
    ];
    if (!empty($this->configuration['body'])) {
      $build['body'] = [
        '#type' => 'processed_text',
        '#text' => $this->configuration['body']['value'],
        '#format' => $this->configuration['body']['format'],
      ];
    }
    return $build;
  }

}


How can I retrieve the current node ID on a custom route?

Your route doesn't have a parameter called node, so therefore $node is null.

In order to make node available as a parameter you have to be on a route that has node as a parameter.

So to add the node parameter to your route, you can do like this:

rsvplist.form:
  path: '/rsvplist/{node}'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'
    _entity_access: 'node.view'
    node: \d+

And then you can add the $node parameter to your buildForm method, like this:

public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
  // Your form.
}

Since I added node: \d+ to your form, $node is now the loaded entity in the buildForm method.


Why is my migrate source plugin (d7_file) not found for my migration?

Make sure the migrate_drupal module is enabled. (I can't be sure that's the reason, but it's the first one I stumbled over when I reproduced this locally.)

The reason this isn't easy to see:

Migrate plugins have multiple providers (which must all be enabled to use the plugin), and the relevant plugin managers actually use their own discovery which automatically infers providers from the parent class namespace. So the d7_file plugin has the providers "file" and "migrate_drupal" as it is provided by the file module but extends a class from the migrate_drupal module.

In effect, migrate's multi-provider thing adds "invisible" dependencies which silently remove the plugin when the required modules aren't installed.


How can I correct a word on the CKEditor field?

According to AdamPS in Enable browsers' (native) spell checker in CKEditor

  2) If you browser supports spelling suggestions, the way to access
  them in Drupal is slightly different. When you are in an edit area,
  then the normal browser context menu may be replaced by the editing
  context menu. However you can access the browser menu by clicking
  Control. [But on a Mac it is potentially command and on a tablet
  ....??]

You need to hold down CTRL before right clicking. (which worked for me on Windows OS)

An alternative would be to install the SpellCheckAsYouType(SCAYT) plugin for CKEDITOR

  Note: You have to build a custom module to install CKeditor plugins in
  D8.


Make a directory and link it in a node at node creation

Creating directories on the fly in the actual file system is uncharacteristic in Drupal.

The simplest way of attaching photos to nodes would be having an image field with unlimited number of uploadable images. That would show thumbnails of those related images right there when you go to the node page. This is all in core.

If allowing all users to edit event nodes is not an option, you could create an image node type and connect images to respective events with node references or taxonomy, and then create a view listing those images on the node page (views attachment) or on a separate, gallery page.


After installing any module I get "The website encountered an unexpected error. Please try again later."

Enable error reporting in Drupal. This way, Drupal can print the errors and stack traces on the page when the errors occur. Also, consider enabling the module using Drush particularly with --verbose and --debug options. This prints logging info while enabling the module.

The source of this could be anything. It could be a bad module install script, bad configuration, bad module hook code, or a malformed template (for that page). I usually get these pages when code tries to access non-existent properties or indexes or have modules that don't play nice with each other. This usually look harmless. But if the error cuts into execution and there was data that was still to be saved, it might result in a bad system.


Dynamic parameters passed to page callback

$items['products/autocomplete.json/%'] = array(
    'page callback' => 'json_list_products',
    'access arguments' => array('access products'),
    'page arguments' => array(2),
  );

view the documentation at this link


Alternative to Simplenews, or a way to send formatted mailing lists to subscribers?

Check out the new Newsletter module.

Features

Multiple newsletters lists configurable on terms, not vocabularies
Plain text or HTML out of the box
Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new posts for this term.
Centralized administration and configuration on single page.
Users can customize the terms in the list they subscribe to
Custom template per list
Statistics (CTR and Open-Rate)
Drupal 7 only


How do you refer to the field in views-view--field-fieldname.tpl.php?

File field has formatter "URL to file", please see this screenshot:

So finally, in $output will be only url to file.

Also, if you don't want any views default wrappers, you can unselect checkbox in "STYLES" fieldset (see screenshot abowe).


"Add content" button on related content node?

You are doing redundant work by having a node reference field. If "shop" is set up as a group post, you should be able to add new shops when in a shopping center context. There should be some kind of "group options" block that will give you these options. (Haven't done this exact thing in 7 yet but it must be similar to the way it works in 6).


How to delete folder along with the files from database also?

file_unmanaged_delete_recursive(), as the name implies, removes any files under a directory without concern to managed files (i.e. files tracked in the database).

In order to remove files from the database, you can make use of the file_delete() function in the File API. This function needs the file ID supplied as an argument, so you'll need to perform a query on the database to retrieve it. For example:

$files = file_scan_directory('sites/default/files/my_custom_dir', '/.*/', array('recurse' => TRUE));
foreach($files as $file) {
  $scanned_file_uri = file_build_uri($file->uri);
  // @TODO: query file_managed.uri for match with $scanned_file_uri
  // then delete with file_delete();
}


Multilingual settings form using i18n variable

I was in a need to create translatable strings for text entered using Page title module and I used the following code to create variable

function module_variable_info($options) {
    $variables['page_title_type_news_and_event'] = array(
    'type' => 'text',
    'title' => t('Page title CT New Events', array(), $options),
    'default' => '',
    'description' => t('Module : Page title', array(), $options),
  );

  return $variables;
}

Now I can see them in others tab at admin/config/regional/i18n/variable and I enabled the check box there

Then I can translate my string at admin/config/system/variable and at others tab


Warning: Invalid argument supplied for foreach() in views_php_handler_filter->php_post_execute()

The error is here:

$view->result = null;

Try changing it to:

$view->result = array();

Views is running over the $view->result var as an array without checking its type, but it's always expecting an array. As NULL isn't an array it complains, but it's just a Warning so the script continues. Because the results loop has failed you get the same effect as when the array is empty, and as you say everything works as expected.


ajax http 500 error while editing panel in drupal 7

Please check below configuration & update :

php.ini

  max_execution_time = 30 --> 60 ;

  memory_limit = 32 --> 128, or even 256M ;

.htaccess

Add the below lines :

  php_value auto_append_file none

  php_value memory_limit 128M

my.ini

  max_allowed_packet = 4M --> 64M


D7 - Multilingual in the admin, only one language for the users

We ended up writing various custom modules to solve that issue.


How do I avoid the HTML I enter is altered?

It's probably not just CKeditor altering your HTML. You should look into the configuration of your input formats at /admin/config/content/formats. There is documentation on https://www.drupal.org/docs/8/core/modules/filter/overview, although it's not very detailed.

An input format applies one or more text filters to your input. Common filters are the HTML Filter, that allows only a limited number of HTML tags, and the Line Break Converter, which turns line ends into <br> or <p> tags. You can configure your input format, or create a new one, without any filters.

If I recall correctly, even if you don't have any text filters configured, Drupal may still strip some HTML tags that are considered particularly dangerous, like the <script> tag.


How to add twig code in View 'global custom text' field?

I try that right now and worked for me.

Note: just make sure set Output format to 0/1

{% if  status  %}

 APPLY

{% endif %}


Using Features to create module with nested field collections

Turns out I was running into some limitations in the Features export module (including some obscure bugs) and a misunderstanding of part of the return result for hook_node_info.  All it took was three solid days of debugging and I got it working.  So this one can go away now; given its limited usefulness, I don't mind if an admin wants to just delete the whole question.


How to add an "apply for a job" button to a content type?

I would do that using Flag module, create a flag named 'Apply' and set it for job content types. You can then use Flag Actions or Rules to send emails.


Mapping split taxonomy terms to new vocabs in nodes in migrate_d2d

As a possibility I mentioned above, I did some wrangling in the prepare() method to move the terms from field_people_organizations to field_journalists and field_non_journalists.

  function prepare($entity, stdClass $row) {
    // Turn off pathauto generation for the node so we end
    // up with only one alias record.
    $entity->path['pathauto'] = 0;

    // Need to manually move any items that should be in the Journalists and Non-Journalists
    // vocabularies there from People and Organizations, since migration mapping doesn't
    // seem to be working.

    // First, see if the nb_migrate_users array is already cached.
    $nb_migrate_journalists = & drupal_static(__FUNCTION__);
    if (!isset($nb_migrate_journalists)) {
      if ($cache = cache_get('nb_migrate_journalists')) {
        $nb_migrate_journalists = $cache->data;
      }
      // Not cached, so we need to generate it this time through.
      else {
        //Get new tids for terms mapped in migrate_map_jounralists.
        $query = db_select('nb_migrate_journalists', 'nmj');
        $query->fields('nmj', array('journalists', 'non_journalists'));
        $query->innerJoin('migrate_map_peopleorganizations', 'mmp', 'nmj.tid = mmp.sourceid1');
        $query->addField('mmp', 'destid1');
        $result = $query->execute();

        foreach ($result as $record) {
          // Use the target vid for the vocab; 5 = Journalists, 7 = Non-Journalists.
          if ($record->journalists == 'x') {
            $nb_migrate_journalists[$record->destid1] = 5;
          }
          elseif ($record->non_journalists == 'x') {
            $nb_migrate_journalists[$record->destid1] = 7;
          }
        }
        // Cache the array.
        cache_set('nb_migrate_journalists', $nb_migrate_journalists, 'cache');
      }
    }
    // Move terms in array based on values in field_people_organizations and $nb_migrate_journalists.
    if (isset($entity->field_people_organizations[LANGUAGE_NONE][0])) {
      foreach ($entity->field_people_organizations[LANGUAGE_NONE] as $key => $term) {
        if (in_array((int)$term['tid'], array_keys($nb_migrate_journalists))) {
          if ($nb_migrate_journalists[$term['tid']] == 5) {
            $entity->field_journalists[LANGUAGE_NONE][] = array('tid' => $term['tid']);
          }
          elseif ($nb_migrate_journalists[$term['tid']] == 7) {
            $entity->field_non_journalists[LANGUAGE_NONE][] = array('tid' => $term['tid']);
          }
          // Remove term from field_people_organizations.
          unset($entity->field_people_organizations[LANGUAGE_NONE][$key]);
        }
      }
    }
  }

I still think there is probably a better way to do this within the class constructor, so if at some point in the future you read this and know that answer, please add it here.

Thanks.


How to set translated variables' values from settings.php (or similar)

In settings.php

$conf['MODULE_i18n_variables'] = array('my_variable');
$conf['my_variable'] = 'default value';
$conf['my_variable__fr'] = 'french value';

And in a custom module

/**
 * Implements hook_init().
 */
function MODULE_init() {
  global $conf, $language;
  if (is_array($conf['MODULE_i18n_variables'])) {
    foreach ($conf['MODULE_i18n_variables'] as $variable) {
      if (isset($conf["{$variable}__{$language->language}"])) {
        $conf[$variable] = $conf["{$variable}__{$language->language}"];
      }
    }
  }
}

This work as long as other languages values are not used. For instance, a multi-language aware edit form for the variable will not reflect the enforced per language values.


The update manager module makes admin pages very slow, what might be the causes and how could I solve this problem?

Update module is slow when site is behind a router or firewall:

https://drupal.org/node/369145

  The Update Status module attempts to get update information using the
  internet. Many servers have firewalls that block this.

That means that Drupal tries to access the Internet, but if the site is behind a router or a proxy the petition probably is ignored, so Drupal is 'stalled' waiting for response. When Drupal is tired of waiting (the petition timeouts), usually several seconds after, the page request continues and finllay Drupal delivers the page. You feel that the site is slow, but in fact Drupal has been waiting same as you.

The solution is to disable Update module in dev environments, or allow the site to connect to Internet to get the update information.


Sub Menu's are not coming under main menu

You can use Nice Menus to solve your issue.


If you force https, then these search forms and views should load properly. There are several ways to do this:

1) If you have access to server config, this tutorial covers Apache, Nginex and Ubunto.

2) You can also use .htaccess to force https as described in this codekarate tutorial.

3) Also you can use a module like securelogin to further protect your login forms from mixed http/https cookie hijacking.


The node author is usually editable in the 'Authoring Information' tab/section of the node-edit page. If that data isn't available for you (may have been removed by another module or other customization).

If you're comfortable editing the data in the database (via phpMyAdmin or another tool), have a look at the node table. You will see that each row contains a value in the uid column - this refers to the user id (uid) of the authoring user. User ids can be matched up to the corresponding users in the users table. Simply update the uid value in the node table for the appropriate nodes (likely ones with uid = 0) and you should be good to go.


Using panels and\or contexts to build simple blog w/ static menu

It is simple to do:

set up your panel as normal - include the 'block' of information you want visible in the section you want it
click on the settings icon and select Visibility: Add new rule:

This allows you to set the conditions under which that particular block of information will be visible. You can have it appear only on nodes of a particular type for example.


Map array of node IDs to bundle types without loading all the nodes

Rather than trying to load all nodes, you can query the DB directly for the nid/type (Bundle) pairs you need. Query the node_field_data table and use the IN operator to retrieve all the relevant nids you need.
$nids = [1, 2, 3];
//@TODO: add select query on node_field_data
$query->condition('nid', $nids, 'IN');
//@TODO: execute query and array map results

See the drupal.org docs on using IN operator in dynamic queries.


Adding the response I gave on Drupal.org:

The issue is that you are rendering the form with the theme() function, in the form definition. Instead, you need to identify the form as using a #theme, and let it be rendered downstream:

So remove this:

$form = theme('atavism_license_list_view', array('form' => $form));

And add this:

$form['#theme'] = 'atavism_license_list_view';

Link: https://www.drupal.org/forum/support/module-development-and-code-questions/2019-03-07/custom-template-file-for-modules#comment-13019068


Facebook share in drupal7 sharethis module picking wrong thumbnail image

Did you test the page with the Facebook Debugger?  Remember that Facebook caches page info, so changes don't appear immediately.  A side effect of the debugger is that it clears the cache when you test a URL, so changes get picked up.

If you wan to use a specific image, you need to be sure it explicitly has an og:image element in the header.  I am pretty sure this is something that the Meta Tags module can do this for you.


How to alter the welcome message after successfull registration

you can achive this and much more similar things with LoginToboggan module, from module page:

  The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
  Allow users to login using either their username OR their e-mail address.
  Allow users to login immediately.
  Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
  The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
  Customize the registration form with two e-mail fields to ensure accuracy.
  Optionally redirect the user to a specific page when using the 'immediate login' feature.
  Optionally redirect the user to a specific page upon validation of their e-mail address.
  Optionally display a user message indicating a successful login.
  Optionally combine both the login and registration form on one page.
  Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
  Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)

UI settings are simple and straight forward, and are located in admin/config/people/accounts


Any way to flag users who previously submitted a webform on revisit?

The table webform_submission has everything you need. The webform nid and the uid.

You could implement hook_user_login and set a flag in the current $user object if the form has been submitted. Then check for this flag where ever you need it.


AFAIK there is currently no core UI to control showing/hiding of those tips.

Th simplify module, one of the D7 choices you link to, has a D8 port that may still help with this.

The Allowed formats module is an incubator for future core improvements in the area of giving sitebuilder's UI control over text format and their help tips.

== UPDATE ==

A patch just committed to that module gives sitebuilders considerable control over help tips, using UI settings on the widgets.

== OLD ==

There are a couple of relevant issue in the issue queue for that module:

Allow to control if "About text formats" link should be shown or not

Allow to hide text format help text for Text(formatted)

The first of those issues contains this code from floretan, which points in the direction you would need to go to hide the help by custom code:

<?php
/**
 * Implements hook_field_widget_form_alter().
 */
function allowed_formats_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  if ($context['widget'] instanceof \Drupal\text\Plugin\Field\FieldWidget\TextareaWidget) {
    $element['#after_build'][] = '_allowed_formats_remove_textarea_help';
  }
}

/**
 * #after_build callback.
 */
function _allowed_formats_remove_textarea_help($form_element, FormStateInterface $form_state) {
  if (isset($form_element['format'])) {
    // All this stuff is needed to hide the help text.
    unset($form_element['format']['guidelines']);
    unset($form_element['format']['help']);
    unset($form_element['format']['#type']);
    unset($form_element['format']['#theme_wrappers']);
  }

  return $form_element;
}
?>


How to approximate user location on IP&Geoloc maps

So, there's probably several ways to do this and your approach will depend on exactly what your needs are for this app.

If you need to preserve the geofield data accurately in the db, but you just want to change the display, you'd need to write a script to modify the Leaflet JS create.point function. This is complicated because you'll have to consider things like the visual context of what you're mapping (i.e. if there's only one house in an area, then even abstracting the location won't really accomplish what you want). Also, your changes will get wiped if your not careful upgrading modules potentially exposing the addresses your trying to hide (depending on how sensitive your data is, this may expose it as well, because someone might be able to dig through the JS and extract the original coordinates). This is also complicated, because simply randomizing the lat-lon data will produce really wonky map results (here's an alternate approach to randomizing user data. I would think that a good approach would be to choose a distance offset, and then randomly apply it to either the lat or lon value. This will keep your point close to where it should be, but it will be offset on either the X or the Y axis to the point where it shouldn't be on the exact location. You could also take the approach where you mis-match the real locations of the users to other users.

If you don't need to store the Lat-Lon accurately, you could write a custom module to hook into the geofield_compute_location function and apply your offset there. This will keep your addresses intact and then apply a similar function to the lat-lon values returned by whichever service is providing your geocoding. This will give you obscured location data to pull into your view.

There's also probably a way of modifying the geocoding request to only provide city-level accuracy, but this is getting over my head.

Hope this helps.


Font-Awesome issue: how to remove menu-link text from a menu item with font-awesome icon?

In this case you're better off using a background image. Save yourself the hassle.

.menulink{
  Width: 25px;
  Height: 0;
  Padding-top: 25px; /* height of image */
  Overflow: hidden;
  Background: url(images/home-25x25.png) 0 0 no-repeat;
}


Basically your patch have to be applyable with the command

patch -p1 < $filename.patch

http://drupal.org/node/707484 is a pretty good tutorial how to create patches so the testbot can use it.


Start wherever it makes sense to you. Your project sounds iffy if your not hired directly by any of these entities to promote their products.

I'd recommend a content type or entity as Accessory and then taxonomy terms for Make Model and Years of cars which will facilitate searching.

Start with that site structure, if it doesnt work for you then change it later.


Salesforce API module encryption warning

This is most likely related to AES encryption on your Salesforce credential data, not the connection itself. From the relevant doc page:

  By default, all Salesforce credentials are stored in the variables table, unencrypted. If this is a problem for you, this module supports encryption via the AES module

When you have the AES module enabled (which it seems like you do), the message you see in your site status report is:

  Salesforce encryption is enabled but not configured securely.

And if AES is not enabled, you see this instead:

  Encryption is unavailable. Using encryption is recommended in order to better secure your data.

Check out salesforce_api_requirements() and salesforce_api_encryption_available() for more. From the logic in the latter it looks like there was an attempt to return more useful information (specifically about the AES module) along with that generic "salesforce encryption" message, but for whatever reason that text never propagated up to what was printed to the screen.


Why is my form_token missing when i'm not logged as admin?

The problem comes from the antibot module.

For some reason that I don't know, when I am not logged in, the module considers that I do not have javascrip enabled and overrides the form_token field which is required to submit the form.


Yes!

You should consider Drupal 6 without phpass to be unnecessarily insecure.  And yes, you should use phpass on all your D6 apps.  There are reasons they've changed the way things work in Drupal 7, and made the same changes available as a module to D6 users.

There is no silver bullet, but there's no reason to ignore an easy-to-use module that will significantly increase your level of security.

Not using it is a little like not wearing a seat belt: of course you want to avoid ever being in an accident to begin with (analogous to ever letting anyone gain access to your data), but once you have an accident it's far too late to try buckling up.  Buckle up now!

Update: A security expert seems to agree with me:

  ...take the view that attackers will ultimately get into your network, access your data... you should be looking at the problem differently.


How do I change base URL when moving site from sub-directory to domain root?

Unless you have made customizations to the URL-related settings in .htaccess or your settings.php, you won't need to update anything. Simply move your site, then clear the cache either via the "Clear Cache" button (on the Performance admin page), or the Drush utility, and you should be good to go.


Editing the post time displayed for comments in Drupal 7

There is a native function in Drupal to format date intervals, it is called format_interval.

Usage example:

 // Date since forum post was created
 format_interval(REQUEST_TIME - $variables['topic']->created)

Hope this helps, happy coding!

PS: See the answer I gave on your stackexchange post for the longer custom version you can also use.


User list with View: display only on role

I think you should use Views PHP module. here you can able to write custom code. May be it'll helpful to you.
You want approx this kind of view?

For that you should try View Php Module. After that choose Global Php option in field tag and then write your code. I tried this may be it's not feasible, but here is the code.

In output section:-

<?php
$roles = array();
$user = user_load($row->uid);
$roles = $user->roles;
if (array_key_exists("7",$roles)) {
   // admin role has rid 7
   unset($roles[7]);
}

foreach ($roles as $key => $val) {
 echo $val."<br>";
}

?>


Editable Fields, Custom Submit function is not being called?

You can try this:

function apws_extras_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
case 'editablefields_form_node_field_apws_batch_completed_field':
      if ($form['type']['#value'] == 'apws_batch') {
        $form['#validate'][] = 'apws_extras_batch_completed_form_validate';
        //$form['#submit'][] = 'apws_extras_batch_completed_form_submit';
        $form['actions']['submit']['#submit'][] = 'apws_extras_batch_completed_form_submit';
      }
      break;
  }
}

function apws_extras_batch_completed_form_validate(&$form, &$form_state){
  // Check if this field is set.
  // Code for validation here.
}

function apws_extras_batch_completed_form_submit(&$form, &$form_state) {
  drupal_set_message('Submit is working');
}


How to track and notify employees when their certifications have expired?

Your question doesn't specify how such notifications should be implemented. Though there are at least 2 possible implementations:

Send an eMail to such employee when the time is right.
Create some type of alert when the employee visits the site.

Read on for more details about either implementation.

Create an alert

Enable the Menu Badges module, which can be used to add notifications to any menu item and/or menu tab of your choice. Here are some details about it (from its project page):

  Provides a method for adding iOS-style badges to menu items. (see screenshot)

Because of how it integrates with the Views module, you basically reduce the solution specific to your question here to something like this:

Create an appropriate view about "expired certifications" (as in your question).
And create a menu item or menu tab for it.
Perform the required Menu Badges configuration to tell it which menu item/tab you used for it in your view.

Refer to the video Defining Menu Badges with Views in Drupal (from the module maintainer) for more details.

Send an eMail

You could use the Rules module to send an eMail when the time is right. To do so, have a look at the question about "Rule to store user's last post date and scheduled rule based 30 day reminder", which may be considered as a variation of this question here. My answer to that question should be pretty close to what you're looking for.

If you'd replace field_next_article by an "expiration date" of a certificate, you already have what's suggested in "Step 1". You should be able to reuse most of the Rules Component included in Step 2, and the Rule included in step 3, with only some minor changes.


$styles is a variable. It's initialised and made available to the template via the core template_process_html() function.

To add CSS you can use drupal_add_css(), and to add JS you can use drupal_add_js(). Either can also be accomplished using the #attached property in a render array (which is actually the recommended approach these days), or by including scripts/stylesheets keys in your theme's .info file.

Where you can add it depends on what context you need to add it in. This could be page callback, one of many alter hooks, a process or preprocess function, and so on. If your new CSS applies to every page, it might make sense to use the info file method.

Alternatively, if you want to override the CSS of an existing theme, you can create a sub-theme and simply modify the appropriate CSS files without having to use the API.

If you're brand new to Drupal there are a few concepts you need to understand before any of this will make sense. I recommend reading the following:

Theming Guide
Preprocess and process functions
Render Arrays in Drupal 7
Writing theme .info files
Creating a sub-theme


How do I alter a view query to use "OR"?

This is untested, but I think what you want to do within your alter function is along the lines of this:

function mymodule_views_query_alter(&$query) {
  unset($query->where[0]['clauses'][2]);
  unset($query->where[0]['clauses'][3]);

  $query->where[1] = array(
    'clauses' => array(
      0 => 'node.promote <> 0',
      1 => 'node.sticky <> 0',
    ),
    'type' => 'OR',
  );
}

This is essentially moving the promote and sticky clauses into a new where grouping, and by setting the type to 'OR', it should work the way you outline in your question.


I just added a block with following code to the content region of my administration theme


In the EVA Field display of the View you'll see a section there called "Entity content settings." Make sure the settings there are as follows:

a. Entity type: Node
b. Bundles: select the event type content type that you want to appear at the bottom.
c. Arguments: Choose: "Use tokens from the entity the view is attached to" and then add the following token (with brackets) where it asks for the token: [node:author:uid]

Now set the contextual filter for the EVA field display as follows:
Author uid
with the following setting:
Provide default value: User ID from URL.
Optionally, if you want to include something like "Events created by Jane Smith" at the top of the EVA view, then you need to add a relationship to the User. Then in the "Fields" section add user name and set it to "Exclude from display." Create a header for the view and choose "Global text" and check on the functionality to allow the use of tokens in the text. The user name token will be [name].

That's it. You'll be good.

I think it is worth to note what's a bit confusing here. It might help you to remember next time.
a. "User ID from URL" is really a misnomer. It's getting the User id from the node. The user id is not in the URL at all.
b. It feels like the filter/argument is being set twice; once in the Entity settings and then again in the Contextual filter settings.


How do I create content during site installation?

There are few ways in Drupal 8 to manage site default content:

Default content module allows to export/import content via drush and store the content in the structure similar to config in Drupal core.
Umami profile in Drupal core has a custom importer which loads the content stored in CSV to be important as part of module install.
Migrate CSV plugin allows to important the content from CSV using Drupal core migration API.
Single File Components could be used to provide content with components.


"The website encountered an unexpected error. Please try again later."

This error comes from an uncaught PHP exception. Drupal catches exceptions so no ugly PHP error message is displayed to user. You can find the exception info in the 'Recent log messages' link on Reports (or try this path: /admin/reports/dblog). Make sure 'Database logging' module is enabled because this module provides this report.

You will see all the internal messages that have been generated. Filter by type 'PHP' and Severity 'error' and you'll probably find a message about an uncaught exception. This is causing your problem. Now you have more information so you may be able to fix it.


Upgrading from d6 to d7: getting puzzling 'requirements problem' error

Before upgrading the drupal core, you must deactivate your contrib modules. I think you did not.?

Upgrade the core first. Then upgrade any contrib modules.
If you have used cck in drupal 6, you will need the cck module to do the migration.


How can I hook into the system Contact form Message Sent process and alter the HTML generated?

Sure, just use hook_form_alter() and add a callback to $form['#submit']. The easiest way to find your form's id is inspecting it using firebug. This article has a lot more detailed info: http://www.lullabot.com/articles/modifying-forms-drupal-5-and-6.

In short:

Find the id for the contact form, "contact_mail_page" or something (notice how hifens turn to underscores)
In a new custom module implement either: yourmodule_form_alter($form_id, &$form, 'contact_mail_page') or yourmodule_form_contact_mail_page_alter($form_id, &$form)
Modify the contact form as you want using the $form variable passed by reference


Template suggestion doesn't work with a custom menu link (custom route)

I'm guessing you put the template in your module folder and not in a theme?

You need to register the template with something like this in your .module file:

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  $theme['page__mycustomtemplate'] = [
    'template' => 'page--mycustomtemplate',
  ];

    return $theme;
}


D7 in sub directory - Not able to log in

The server gone away error is an error that happens when the client cannot connect to the  database server, and it can happen because:

The client doesn't have the necessary privileges to access the database
There has been a timeout on the TCP/IP connection
The client is running on Windows, and the server dropped the connection, probably because a timeout

When I got that error on my sites was always because the credentials I used in the settings.php file were wrong.
The other reason to get that error is that the value of max_allowed_packet is too small.


How to add an sms:number link to a menu?

On the sites/default/services.yml

There is an option called filter_protocols

Add sms to it.

If file is not available, copy the file from default.services.yml to services.yml


How to allow direct user input links the Facebook way?

You are looking for oembed, there is a Drupal module for it as well, that offers integration to media and some other modules.

  This module will allow your Drupal site to embed content from
  oEmbed-providers as well as for the site to become an oEmbed-provider
  itself so that other oEmbed-enabled websites can easily embed your
  content.

This won't give you a facebook experience out of the box, you still have to configure quiet a lot, you might want to read up on this: #2108973 Making oEmbed module work with WYSIWYG and CKeditor, which also links #2269433: Support URLs on a line by themselves in ckeditor/WYSIWYG.


Override contrib Disqus behavior settings

You can also use hook_js_settings_alter Something like:

/**
 * Implements hook_js_settings_alter().
 */
function YOURMODULE_js_settings_alter(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  if (isset($settings['disqus'])){
    // Change settings here
    $new_disqus_settings = [];
    $settings['disqus'] = $new_disqus_settings;
  }
}


The jquery approach to achieve this one which worked for me (drupal 7) is the following code

$("#edit-pass").keypress(function(event) {
  if ( event.which == 13 ) {
    $('#edit-submit').click();
   }

});

$("#edit-name").keypress(function(event) {
  if ( event.which == 13 ) {
    $('#edit-submit').click();
}});

#edit-name and #edit-pass are my two login fields.


Drupal 6 to Pressflow migration: MyISAM to InnoDB?

You should be fine going from Drupal 6.19 to Pressflow 6.22 but make sure you backup files and database just in case.
As for converting the tables your best doing that either through mysql cli, or phpmyadmin.

I would treat these as two separate jobs: First, migrate to Pressflow and confirm the site is working; then, secondly, start moving tables.


I finally solved this problem somehow.. I think this is an EntityAPI's issue. So, here is my (temporary) solution:

removed those changed fields directly from hook_schema, added new fields directly to it.
removed those fields with db_drop_field function and added new fields with db_add_field function with hook_update_n function. By this way I managed to have the same structure in my (changed) entity and db table schema.
flushed the caches

Error has gone, so far everything is working fine. But I'm not sure this solution will not cause any problems in future... I still can't understand why entity api doesn't see changed fields in hook_update_n function...


Dynamically change widget type in node edit form

The use case you describe is specific in nature, but the question you actually asked in the title is more general purpose. I’m answering the question in the title.

To the best of my knowledge, there is not at present an Input Widget Switcher module for Drupal 7 or earlier, but there really needs to be. There are similar modules such as Display Suite for altering the displayed output of a node, including using different display formatters (example: showing the same date field as a short date format in a Teaser and as a long date format in a full node display), but nothing analogous for node input form widgets.

Drupal 8 has the underlying structure needed to implement something like this, known as Form Modes (basically the input form equivalent of View Modes such as Full vs. Teaser, which Display Suite builds on). But while there is a UI for creating them, there is not at present to the best of my knowledge an ability to use them or switch between Form Modes in core.

That said, the Form Mode Control module for D8 does seem to provide this ability. It allows switching between Form Modes based on Role or Permission and on Node (or Entity) Creation vs. Modification (for instance, on Creation the Widget for a GeoField might be Lat/Long with HTML5 GPS Geolocation enabled, but on Modification switch to a different Form Mode that uses, say, OpenLayers Map Widget so that the already-existing location marker can be moved on a map).

There’s also the similar Form Mode Manager module (also D8 only) that works a bit differently, but it’s only in Alpha at the time of this writing, while Form Mode Control is in Release Candidate 2 and thus better for production sites.


Contextual filter and exposed filter related

Probably I misunderstood your problem, but I put my solution anyway.

OK I have a view with entities of content type Foo and exposed filters as block, which appears on all pages.
I am storing filter values in user entity (same fields as in Foo - taxonomy term reference fields).

When URL has not exposed filters parameters (exposed filters form hasn't submitted) I try to set filters default values from user entity fields:

    /**
     * Implements hook_form_FORM_ID_alter
     */
    function mymod_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
     if (! _mymod_isFormSubmit()) {
     //exposed filters form hasn't submitted so I am using values from user entity
     global $user;
     $wrapper = entity_metadata_wrapper('user', $user);
     foreach(_mymod_getFiltersMapping() as $filterName => $fieldName ) {
      $tids = array();
      foreach($wrapper->{$fieldName}->value() as $term) {
        $tids[] = $term->tid;
     }
     $form_state['input'][$filterName] = empty($tids) ? 'All' : reset($tids);
    }
  }
}

It isn't working for me yet, I am getting always random values, maybe because usage of Better Exposed Filters form.


How to change default value of taxonomy term in View exposed filter drupal 7?

To display Results Only when Criteria is selected :

In your view, change Advanced Settings -> Exposed form style to Input required

In Exposed Form style settings you could define the text to be displayed on no results

OR

To Alter Exposed form options:

You need to implement hook_form_alter()
Here is a sample code of it:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    case 'views_exposed_form_id':
    $name = 'Vocabulary_name';
    $myvoc = taxonomy_vocabulary_machine_name_load($name);
  $tree = taxonomy_get_tree($myvoc->vid);
    foreach ($tree as $term) {
     $tax[$term->tid] = $term->name;
    }
    $form['field_taxonomy']['#options'] = $tax;
}


WYSIWYG Image Upload in Basic Page (CKEditor and CKFinder)

If it looks like you can upload nodes to your basic page, but they're not displaying then you're probably using filtered HTML as your page filter. If you don't have the ability to add pictures at all, then look at the configuration of CKEditor and you may need to add the appropriate button for the content type.


Option for auto Masspay in ubercart marketplace

Automatic mass payment (with paypal only)

Explanation:
When a user makes an order and pays with PayPal or does ExpressCheckout with PayPal and the system redirects him to "checkout/complete" the added code starts to work and makes masspay for all the orders done before that one. (Newest order not included)

Another Method :

Go to Test Accounts, select "Create Account: Preconfigured", Choose
account type "Seller", use given data
Go to API Credentials, copy API Username, Password, and Signature to
Drupal Enable uc_paypal module
Setup PayPal Website Payment Pro settings at: "Store Administration

    Configuration >> Payment Settings >> Edit >> Payment Gateways" or directly via /admin/store/settings/payment/edit/gateways

Enable this payment gateway for use API server: Sandbox
Now enter your API credentials
If IPN is setup you may now make payments at "Store administration >>
reports >> Seller reports"


Changing column names for CSV export in Webform results download page

If you want to change the column title of an exported element, the simplest solution is to specify an 'Admin title' via the element edit form's 'Advanced' tab under the 'Administration' detail widget.


Class Term missing sometimes when used in myTheme.theme

The error is caused from the fact you didn't fully qualified the class name, which means you forgot the namespace of that class.

Or you use \Drupal\taxonomy\Entity\Term::load($tid); or you add a use \Drupal\taxonomy\Entity\Term; line at the top of the file. In this way, PHP knows where to find the class you reference.


Auto-incrementing by a value other than one is not an easy task. Drupal's Schema API allows you to supply the mysql_suffix property to supply mysql specific properties as explained in this comment.

The problem is that there is no mysql TABLE CREATE option which allows you to change the auto increment amount. There is a MySQL variable auto_increment_increment but it can only be set globally.

In this similar question a solution has been posted using MySQL triggers. AFAIK this is the  best SQL solution that exists.

The best solution would probably to find a way to not need to auto_increment with a value other than one or use an INTEGER type and do the incrementation manually through PHP.


I did by using entity form + field collection.


To alter a node edit from, you need to create a custom module that implements hook_form_alter(), using code similar to the following one:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) {
    $node = $form['#node'];
    // ...
    // @todo Add the code you need.
    // ...
  }
}

For examples of actual implementations of hook_form_alter() that alter the node edit form, see book_form_alter(), locale_form_alter() (which alters also other forms), menu_form_alter(), path_form_alter(), and taxonomy_form_alter().


How to get XML/JSON data for api.drupal.org?

I was curious about this, too. Below is a dump of the API in JSON format. Unfortunately I don't think the same is available in XML format, or that the query can be further refined to, say, retrieve only a list of hooks.

URL structure:

api/(project)/full_list/(branch)?limit=M&page=N

https://api.drupal.org/api/drupal/full_list/7?limit=20&page=0

Source: Issue# 2369135: Public API into api.drupal.org?


Main menu links not operational on front page when anonymous

The most often reason when you can`t see any kind of links in menu - are permissions for users. So please double check whether all of ones connected to your links (maybe modules/content types or whatever) are enabled for anonymous user.


I found a solution using the following code.

global $base_url;
$path = 'sites/xxx/';
drupal_add_js($base_url . '/' . $path . 'script.js', 'external');


How do I check the image's view mode in the image.html.twig template?

If you're using a Media entity, you can check the view mode in the media template: media.html.twig:
From the media.html.twig file documentation:

view_mode: View mode; for example, "teaser" or "full".

This would let you add the class to the image parent <div>.
If you want to target only images, you can do this:
media--image.html.twig
And if you want to target only images with the view mode abc, you can do this:
media--image--abc.html.twig


I doubt this is possible in views but you could try a combination of menu block and display suite modules, if you can't custom-code it.

You might also need a module which creates fly-out menus. Display suite is capable of pulling in various entities into your display, and there is a great set of tutorials available on Youtube that will show you how to achieve this.

This site is built with Drupal commerce, display suite and menu blocks; although I didn't add nodes to my menu blocks, it is possible.


Zerolab is right! If disclamer module is not good for you, also try Splash (Splashify on D7)


Address field validation-- how to allow only English/single-byte characters?

You could compare the length of the string by using strlen which doesn't account for double-byte characters and then using drupal_strlen which does account for double-byte characters. If those functions think the length is different then there are some double-byte characters in there.

That comparison would need to go in a custom form_validate function.


Template hooks like template_preprocess_user() are implemented by custom module/theme by replacing template with [MODULE_NAME/THEME_NAME]. So, for example, if your theme short name is bartik, then the function name will be bartik_preprocess_user() which will be implemented in the bartik.theme file.

function [MODULE/THEME_NAME]_preprocess_user(&$variables) {
  $variables['foo'] = 'foo';
}


Drupal Lightbox2 fails W3C validation because of rel="lightbox[field_image][]" attribute

You can copy the lightbox2-insert-image.tpl.php file into your own theme and change it there - but this will break the functionality of the module as javascript uses rel attribute multiple times.

You could refactor the javascript, change all occurrences where it accesses rel and change it to data-rel and create patch and submit it to drupal.org to the author of the issue as a request (or just submit issue now requesting this and wait if/until the maintainer does it).

On a personal note - why do you need it to pass W3C validation? Is it a project MUST requirement? If not, I would not waste any time on this as valid HTML is not that important any more, not even for SEO and indexing.

Edit: http://google.com is not passing W3C validation, I think that sends a message. (http://validator.w3.org/check?uri=google.com&charset=%28detect+automatically%29&doctype=Inline&group=0)


How to change password via REST when validating email address (first login link)

I'm not sure there is a pure Drupal core way of doing this, but there are contrib modules which can help. These modules involve resetting the password when it has been forgotten but may help with understanding the process.

Password reset REST allows resetting the password via REST.

  Small module to help with resetting password through rest.

  This attempts to provide the same logic present with a
  pass-reset-token as you'd do with the normal interface.

REST Password Request provides an alternative method which involves generating a temporary password so the user can change their password via rest, and then log in as normal.

REST Register User with Email Verification supports email validation, but may not be exactly what you're after.

It is also worth reviewing this issue regarding anonymous REST and user entities: A REST resource's "auth" configuration MUST be non-empty, which prevents configuring it for anon access only


Creating a system account used by a module: Is setting the password with drupal_random_bytes() too excessive, or is there a better method?

As you probably know, another option is to use user_password() to get the password string.

When Drupal hashes it, e.g during user_save(), with user_hash_password(), drupal_random_bytes() is used as part of the _password_generate_salt() calculation.

Just thought it worth mentioning.

You may also be interested in preventing login through the UI by that account with a user_login validation handler.


How to use Devel module to see what creates an URL?

Not really sure what you are meaning by 'create url', but any url in Drupal is registered through hook_menu(). Don't let the name confuse you - this is a seperate concept to lists of urls (like the navigation menu). The menu system keeps a cache of url to callback function mappings, which you can inspect to see which function each url points to.

To view the menu cache, you can run this code:

dpm(menu_router_build());

You can then look through the array to see the details for each url.


How do you order meta tags added by drupal_add_html_head()?

Use the #weight property. As drupal_get_html_head() uses drupal_render() to render the meta tags, #weight is used when rendering them.

I uses the following code to make a test on my local site; it is the same code you are using, except it doesn't have any reference to the node object.

  $og_title = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => "This is the title",
    ),
  );
  drupal_add_html_head($og_title, 'zujava_og_title');

 $og_url = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:url',
      'content' => url('node/1', array('absolute' => TRUE)),
    ),
  );
  drupal_add_html_head($og_url, 'zujava_og_url');

  dsm(drupal_get_html_head());

The output I got is the following one.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta property="og:url" content="http://tero.local/dr72/node/1" />
<meta name="Generator" content="Drupal 7 (http://drupal.org)" />
<meta property="og:title" content="This is the title" />

As you see, the last added tag is the first to appear.

I then run the following code.

  $og_title = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => "This is the title",
    ),
    '#weight' => 10,
  );
  drupal_add_html_head($og_title, 'zujava_og_title');

 $og_url = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:url',
      'content' => url('node/1', array('absolute' => TRUE)),
    ),
    '#weight' => 200,
  );
  drupal_add_html_head($og_url, 'zujava_og_url');

  dsm(drupal_get_html_head());

The output I got is the following one.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Generator" content="Drupal 7 (http://drupal.org)" />
<meta property="og:title" content="This is the title" />
<meta property="og:url" content="http://tero.local/dr72/node/1" />

As you see, the order of the meta tags has been changed; the meta tags added from the code appear after the default meta tags added from Drupal.

_drupal_default_html_head() (the function that returns the default meta tags) uses #weight for the "Content-Type" meta tag.

  $elements['system_meta_content_type'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'http-equiv' => 'Content-Type',
      'content' => 'text/html; charset=utf-8',
    ),
    // Security: This always has to be output first.
    '#weight' => -1000,
  );


you can try rules module to achieve this.
Create a event like "when a node is saved" and provide some condition if required and then action like grant/deduct user points. User points is integrated with rule.


Comparing node creation and modification dates in twig

You can't compare render arrays. To compare fields better use raw values stored in the node:

{% if node.getCreatedTime > node.getChangedTime %}
    ...
{% endif %}

(The comparison doesn't make much sense, probably you want to swap both dates)

The node object is available in node and page templates. In other templates you might find it in a deeper level. If not and the node is displayed as main content you can add it in preprocess:

  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
  }


How to reply to a comment through services in Drupal 7?

This is how I was able to reply to a comment through web-service.

 URL:- example.com/rest/comment
 Method : POST
 Parameters:-
 nid :6
 pid: 4
 comment_body[und][0][value]: Some text


You can do that with Views. Create view for nodes, add a filter for these two vocabularies and expose them, so that they can be selected by the user.


Avoid random number cached in preprocess hook

First, try to pass a render element with a '#cache' value set, maybe like so:

$variables['imageSet'] = [
  '#type' => 'value',
  '#value' => $imageset,
  '#cache' => [
    'max-age' => 0,
  ],
];

Next, you could try to completely disable the cache for this node (though that's probably not the best idea).

$variables['#cache']['max-age'] = 0;

And last – but quite advanced – you can provide a custom controller, that returns an uncached JSON response with your calculations and then use a little JS script that fetches the JSON via Ajax and inserts it into some placeholder selector in your markup (for the placeholder you could even provide a pseudo field to be placed at a desired position via the admin UI).

I used exactly the concept described above to build User Online Status. You can simply grab a copy and check its code to get an idea how that works.


some css of same file getting processed some not

It was a syntax error after all...forget one curly bracket somewhere in my stylesheet.
I never expected a syntax error in css to cause this kind of difficulties. I.o.w. I unconsciously assumed it couldn't be syntax and therefore it never crossed my mind. Lesson learned: never assume even when you don't realise you're assuming!


Core forum hook_menu_local_tasks_alter() override

You're right in not wanting to mess with core; it makes things tricky when you're trying to update to a new version of Drupal. You have to maintain patch files which may break with new core code and it just gets messy.

Fortunately Drupal does provide a method to handle exactly what you're after.

In Drupal 7 hook implementations are alterable, so you can use hook_module_implements_alter() to stop forum_menu_local_tasks_alter() from ever running:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_local_tasks_alter') {
    unset($implementations['forum']);
  }
}

You'll need to copy the code from forum_menu_local_tasks_alter() and put it in your own mymodule_local_tasks_alter() function, and just replace the call to forum_forum_load() with the call to your mymodule_forum_load() function.


Two step user approval after registration

You don't need any third-party modules. Drupal core has the option to verify the email the user enters, and the option for the administrator user to approve the accounts users create. In Drupal 7, those settings are on /admin/config/people/accounts.

As for name, and date of birth, those are fields you can add to user accounts. In Drupal 7, those settings are on /admin/config/people/accounts/fields.


I was able to accomplish this by creating a new language negotiation provider. It was mostly a matter of just copying the hooks and callbacks with only minor changes and a lot of trial and error. There wasn't much documentation that I could find on it...
The only thing is that the first part of the url MUST be a language, though it can also be a directory.


Views contextual filter if field value is X then show this in views page Y

This sounds like a job for Page Manager (part of C-Tools).
Create variants that activate on content type AND field value.


Why do Drupal.behaviours and document.ready behave differently?

Drupal.behaviours are similar to document.ready but Drupal make sures that on every ajax call code written in a Drupal.behaviour is executed again. While code written in document.ready is called once on page load.


How to use number fields for drupal commerce attributes

For the answer, I actually found a possible dup of my questions here:

support integer or float values as an attribute

but it was never answered, which is why I left mine up.  However, the question had a little more research into my problem and was able to give me insight that any field that implements hook_options_list and has an entity "property_type" defined in its hook_field_info then it can be used as an attribute.

From here I created a module that installs a new widget for the "list" modules that allows textfield input and adds the sanitized value of the textfield to the "allowed_values" on POST so that it passes validation.  From the viewmode standpoint it works like a normal list and you can use the select widget on the commerce product attribute settings to use this as an attribute.

I know the security ramifications of this could be dicey, however I am sanitizing the field input and I have only myself actually contributing content so I feel this solution works for me.


hook_mail is not sending rendered HTML email

I have done the same what you done above. Using hook_mail_alter function will not work for this case either.

Better is to use Mime Mail module to achieve this HTML Format.

  It permits users to receive HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.


go to admin/config/search/settings and change the length of Minimum word length to index to 2 and re-index the site.


How can one add superscript character like TM or Reg on a block title

Block Class Styles may be useful:

  Extends the Block Class module to incorporate styles (or themes)
  rather than css classes. Adds style-based tpl suggestions. Allows HTML
  in your block titles.

Other options would be to create your block in code, and set the $block->subject to be your <sup> inclusive title, or to override the block-XYZ.tpl.php for the your particular block and add the title in there.

By default, Drupal core runs check_plain on any UI created blocks, so through the UI I don't think there's another option.


You can create view for your needs. Access only to admin role and pin it to "Default Shortcuts" menu.


How to make a required / not required one field depending on value of second field (Drupal in registration form)


How do I set up a shipping condition that accesses the value of a specific field in product?

What you can do is loop through the line items and each line item is passed through a rule component where you can check the line item's weight. If you want to get the shipping fee for line item, you would need to set a rule set component. If you just want the component to provide the weight of the line item, a rule component will do.

I am not sure what you are trying to achieve with the rule or how your flat rate shipping works. Are you looking for the heaviest weight present in the order and apply to the order the shipping fee of that weight? Or does the fee accumulate according to how many line items and their weight? Regardless of how your shipping rate works, it's still the same concept: Loop through the line items. Pass the line item to a rule component that checks the weight of the line item.

The rule will look like this (assuming your shipping condition is: if product is light - add 0.25$ to shipping fee, 0.5$ for medium, and 1$ for heavy.)

Rule:

  /* ACTIONS*/
  // Add a variable: total_shipping_fee; set to 0.
  // Loop through line items
     // For each line item, trigger get_shipping_fee component passing line item and providing the prod_shipping_fee for the product
     //  Calculate value: total_shipping_fee + prod_shipping_fee
  // Set shipping fee to total_shipping_fee

For the rule set component: (get_shipping_fee), create three rules that checks the weight of the product; each rule returning or providing the shipping fee. For instance:

/* SETTINGS */
Parameter: line_item
Provided: shipping_fee

/* CONDITIONS */
// If product is light

/* ACTIONS */
// Set shipping_fee to 0.25$

The provided variable or variable returned by the rule component depends on how your flat rate shipping works. Also, you might need to pass another variable to the rule component.

Also, if you're new to drupal and rules, you can read the documentation to make it easier for you.

Hopefully, this will give you ideas to the actual solution of your problem.


Interesting question and a typical use case. In a custom module, do the following:

use Drupal\views\ViewExecutable;

function helper_views_pre_render(ViewExecutable $view){
  if ($view->id() == "numbers" && $view->current_display == 'page_1') {
    $total = 0;
    foreach ($view->result as $value) {
      $number = $value->_entity->get('field_number')->value;
      $total += $number;
    }
    $view->attachment_after = [
      '#markup' => '

Total:	'.$total.'

',
      '#allowed_tags' => ['table','tr','td']
    ];
  }
}

Change the names according to your view name & field names. I'm sure you get the point: you add a table below with the total result.

I did a test and it gave me the following result:


Swap prices in Ubercart based on Attribute price

Looks like the Ubercart Ajax Attribute Calculations module will do the trick, at least somewhat... it will change out my product's "$0" base price for the attribute price, but it still does not technically "swap" the prices.


How to load webform results using EntityFieldQuery

Webform results aren't entities, so you can't use an EntityFieldQuery.

You'll need standard db queries to get that data.


system_cron() eats all ram and runs forever

Try Elysia Cron, it provides a lot of fine tuning and control over standard cron.

Khalid Bahey from 2bits.com wrote an extensive article regarding this module: Improving the performance of Drupal's cron by using the Elysia cron module


How do I get the vocabulary of a term inside an "article" type content type?

Adding the answer now. My final code in the field--entity-reference.html.twig file:

{% for item in items %}
  {% set mylabel %}
    {{ item.content }}
  {% endset %}
  {% set myclass %}
    {{ item.content['#options'].entity.vid.0.value['target_id'] }}
  {% endset %}
  {% set myclass = myclass|replace({'_':'-'}) %}

      {{ mylabel|striptags }}

{% endfor %}

HERE is the code needed in a node to access the parent vocabulary of the taxonomy terms in the node. (That is, individual tags on a content type node).

item.content['#options'].entity.vid.0.value['target_id']

NOTE: This is on Drupal 8.5.3 and none of my "tags" have more than one parent.


Modify widget in Entity Reference field select box?

Entityrefence 7.x-1.x-dev allows you to use results from a View in the select box, which will allow you to do what you need.

create/edit a view, add a new display of type "Entity Reference" to it, setting properly the fields you want to be shown;
edit the entityreference field, find "entity selection mode", set it to "views: filter by an entity reference view" then select the proper "view used to select the entities" option created on previous step.


Passing taxonomy term through drupal_html_class() and use it as row class name

I got it working by using this preprocess function:

function mytheme_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'field_category') {
      $tid = $variables['row']->_entity->field_category->target_id;
      $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
      $name = $term->getName();
      $variables['output'] = \Drupal\Component\Utility\Html::cleanCssIdentifier($name);
    }
  }
}

An alternative would be using mytheme_views_pre_render.


You have the possibility to edit the current password locally.

You should take a look at Resetting the administrator password with sql-query. It is possible with some commands and SQL queries to change the current password for your admin user (UID=1).


Can I simplify first code to variant without additional function?

Not natively, as you've rightly said EFQ doesn't have a random order method. At a guess that's because field storage is pluggable, and it would be tricky to come up with a cross-compatible method that makes sense for e.g. MySQL and MongoDB. Might be wrong though, it may simply not have been considered important enough to implement/overlooked/etc.

If the extra step is unacceptable, the other option would be to subclass EntityFieldQuery to add your own random order method, and override the execute callback with your own version of field_sql_storage_field_storage_query() to get it into the final query.

The method you already have is arguably a bit cleaner than that; certainly it's less effort.


Change workflow default state with hook_form_alter()

It seems your implementation of hook_form_alter() runs before the one provided by the Workflow module. Implement hook_module_implements_alter() to change the order in which implementations of hook_form_alter() are executed. Alternatively, give your module a higher weight than the Workflow has.

Beware that this approach does not work for changing the order of implementations of hook_form_FORM_ID_alter() specifically. Implementations of hook_form_FORM_ID_alter() are always executed in the same order as those of hook_form_alter(). This is due to the way how drupal_prepare_form() calls drupal_alter().


Can Rules be used to disable the logo variable on some pages?

I don't think that I'm on the wrong way (correct me if) but I think you should do a hook_preprocess_page(&$vars) in your theme's template.php and unset the $var['logo'] when you meet your condition.

I wouldn't do that with Rules, I don't even know if it's possible.


welcome.

The only tweak needed I see is:

$sql = "SELECT field1, field2 FROM {tablename} WHERE field3 = :var1 AND field4 = :var2";
$result = db_query($sql, array(':var1' => $var1, ':var2' => $var2));

The method you've written your query allows for SQL-Injection -- using placeholders in the SQL helps to defend against this.

I invite you to read up on the Database API documentation, specifically queries:

Result Sets
Dynamic Queries
Static Queries


Take a look at the default node.tpl.php. You'll notice that they render the content with render($content).

I've never used Contemplate, but if you install the devel module you can then use the dpm() function to take a look at the variables in detail. Try dpm($content), and you see all the content that you can render, or even use the hide function to remove content. For example, you can use hide($content['links]) prior to render($content) and the links will not be rendered; you can display comments with render($content['comments']);. Don't forget to print the value returned by render(), as render() returns the HTML markup used to render the element passed as argument to the function.

You can easily render the image field with render($content['your_image_field']).
If you are using the Countries module, then you can control what it is displayed in the content types display on admin/structure/types/manage/your-content-type/display, and simply render it like you do with the rest of your content.


Give a specific user role the ability to edit, delete users other specific role

Sounds like a combination of the following:

http://drupal.org/project/role_delegation - Adds a permission to assign roles per role
http://drupal.org/project/administerusersbyrole - Allows controlling, based on roles, which users can admin which other users.


Your code seems to be OK. I use some similar code in one of my projects (this a csv importer, similar concept):

function custom_function($importer_id, $csvfile_path) {
  // Load the Feeds Source object.
  $source = feeds_source($importer_id);
  // Load the source fetcher config.
  $fetcher_config = $source->getConfigFor($source->importer->fetcher);
  $fetcher_config['source'] = $csvfile_path;
  $source->setConfigFor($source->importer->fetcher, $fetcher_config);
  $source->save();
  $source->startImport();
}

Make sure that you are using the foreground configuration, this way the batch process could be be executed "inside" drupal with showing the progress bar. Or you can force it:

// Tweak the importer configuration, to enable "Process in the background".
$config = array(
  'process_in_background' => TRUE,
);
$source->importer->addConfig($config);

// Execute the import.

Another approach could be to schedule it

// Schedule the import, and make sure importer is scheduled, too.
$source->schedule();
$source->importer->schedule();

This is a good article about feeds importer


Building a view with arguments from a search select list

In the block display, add a contextual filter for your taxonomy term field. Set it to Provide a default value when the filter value is not in the URL. Use Taxonomy term ID from URL as type for this default value and select Load default filter from term page.


altering a block that is embedded in a view

I assume you're displaying a block_content entity.

That is not actually rendered through the block system, it's an entity, so you need to implement hook_block_content_view() (see hook_ENTITY_TYPE_view() for documentation)


Ajax error when trying to add another paragraph

I had the same issue.
It turned out every time a paragraph is added the validation method runs.
In your case, echo is illegal and it stops the following process. Try replacing it with php error_log or Devel debug functions.


Yup! Simply edit your "Navigation" menu (at /admin/structure/menu/manage/navigation) and reorder the menu entries under "Add content". Now when you go to /node/add they'll appear in whatever order you set them in your "Navigation" menu. Example screenshot below. On /node/add they will appear as Basic Page, then Article.


Handling circular entity references with Migrate

The main problem has to do with how stubs are handled in Migrate, and is related to a known issue.

In short, when the destination can be one of several content types, the migration doesn't know what content type to create the stub as in a generic way.

My current workaround for this is to prevent stubs from being created:

abstract class MyNodeMigration extends DrupalNode6Migration {
  ...

  protected function createStub(Migration $migration, array $source_id) {
    return FALSE;
  }
}

When the migration runs, stubs don't get created, but the entity reference fields in my destinations also don't get populated.

I then manually reset the highwater mark

db_update('migrate_status')
  ->fields(array('highwater' => 0))
  ->condition(...)
  ->execute();

and then rerun the migrations.  Since the destination nodes exists, the entity reference fields can be populated properly.


Should I pass the $form parameter when building system_settings_form?

The form parameter is passed from drupal_get_form(), but if you choose to start a new form array it doesn't really matter. The form works as expected.

However, it's good practice I think to include $form and $form_state in the parameter list because if you ever change your menu entry to pass an argument, then all you need to do in your form builder callback is to add it to the list at the end.


Why aren't CSS files served? There is nothing in sites/default/files/css

A few more things to check when you have issues like this:

Any noteworthy issues on the Status page? (admin/reports/status)
Does saving the File system page generate any errors? (admin/config/media/file-system)
This sometimes indicates permission or ownership issues in the file structure, which could keep the aggregate CSS and JS files from being generated?
Have you checked the error log for any noteworthy messages? (admin/reports/dblog)

Clearing the cache is a good place to start, but I see that you already did that. Try checking the error log immediately after clearing the cache to see if anything pops up.


have put in the api key, I think you are missing that. Have you also enabled it on certain node types you want to display.