Listing child terms based on relationship with parent

First you have to create the Taxonomy hierarchy within Views, so later only the children terms will be in Views rows results (so they can be chosen from a ER field on the node creation form). You can't do that starting from User Views because only Parent Relationships are available, no way to drill down, only up is possible.

Create Taxonomy term Views of your particular Vocabulary. They will list both Parents and Children. It will already have the Taxonomy Name field, keep it.

To create the hierarchy add the Relationship Parent first (It's called "Taxonomy term", search for "parent" to find it quickly in the Relationships list. Require it because we only want to display terms that have a parent, we only want children terms to show on our list

Then add another Relationship, introducing the User, it will be named something like User using field_country, make it use the Parent Relationship (so we get users who are tagged with top-level terms). Require the Relationship because we only need terms that do have users tagged with them.

Now add the Contextual filter User ID. It will automatically use the Country Relationship, and configure it:
When the filter value is NOT available
Provide default value
User ID from logged in user
When the filter value IS available or a default is provided
Specify validation criteria
User ID
Single ID
Hide view or what ever makes sense in your case
To easily test whether the correct sub-terms appear enter some user ID into the Views Preview field. It will provide the context directly to Views so you can see which sub-terms are shown and whether they match that user Country.

Add the Entity Reference Display to your Views and adjust its Settings, (Search fields: Name). Save the Views so you can use it in the next step.

Create/Edit Taxonomy Reference Field on your CT, select the Views as the Reference Type and then select the Views you've created in the first step.

Adjust the "Manage form display" for the new field so it appears as you like it on the node create page.

Now when you go to create a new node of that type the field will list all the sub-terms of the Country the author is tagged with.
You still have to test by logging in as some user to test that the context is passing through correctly (Switch user block can speed it up).


How to handle private file uploads and downloads?

If the whole node should only be visible to the author, then you should either implement hook_node_access() yourself and correctly deny view access or use a content access module (e.g. Content access) to do that for you. Note that hook_node_access() won't prevent that now to show up in listings, for that you need a content access module (or implement one on your own).

Alternatively, if you just want to hide the field, you could use the Field permission module and configure it accordingly.

Both ways should be able to to this because it is something that Drupal can check, it can't know that you prevent access in hook_node_view().


How do I fix File Upload After Upgrading to PHP 7

upload_tmp_dir existed in two places. I was only updating in one location. Answer came from https://stackoverflow.com/questions/15733183/unable-to-set-upload-tmp-dir-on-iis


Render a full entire html page from custom module

Your callback in hook_menu() will by default call drupal_deliver_html_page() which in turn calls drupal_render_page() where the page.tpl.php comes from.

It is possible to implement your own "delivery callback" method, which will be called by drupal_deliver_page() this is how the ajax is delivered in D7


Using setAttributes() returns a fatal error

The error is simply caused from the fact you are trying to access a member function for something that is an object; in fact, theme_image_style() is returning a string, not an object. This is true also for Drupal 8.

  Returns HTML for an image using a specific image style.

To set attributes, just use the following code.

$imgpath = file_load(($node->field_image[LANGUAGE_NONE][0]['fid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail', 'attributes' => array('class' => array('AnyClass'))));

$link = l($image, "node/$node->nid", array('html' => TRUE));
print $link;

It works because theme_image_style(), as theme_image(), accepts a list of attributes to add to the image tag.


hook to redirect user before they create node?

If I am understanding this correctly, this might be a job for hook_init(), eg something along these lines:

function YOURMODULE_init() {
  global $user;

  if ($user->uid) {

    $fails = /* whatever */ ;

    if ($_GET['q']!='node/add/foo') {

      if ($fails) {
        drupal_set_message('How about creating foo first...');
        drupal_goto('node/add/foo');
      }

    }

  }

}


Why are there several branches at the official documentation (e.g. 8.0.x, 8.1.x)?

Drupal 8 made the switch to semantic versioning, and a shorter release cycle between minor versions.

Per release policy, there can be differences between minor versions.  In general, new minor versions are backwards compatible (or provide a BC layer), but can also introduce new features.  In addition, as minor versions get released, some functionality remains but becomes deprecated.

This is why there is different documentation for different minor versions; the document actually is slightly different.

To keep on top of changes in Drupal 8, monitor the list of Change Records or the Twitter account that announces each new one.


Control number of autocomplete results in drupal?

You will have to make a custom module to alter the result of autocomplete coming from node reference module. This example(taken from here) is for 20 result, you can increase/decrease according to your need.

function MYMODULE_menu_alter(&$menu) {
  if (isset($menu['nodereference/autocomplete'])) {
    $menu['nodereference/autocomplete']['page callback'] = 'MYMODULE_nodereference_autocomplete';
  }
}
function MYMODULE_nodereference_autocomplete($field_name, $string = '') {
  $fields = content_fields();
  $field = $fields[$field_name];
  $match = isset($field['widget']['autocomplete_match']) ? $field['widget']['autocomplete_match'] : 'contains';
  $matches = array();
  $references = _nodereference_potential_references($field, $string, $match, array(), 20);
  foreach ($references as $id => $row) {
    // Add a class wrapper for a few required CSS overrides.
    $matches[$row['title'] ." [nid:$id]"] = '
'. $row['rendered'] . '
';
  }
  drupal_json($matches);
}


How to print a block in node.tpl.php only for admin?

You can do something like this:

global $user;
if (in_array('admin', $user->roles)) {  //if not "admin", maybe "administrator"?

}

Or you can use the built-in block access control, under your block's configuration you'll see "Visibility Settings" and in there is a way to restrict by user role.

Edit: what the hell, it's friday and I'm bored.

Take this in small steps before you conclude it's "not working".

Step 1)

global $user;
if (in_array('admin', $user->roles)) {  //if not "admin", maybe "administrator"?
    echo "
admin user!
";
}

If that works, then start making it more complex.  This is the best way to learn how to do new things, especially with PHP since you get to see your stuff immediately!


Body text special characters are escaped

Assuming by my normal HTML becomes you mean the escaped HTML is rendering on the front end, you're probably just resetting the format for the body field with this line
$entity->set('body', $body_encoded);

You can target the value directly instead like this (and you shouldn't need to encode/decode anything):
$entity->body->value = preg_replace('/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/', '<iframe width="560" height="315" src="https://www.youtube.com/embed/$1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>', $node_body);

If that isn't working you can try setting the format too:
// Possibly change 'full_html' to whatever's appropriate for your site.
$entity->body->format = 'full_html';


I can't remove an manage_file field image

You can use db query to remove the entry

  $mydir =  variable_get('file_public_path', conf_path() . '/files');
  $filename = $mydir .$file_directory. $filename;
  unlink($filename);
  db_delete('file_managed')
      ->condition('filename', $filename)
      ->execute();
  $FileStatus = "The file has been removed - ".$filename;

Get the public directory path and delete the file from file_managed table

This will make your work easy.


How to send a custom Solr Query using Search API Solr

From version RC4 you can use makeServletRequest() to generate custom solr queries. See some examples on GitHub.

Here are some code examples:

  // Ping example
  // class_exists('Apache_Solr_Service') ?: spl_autoload_register('_search_api_solr_autoload'); // make sure that SolrPhpClient class is loaded (use only for <=rc3)
  $server = search_api_server_load('my_solr_server'); // CHANGE THIS
  $solr = new SearchApiSolrService($server);
  $result = $solr->ping();
  drupal_set_message(print_r($result, TRUE));

  // Simple search query (not fully tested)
  // class_exists('Apache_Solr_Service') ?: spl_autoload_register('_search_api_solr_autoload'); // make sure that SolrPhpClient class is loaded (use only for <=rc3)
  $server = search_api_server_load('my_solr_server'); // CHANGE THIS
  $index = search_api_index_load('my_index'); // CHANGE THIS
  $query = new SearchApiQuery($index);
  $query->keys('foo');
  $query->fields(array('title'));
  $solr = new SearchApiSolrService($server);
  $result = $solr->search($query);
  drupal_set_message(print_r($result, TRUE));

  // Custom path example for rc4 and above (not fully tested)
  $server = search_api_server_load('my_solr_server');
  $uri = SearchApiSolrConnection::LUKE_SERVLET . "?show=schema"; // or any other custom URL
  $connection = $server->getSolrConnection(); // or: new SearchApiSolrService($server)
  $response = $connection->makeServletRequest($uri);
  drupal_set_message(print_r($response, TRUE));

  // Example for assembling the right URL
  $server = search_api_server_load('my_solr_server');
  $url = 'http://' . $server->options['host'] . ':' . $server->options['port'] . $server->options['path'];

Above code tested in hook_init with Drupal 7 and Search API Solr [rc3].

Acquia

If you're using Acquia, you can use Acquia-Search-Proxy which allows you to send custom queries against Acquia Search (Apachesolr + Search API Solr). See also my fork of Acquia-Search-Proxy which include some extra improvements.

Example custom queries via CLI:

PATH_INFO="/admin/ping" php search-proxy.php
PATH_INFO="/admin/luke" QUERY_STRING="show=schema" php search-proxy.php
PATH_INFO="/select" QUERY_STRING="q=foo" php search-proxy.php
PATH_INFO="/admin/file" QUERY_STRING="contentType=text/xml;charset=utf-8&file=schema.xml" php search-proxy.php


It sounds like you're reinventing the wheel here; as @burnsjeremy mentions, there's already an effective system built into Drupal for storing permissions.

hook_permission() allows any module to define its own custom permissions that can be set per-role. Once implemented, user_access() can be called to check a user for custom permissions.

If you need some data that is more granular (i.e. at the per-user level), the global $user object has an array property called data. $user->data is loaded/saved with the user object and should always be available to you.


Why does my background image only sometimes show?

To fix it, if you want, you can check all your blocks and views and template files to see if you can find the HTML (as you can see it when you view source)

    <style type="text/css" media="all">
    .not-front #region-header-first .field-name-field-headline,.not-front #region-header-first .field-name-field-subhead{color:#ffffff !important;}
    </style>

code and remove it, OR don't worry about it and just add

.not-front #region-header-first .field-name-field-headline,.not-front #region-header-first .field-name-field-subhead{color:#ffffff !important;}

to your theme's .css file


Create a new Menu in Drupal 8 programmatically

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

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

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

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

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

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

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

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


Migrating revisions from external data source

Yeah, this part is not documented at all, I had now also problems with it, so here is how I solved it:
When you want to migrate a content that has revisions, you need to migrate the first version with the entity:node plugin, then you migrate the next versions with the entity_revision:node. You don't do anything else, just change the destination plugin and when you migrate the revisions, you set the nid value to the first version of the node. So you keep the body and the file and other fields, you just add the nid field, so the revision plugin will know where to put the content. That's it at least from the yml part.
From the source, you have two one for the node plugin where you list only the first version of your content that you want to migrate and one for the revisions where you list everything EXCEPT the first version also, you have a new column which contains the first version's ID for every revision's it's own.

If you migrate the current publish one into the node table, and you migrate the rest into the revision, the IDs, the order of the revision and some other things will be messed up. At least my case was that.

By code (not 100% complette, just main parts):

migrate_plus.migration.node.yml:

id: my_node
source:
  plugin: my_node
process:
  title: title
  body: body
  langcode:
    plugin: default_value
    default_value: "und"
  status:
    plugin: default_value
    default_value: 1
  #other fields except nid.
destination:
  plugin: entity:node

Query for the source plugin (id = my_node):
SELECT id, title, body FROM content WHERE version = 1
in getIds() the id is the only id.

migrate_plus.migration.node_revision.yml:

id: my_node_revision
source:
  plugin: my_node_revision
process:
  nid:
    plugin: migration_lookup
    migration:
     - my_node
     - my_node_revision
    source: first_version
  title: title
  body: body
  langcode:
    plugin: default_value
    default_value: "und"
  status:
    plugin: default_value
    default_value: 1
  #other fields.
destination:
  plugin: entity_revision:node

Query for the source plugin (id = my_node_revision):

SELECT first_ver.id AS first_version, c.id, c.title, c.body FROM content c
  INNER JOIN (
    SELECT * FROM content c
    WHERE version = 1
  ) first_ver ON c.resourceId = first_ver.resourceId AND c.articleId = first_ver.articleId
WHERE c.version <> 1

in getIds() the id is the only id.

The above example will give new id's for the content.


How do I show related nodes as attachment in the term view block?

To insert one view into another (and pass arguments) as a field use Views Field View module.

You'll have to use Has Taxonomy term ID Contextual filter in your Content Study Views, as No Sssweat suggested in comments, but you only need to choose the option to load it from the term page (not node page). And you don't need the additional ID Contextual filter for any exclusion (because you're not displaying it on node pages).

Then include that Content View as a Field on your Term View, it will automatically filter out correct Studied on each Term row.


I guess the simplest solution would be a normal textfield with a youtube-specific formatter. A formatter is some code that takes the value of a certain field and uses it to generate a chunk of html, displaying the field on your page the way you want. The downside of this solution is that it will add a separate field to your form.

A quick search found two sandboxes with youtube field formatters:

https://drupal.org/sandbox/Hydra/1404188
https://drupal.org/sandbox/double/1795842

Unfortunately I could't find an oficially released, stable module.

If you want complete control over your formatter, here's a tutorial how to create your own: Creating Custom Formatters with the Field API . In the comments, some commenters even say it helped them create a youtube field formatter.

[Update]

I just noticed the Googtube module, it seems to be exactly what you're looking for: like Video Filter module, but parsing regular YouTube URL's as embedded video's.


How to list nodes and have them grouped by Day / Week / Month?

What you need to do is create a custom PHP field and manually code out the group by conditions as you have set there. I had the same issue I documented on my blog here: http://drupul.com/content/views-multiple-group-recipe-drupal-7

This is the code I used in my PHP field:

<?php
global $prev_month;
global $month;

if($prev_month != date('F Y', strtotime($data->field_field_date_2[0]['raw']['value'])))
{
  $month = '
'. date('F Y', strtotime($data->field_field_date_2[0]['raw']['value'])) .'
';
  $prev_month = date('F Y', strtotime($data->field_field_date_2[0]['raw']['value']));
}
else
{ $month = ''; }

print($month .'
'. date('M d', strtotime($data->field_field_date_2[0]['raw']['value'])) .'
');
?>

You will of course have to modify it to your setup, but its very similar to the setup you need as I needed it to be grouped by month then week and then day.


The only thing you are doing with your code is replacing the button that you are clicking. It's probably getting replaced, but visually will look exactly the same as it did before, which is why it appears nothing is happening.


hook_entity_presave showing error in commerce kickstart

Try the code without using the following line.

$total_amount = commerce_currency_format($amount, $currency_code);

The remaining code will be the following,

function custom_module_entity_presave($product, $type) {
  if ($type == 'commerce_product') {
    $cal=commerce_product_calculate_sell_price($product);
    $currency_code=$cal['currency_code'];
    $amount=$cal['amount'];
    $product->field_calculated_price['und'][0]['value']=$amount;
  }
}

If this code not showing error, then the problem will be on your field_calculated_price field type. I think it is a custom field and the problem is the field type is not compatible with commerce_currency_format.

Please make try... Hope this will help you.


Programmatically created field doesn't appear in Views fields

Unless you manually describe the new field to views, it won't know about it. You can do that with hook_view_data_alter():

function MYMODULE_views_data_alter(&$data) {
  $data['commerce_product']['markup'] = array(
    'title' => t('Price markup field'),
    'help' => t('An amazing field which does something great'),
    // Add the rest of the definition here...
  );
}


Hooks go in the .module file, the only hooks that can also work in the .theme file are preprocess and alter hooks.

So if you want the message to be sent when a node is created or updated, use hook_ENTITY_TYPE_presave.

Create a custom module, lets call it "Send Message"

send_message.info.yml

name: 'Send Message'
description: 'Sends the message when a node of Content type Article is created or updated.'
core: 8.x
package: Message
dependencies:
  - message
type: module

send_message.module

<?php

use Drupal\node\NodeInterface;
use Drupal\message\Entity\Message;

/*
 * Implements hook_ENTITY_TYPE_presave()
 */

function send_message_node_presave(NodeInterface $node) {

   if ($node->getType() == 'article') { // checks if content type is article
      $message = Message::create(['template' => 'foo_message_type', 'uid' => $node->getOwnerId()]);
      $message->set('field_node_ref', $node);
      $message->save();
      $notifier = \Drupal::service('message_notify.sender');
      $notifier->send($message);
   }

}


How to Exclude a Specific Node from a Block View

Just add a filter on node id which excludes the node in question


Define a Panels visibility rule programatically

I think probably that is due to the missing 'summary' key from your '$plugin'. A simple access plugin to check if the current page can be defined as :

$plugin = array(
  'title' => t('Front page'),
  'description' => t('Is this the front page.'),
  'callback' => 'ctools_front_ctools_access_check',
  'default' => array('negate' => 0),
  'settings form' => 'ctools_front_ctools_access_settings',
  'summary' => 'ctools_front_ctools_access_summary',
);

/**
 * Settings form for the 'by parent term' access plugin
 */
function ctools_front_ctools_access_settings($form, &$form_state, $conf) {
  // No additional configuration necessary.
  return $form;
}

/**
 * Check for access.
 */
function ctools_front_ctools_access_check($conf, $context) {
  if (drupal_is_front_page()) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

/**
 * Provide a summary description based upon the checked terms.
 */
function ctools_front_ctools_access_summary($conf, $context) {
  return t('The front page');
}

The canonical reference of this could be found in the access plugins defined in the ctools module itself.


Date is wrong in storage but correct on display?

Datetime and Daterange fields are stored in UTC in the database (the storage) and converted to the time zone on output. This is done because the system supports users across the world, so everything is normalized to UTC.

Basically, when you use the UI the field widget takes the input value, and converts it from the user's time zone per system configuration to UTC (see DateTimeWidgetBase::massageFormValues()).  The actual format in storage is the ISO equivalent to the PHP format Y-m-d\TH:i:s.

When output, it takes loads the UTC value, and converts it to the user's time zone per system configuration or uses the forced time zone (the time zone override).  See DateTimeDefaultFormatter::formatDate() for an example, and also DateFormatter::format().

By default, views output field values using the formatters, so the same rules apply.
It sounds like you may have an override in the view settings for the field.


Look at the Fences modules to change the output of a field to a span as you have here. Then use https://drupal.org/project/semanticviews to wrap the span field with semantic markup.   I'm on my phone gluck


How to make user profiles searchable and filterable by multiple fields in the context of a job site

I think you're going to need to use views here.

When you create your view, make sure you use Users and not Content. See screenshot. Once you do this you can set up and expose all the filters you need to allow searching, etc.


How to restrict moderators to only access a limited set of users?

If moderators are creating the Company nodes themselves, you will probably be best off with the Content Access module.

If Company nodes are created by administrators, you could use the Node access user reference field to reference the moderators. They would then get the necessary view permissions.

Let me know if I missed your question.


The Tab Tamer module should do everything you need.

  Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.


Problem with session ID and Drupal cookies when trying to establish a connection

I had the same problem in Drupal 8. The AJAX POST isn't retrieving the cookie from user/login as Drupal does a redirect right away to another page (user usually) which is where you get your 200. And there is nothing (nothing) you can do to interrupt that redirect as its wired into the browser. Postman in Chrome (and I presume Poster in Firefox) don't have those restrictions.

In Drupal 7 the Services module provides a login endpoint. After that you can retrieve the session ID and create the cookie by hand. See https://groups.drupal.org/node/358308

In Drupal 8 that endpoint doesn't exist (and there is debate as to whether it should). What I do is:

In the app I create a regular login form with a return destination to my app
<form action="/user/login?destination=/app">
Once that's done I retrieve a CSRF token as by then the cookie is set. In Drupal 8 you get that at rest/session/token. With Drupal 7 and the Services module you retrieve it at a different path based on your end point.
After that every request goes back with the X-CSRF-Token header and the cookie isn't used anymore.


Oswald is correct. Alternatively, in Drupal 7, you can use drupal_get_query_parameters():

$query_parameters = drupal_get_query_parameters();
if (!empty($query_parameters['l'])) {
  $l = $query_parameters['l']
}


Search form block not showing in IE7 and IE8

Judging from your commments it's a permission issue. To solve it select People -> Permissions from the admin menu (or use the path admin/people/permissions) then look for Search and give 'Use search' (and possibly 'Use advanced search') permissions to the roles you want.


Typo on the module file name:

module.info.yaml

Should be

module.info.yml


Webform Module Email - Module Specific Configuration

You say that you use Swift Mailer for your current setup, but for your test setup with Webform, it seems like you use Webform PHP Mailer.

Try to use Swift Mailer instead and see if that works.


If you are willing to use PHP, I suggest you create your own rule, using hook_action_info().

You have a good example in the Examples module.


Hide or disable field after registration

If you want to do it in custom module

my_module_form_user_profile_form_alter(&$form, &$form_state) {
  // Since it is on registration form, field might be reqruied.
  $form['your_field']['#required'] = FALSE;
  $form['your_field']['#access'] = FALSE;
}


How to rebuild the theme registry on every page?

This isn't included in stock Drupal 7.

If you're not using Zen, the most common way to access this feature is via the module Devel.

Then it's accessible from /admin/config/development/devel, right down the bottom of the page.


If you look at the code for the form submission handler used for the user login form (user_login_submit()), you will notice that it executes the following code.

  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;

  user_login_finalize($form_state);

user_login_finalize() is the function that invokes the hook_user_login() implementations.

  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')
    ->fields(array('login' => $user->login))
    ->condition('uid', $user->uid)
    ->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();

  user_module_invoke('login', $edit, $user);

Effectively, the user is redirected after hook_user_login() is invoked, which means a new page is being served, and Drupal is bootstrapping once again. The content returned from drupal_static() is then reset.

The solution is saving the value in a session variable, for example using functions like ctools_object_cache_get(), and ctools_object_cache_set(), which are already available if you are using the Views module on your site, as it requires the Chaos tool suite, on Drupal 7.


Was fairly easy to fix the issue.

In styling settings of a field in view i used "SPAN" for field.


Show workbench moderation comments on node view page

I would achieve this using Computed field Module.

Install Computed field module
Create a new field of type computed
In the field settings, On the Computed code (PHP)

$entity_field[0]['value'] = $entity->log;
Now in manage display make this computed field visible. That's it.

Note: This is just one way of achieving it.

Instead of installing any modules, You can also write tpl file for the particular content type and display the log message.


Show a block only on the frontpage of the sub-domains

I recommend you to use context module for block displays with the domaincontext module extension.

  Domain Context module is an integration module for the Domain Access module and the Context module.

  The Domain Access module allows administrators to set specific
  settings for each of their domains that are using the same code base.
  The Context module allows you to assign blocks to regions (and more)
  given certain conditions that can be set in the Context admin.
  Currently when both modules are installed you have no interface that
  will allow you to trigger a context on a specific domain. This module
  adds a domain condition to the context administration so that you can
  trigger a context on a specific domain.


#states doesn't work with exposed filters

I tried to use id instead of name and now it works!


Write drupal config in a profile installation

Many configuration elements can be exported and imported using Features module.

  Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

Problem is that it only accepts modules that exports their configurations with Chaos tools style, so you can't export blocks, but can export boxes, and so on. Wysiwyg has currently ctools commented out from it's requirements, so you will need to see if it can be exported or not, at it's current stage of development.

If configuration is kept in system variables, you could consider using Strongarm:

  Strongarm gives site builders a way to override the default variable values that Drupal core and contributed modules ship with. It is not an end user tool, but a developer and site builder tool which provides an API and a limited UI.

As Clive pointed out, there is also Configuration Management module:

  For the most part this module provides the same functionality as a subset of the features module.

The main difference is - it packs only configuration, is smaller and easier to handle, and was written explicitly to deal with "the shortcomings of using features module for configuration management". Still, you are moving whole page, so features with their broader goal might be the way. Your choice.

In all other cases you need to figure out how module stores it's configuration and data, and interact directly with database from your installation profile.


how to notificate users about new created referenced nodes

I think you can accomplish it by creating a custom module. Whenever users create nodes of type B, you can mail and notify those users who created nodes of type A.

You can get the list of users who created nodes of type A with a SQL query like the following.

SELECT DISTINCT uid FROM node WHERE type = 'goals'

In order to send mails when users create nodes of type B, you will have to implement hook_node_insert(), so that you can send notifications after nodes are successfully created. You could also use hook_node_presave(); the only difference is that the latter will send mails before nodes are created.

function MODULE_NAME_node_insert($node) {
  if ($node->type == "B") {
    $params = array();
    $from = variable_get('site_mail', 'admin@example.com');
    $send = TRUE;
    $language = language_default();

    // It is assumed that array od users who created node of type "A" is returned
    // by the following function.
    $users = _list_of_user_created_A_node();
    foreach ($users as $key => $value) {
      $uid = $key;
      $mail = $value;
      $params['node_title'] = $node->title;// The node title of the created node B
      $params['userID_A'] = $uid;
      $params['mail_of_user_A'] = $mail;
      drupal_mail('MODULE_NAME', 'notify_mail', $mail, $language, $params, $from, $send);
    }
  }
}

See hook_mail() on how sending mails.

You could also save the node titles in a database table, and send mails during cron task's execution.


How to stop text-boxes in my custom block trailing past the block?

While creating this form in your custom module you set DIV class to form items which is textfield in your casy. All you will have to do is use #prefix & #sufix
You will start your DIV class from #prefix before #type of form items & close the DIV at #sufix.

Here is the example

$form['first_name'] = array(
  '#prefix' => '
',
  '#title' => t('First Name'),
   '#type' => 'textfield',
  '#suffix' => '
',
  '#maxlength' => 128,
  '#required' => TRUE,
);

Open the CSS file or create your own at your theme folder, but if you create your own then you will have to declare it in theme.info file.

Write CSS for the class demo-form which you have applied to the form element & resize it as your wish. If you have created your own CSS file then don't forget to clear your cache.


The throttle value you're mentioning is specific to cron jobs, not to a single send event. There's no easy way to throttle the number of mails delivered in a single send event.

In general, the main reason someone would want to use cron in this case is when your subscriber base is large enough that a single "Send" action will time out, due to the time taken to send the total number of emails exceeding your server's PHP maximum execution time directive.

Cron is utilised in this case to break up large subscriber bases into chunks your server can better manage.

In your case, you have a limitation of 20 outgoing mails imposed on you by your service provider. To ensure you can send mail to more than 20 people at a time, you will have to use cron to get around this limitation.

The throttle you refer to is the number of messages sent PER cron. Removing cron isn't advisable for a substantial list, as your server will connect to Amazon, attempt to deliver all the mails, of which only 20 would be accepted.

Without knowing the inner workings of Simplenews, one of two possible (and undesirable) scenarios would unfold:

1.) Any mail in excess of the first 20 would be ignored by Amazon, and sending would fail. Your site would ignore the errors, and of your entire "Send" event, 20 mails would go out.

2.) Simplenews might cache the remaining mails that Amazon doesn't accept in your DB. These would wait around to be sent at a later stage (next cron run), but because you're not running cron, Simplenews wouldn't be invoked during cron, and that queue would never be properly addressed. This would result in you sitting with a large number of unsent mails clogging up the Simplenews spool table.

Bottom line, disable cron at your peril. The second your subscriber base goes over 20, your newsletter sending process will start to give you issues.


Reset a page with multiple exposed filters

Are the query parameters showing in the URL?  Perhaps you could simply direct users to a clean version of the page without the parameters...


How to make Drupal 6 search result URL have ".html" at the end?

custom_url_rewrite_outbound() is not the only function you need to place in settings.php; you need also custom_url_rewrite_inbound(), which converts back the URL to the one known by Drupal.

For those functions, you can use code similar to the following one:

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  if (preg_match('|^search/([^/]+)/(.+)|', $path, $matches)) {
    $path = 'search/' . $matches[1] . '/' . $matches[2] . '.html';
  }
}

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  if (preg_match('|^search/([^/]+)/(.+)\.html$|', $path, $matches)) {
    $result = 'search/' . $matches[1] . '/' . $matches[2];
  }
}


I want to change the layout of add/edit page

As shown in the comment at the beginning of theme_get_suggestions(), for a URL such as http://www.example.com/node/1/edit, the following default suggestions will be used.

page__node
page__node__%
page__node__1
page__node__edit

If you want to add page__node__edit__article as suggestion, you need to implement hook_preprocess_page() in a module. The following code works for any content type.

function mymodule_preprocess_page(&$variables) {
  if (!empty($variables['node']) && arg(2) == 'edit') {
    // (1)
    array_unshift($variables['theme_hook_suggestions'], 'page__node__edit__' . str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $variables['node']->type));
    // (1)
  }
}

If you want to be use not to apply the template file for, e.g., node/1/edit/revert, replace the code between // (1) with the following one.

$arg3 = arg(3);
if (empty($arg3)) {
  array_unshift($variables['theme_hook_suggestions'], 'page__node__edit__' . str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $variables['node']->type));
}


EntityReference and custom field but not Title

I believe you are looking for the Entity Reference autofill module.

Please excuse me if I misunderstood your need.


In your custom module use the hooks defined in the Ubercart terms and conditions module.


How to redirect from confirmation page back to page of form?

I have written the code for d7 where the article node form once submitted it is redirected back to the form.
    It will help you for d8.
    /**
     * Defines hook_form_alter()
     */
    function demo_form_alter(&$form, $form_state, $form_id) {
        if (strstr($form_id, 'article_node_form')) {
          $form['actions']['submit']['#submit'] = array('demo_form_submit');
        }
    }
    // custom submit handler for '_node_form'
    function demo_form_submit($form, &$form_state) {
      // call default action
      node_form_submit($form, $form_state);
      $form_state['redirect'] = url('node/' . 'add' . '/article', array(
          'absolute' => TRUE
        )
      );

      $_GET['destination'] = $form_state['redirect'];
    }


Integer thousands separator in add node form

you can quickly and easily build a custom module around this:

<form>
    <input type='text' id="input">
</form>

<script>
    jQuery('#input').keyup(function (event)
    {
        var value = jQuery('#input').val();

        if(event.which >= 37 && event.which <= 40)
        {
            event.preventDefault();
        }

        var newvalue = value.replace(/,/g, '');
        var valuewithcomma = Number(newvalue).toLocaleString('en');
        jQuery('#input').val(valuewithcomma);
    });
</script>

adapted from here

EDIT

This code has been modified and works in Bartik theme, using an Article content type with an integer field 'number' - it simply resets the value of the input and strips the commas before the form is submitted to the server:

<script>
    jQuery('.page-node-add-article .field-name-field-number input').keyup(function (event)
    {
        var value = jQuery('.page-node-add-article .field-name-field-number input').val();

        if(event.which >= 37 && event.which <= 40)
        {
            event.preventDefault();
        }

        var newvalue = value.replace(/,/g, '');
        var valuewithcomma = Number(newvalue).toLocaleString('en');
        jQuery('.page-node-add-article .field-name-field-number input').val(valuewithcomma);
    });

    jQuery('.node-article-form').submit(function()
    {
        var text = jQuery('.page-node-add-article .field-name-field-number input').val();
        var newtext = "";
        for (var i = 0; i < text.length; i++)
        {
            var c = text.charAt(i);
            if (c != ',')
            {
                newtext += c;
            }
        }
        jQuery('.page-node-add-article .field-name-field-number input').val(newtext);
    });
</script>


If you are using varnish in front of the your server, then it will completly cache you request, Mobile tools will not be able to determine the useragent is mobile or desktop to redirect the theme.

One of the solution is to determine at varnish level and redirect to a m.domain which always has a mobile theme attached to it.

Refer the following links

http://fangel.github.com/mobile-detection-varnish-drupal/
http://mobiledrupal.com/content/mobile-device-detection-varnish-0


Checking where are users coming from to the landing pages

If you are able/willing to add some type of query parameters, you should be able to make this work using the Rules module, as detailed below.
Assume a path like /index.php?campaign=123) you can make the value (= 123) of the URL argument (= campaign) available as a new variable to the Rules module. To do so, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


How do I get the userpoint description to include clickable node link?

You can reference the node using the entity_type => 'node' and entity_id => $node->nid arguments, then the description will automatically be linked to the node.


How do I make a form in Add Content using Drupal 7?

I'm not sure if you really can do this with it, but have a look on:
Webform


You're trying to assign a value to an object property without declaring the object.  Try this:

function review_m_admin_settings_form_submit($form, &$form_state){
    $node = new stdClass();

There's actually not any need to check if $node->text isset either because we know we haven't set it already.

You also need to pull your form values from the $form_state variable.  For example:

$node->text = $form_state['values']['text']


URL: http://example.com/service_enpoint/file

Method: POST

file: (file to be uploaded in base 64 encoded format)

filename :plus-box.jpg

uid: 55

The jpg file should be uploaded in base 64 encoded format.

As response you will get a fid , which you will have to pass in the image field while creating the node.


Instead of adding the field to the product, consider adding the field to order items.

Then make it available in 'manage form display' -> 'add to cart'.

in Drupal 7 this functionality was provided by Commerce customizable Products module, now it has been moved into Commerce 2.x itself.


Either you made a mistake when copying and pasting that PHP code, or you defined calculator_preprocess_page() as being inside calculator_help(). Also, as Ivan Jaros also pointed out, Drupal 8 requires you to use hook_page_attachments() to attach page-level assets.

I do recommend you add these assets elsewhere in the code, preferably in the render array you build that actually needs the library.


You want to change the email before it is sent.
So try this as a starting point (put together with the help of:
1. your post
2. https://drupal.stackexchange.com/a/98559/34326
3. https://www.drupal.org/node/2057703#comment-8343071):

function mymodule_mail_alter(&$message) {

    if ($message['id'] == 'message_notify_commerce_order_order_confirmation') {
        $file = file_create_url(file_build_uri('path-to-file-relative-to-your-files-folder.pdf'));
        $attachment = array(
            'filecontent' => file_get_contents($file),
            'filename' => 'test.pdf',
            'filemime' => 'application/pdf',
        );

        $message['params']['attachments'][] = $attachment;
    }
}

The file should be located in sites/default/files or whatever applies to your site.
You should also change filemime to what matches your file.

I am getting errors "realpath() expects parameter 1 to be a valid path" and "is_file() expects parameter 1 to be a valid path", but the email with the attachment is sent anyway, which is why I am posting this.The errors seem to be related to the 'filepath' parameter which is mentioned in the 3rd link, because depending on what I define, the results vary:
eg. 'filepath' => $file,, which gives me no attachment and no error or 'filepath' => $file->uri,, which gives me an additional error about a "non-object" and no attachment.

http://passivemanagement.net/blog/2014/01/let-drupal-send-email-attachment-using-mimemail-module uses a different markup for the file, but right now I can't figure out, how to adapt it to the task at hand.


Redirecting after login for specific roles

Some things to look at:

'query' itself needs to be an array, not a string, eg...

array('id_rub' => '14', 'lg' => $language->language)

and if you want to call header() directly, you need some more parameters:

header('Location: ' . $url, TRUE, $http_response_code);
drupal_exit($url);

(and an exit for good measure...btw, that's all drupal_goto() is really doing anyway)


How to show message view containing own and following activity?

About the Message module and user activity

Even though you're question doesn't really say so, I'm assuming that:

"activity" in this question is about message instances created by the Message module, targeted to the current user.
"activity of the user he is following" is about message instances target to the current user (also), though they are about events related to any of the followed users (indicated by your follow-flag).

If these assumptions are correct, then your question is about creating a view of various flavors of messages (typically created using various Message Types), which are all targeted to the current user.

Creating a view about Messages by user

Add a new view

View name "Messages by user".
Show Message.
Type All.
Create a page (not a block)

Create a table display of this view

For this question here, you only need a single table display, of All messages.

To differentiate this "All", think of additional displays you might want to add later on, such as:

Read messages
Unread messages

Add Contextual Filters

Message: User uid, and for "When the filter value is NOT in the URL" use "Provide default value" with Type "User ID from logged in user".

Add Relationships

"Message: User uid" will result in the messages targeted to the current user, so that one you need for sure.

I suggest you create a first display only using the above relationship (to check the results you get so far). Then clone this display into another one, in which you add another relationship like "Flags: follow (by current user)" (assuming that follow corresponds to your follow-flag). By swapping between the 2 displays, you can decide which one you really want, or just keep both.

Add Fields

Message: Message ID (Msg ID)
Message: Timestamp (Created on)
Message: Render message (Get text) (Text)
(User) User: Name (User), and use "Exclude from display" for this field, which is only needed to add a "Global: Text area" to the views headers which contains something like Messages for user [name].

Add Sort criteria

Message: Timestamp (desc)

Further Refinements

Filter criteria: none
Page settings:

Path: /user/%/messages
Menu tab: Messages

Make the Messages manage-able

If you complete the above steps, you'll have a view that shows all relevant messages ... and that's really it. It won't be obvious for a user to remember which messages have been read already, and which ones are new (= unread). Try it for yourself (to experience the pain ..).

To implement a facility to mark messages as read/unread, just perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

Create a flag (using the the Flag module).
Create a view 'Messages by user' (= improved version of the view specifications described above).
Use Rules to flag/unflag messages.
Trigger the Rules Component to mark messages (using the VBO module).
Create notifications about Unread Messages (using the "Menu Badges" module). So that whenever a new message gets created, the user gets a notification in the format of an iOS-like (red) badge with the number of unread messages.

Fruit of your labor

If you follow the above steps, the result of it is something similar to an eMail client inbox, whereas the eMail "messages" are not real eMails, but instances of messages created by the Message module.


Is this the right way to do this? Inserting a block into the content body field of a node

I am not one to say what is a/the best way, but if template_preprocess_WHATEVER() is, you set it up something like this:

function template_preprocess_WHATEVER(&$vars) {
  if ( CONDITIONS YOU NEED IF ANY ) {
    $block = module_invoke('book', 'block_view');
    if ($block) {
      $book_block_view='
';
      $book_block_view.=render($block);
      $book_block_view.='
';
    }
    $vars['book_block_view']=$book_block_view;
  }
}

and now you would have $book_block_view available in WHATEVER to print or use.


Follow an example:

$result = db_query('SELECT tid, count(tid) AS count FROM {taxonomy_term_field_data} WHERE vid <> :vid GROUP BY tid', array(':vid' => 'tags'));

But, from docs...

  Deprecated

  as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a
  database connection injected into your service from the container and
  call query() on it. For example, $injected_database->query($query,
  $args, $options);

More info in db_query.

Edit 1:

Drupal set by default sql_mode with 'only_full_group_by', in your case when you use SELECT *, an database exception is throw, look in your log, you will see something like this:

  Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'database.table.field' which is not functionally dependent on columns in GROUP BY clause.

So to correct this you must aggregate all fields in your SELECT list. If you only need e-mail list something like this can solve:

db_query('SELECT email FROM {contact} GROUP BY email');


Field settings are not being exported with Features

The setting got exported but could not be set, because it was referencing an nonexistent product type.

On the old site i had a Recurring Product type w. a "recurring_product" machine name. I wanted to export the display for this. On the new site only a "recurring" product type existed and therefore could not match the setting.


How to debug and fix error [fcgid:warn] (OS 109)The pipe has been ended , get overlap result error, [core:error] End of script output before headers

This issue should be fixed in the newest Varbase release. See: https://www.drupal.org/node/2912709


Two forms on the same page - both submit the same

Found the solution. The problem was that the forms had the same form_id -- some_form_name, the string passed to drupal_get_form().

I generated the string with something like drupal_get_form('some_form_name_' . $product_id); instead of passing as second argument.

However, that means I would have to define a function for each product id. To avoid this, I implemented hook_forms(), so that each form id starting with some_form_name_ would use the same callback to generate the form:

function mymodule_forms($form_id) {
    if (preg_match('/^some_form_name_\d+$/', $form_id)) {
        return array(
            $form_id => array(
                'callback' => 'some_form_name',
            ),
        );
    }
}

This way, even though each form has a different form_id, they all use the some_form_name function to generate the form.

And no problem left.


What approach you want to use depends on the remote database and how dynamic the information is as well as how much data you expect to display.

If the remote DB is easy to work with and you don't need to do anything interesting with the data you might integrate with it using a custom module working directly against the remote database.

If the data needs to integrate with typical Drupal stuff (Views, Panels, Pages, Fields) then you might want to pull the data into nodes. This would still probably mean a custom module. I believe the Migrate module (http://drupal.org/project/migrate) could be a good help here.

How current the data needs to be is also a consideration. Should it checked for new content every time a certain page is visited or is it fine to run it on a cronjob in the background. Like every 3 hours?


Had this question once, came along this Generating node title from node fields

In the reactions, there's a little gem in the comments: https://www.drupal.org/project/auto_entitylabel
You can use Tokens and al kind of this stuff ;-). When your field is field_foobar then you'll have the tokens [field_foobar-formatted] and
[field_foobar-raw]


How to Configure WebForm to Allow Users to Choose Which CiviCRM Campaign to Contribute to?

You can actually do this without Webform-CiviCRM if you like:

Set up your campaigns in CiviCampaign
Create a new profile to add a field to (or from the Profiles page, click "Fields" beside an existing profile to add a new field there)
Add a new "Campaign" field to the profile you are working in (this will list all active campaigns in the profile)
Add the profile to the Contribution Page in question (note: if you added the field to an existing profile it may already be on the Contrib Page)


What version is the CKEditor in the CKEditor module?

The library files are linked to directly via CKEditor's own CDN, so the answer can change depending on what their CDN is currently serving.

You can use ckeditor_get_version() to check which version is currently being used:

$current_version = ckeditor_get_version();
// e.g. 4.3.2


How to switch table prefix in a module in Drupal 6?

The prefix is stored as one of the variables in the settings.php file, all of which are made global early on in the page build process.

That in mind, you can do something as easy as:

$GLOBALS['db_prefix'] = 'db1_';
print variable_get('site_name', 'default'); // Site name from first set of tables

$GLOBALS['db_prefix'] = 'db2_';
print variable_get('site_name', 'default'); // Site name from second set of tables

Bear in mind that this change won't persist across page loads so you'll need to do your processing in a single load, or implement some sort of system to track which prefix you should currently be using.


How to make my custom theme suggestion the most specific

Suggestions is a PHP array that is provided by a hook and an alter hook. The standard rules apply, alter hook is later, so add it there to be more likely to be the last.

And if you want to be sure, set the module weight and/or implements hook_module_implements_alter() to ensure that your module is the one that is called last.

If you want to implement this in a theme then you only use the alter hook anyway and the module_implements_alter() won't work, but themes and especially the active themes are called last anyway.

The duplicate is possibly because the defaults include a suggestion for the field type and one for the field name, so if you name it the same as the field type, then you get the same suggestion twice


CSV import ends up in unresolvable state

I solved the problem by cloning my import.

When I selected the cloned import it wasn't hampered by the progress information and greyed out import button. I could just upload my csv via the new import.


CKEditor with CKFinder - removing the 'Browse Server' button, but only for certain profiles

In case anyone else end up on this link to look for a solution.
I am using wysiwyg, IMCE, IMCE wysiwyg api bridge, and ckeditor.

Configuration -> Media -> IMCE -> Role-profile assignments

select User-1 or any other profile according to your setting.


Adjusting module weight: what are the risks and things to look out for?

Well there isn't a general answer to this, it really depends on the modules. Some of the things I would take into consideration (In Drupal 6) :

hook_boot is called as modules are loaded ; so only modules that are lighter than you have been included. If you rely on code from another module that is heavier than you, make sure you include them manually.
If a module has by default a weight other than 0, then it means that this module specifically set this weight. Check that module's .install file, as this is most likely where the weight is set - and with a bit of luck there will be a comment explaining why ! (this may be true even if the weight is zero)
Modules that set either a very low or very high weight usually have a good reason for it (must run before/after everything else). Typically development modules do this, though others might as well. Keep these modules first/last unless you have a good reason for it.
Look at the module's dependencies (the ones the module depends on, and the ones that depend on this module). Ideally keep these modules in the same order. If you must change the order, the only way to understand the consequnces is to look at the code.
Use common sense. Information that is added by a module (say to a node on node load) will not be available to modules lighter than this one.


Connecting multiple data entities to the user object

You would probably be best to create a Shipping Address content type. You should also look at the Address Field module to collect the addresses rather than field collection.

Then you can create a simple view to list the shipping addresses (Node Tile not linked) using a contextual filter on uid. Then set up a node reference field in your webform using the view to provide the values. The user can then select which shipping address to use for his order.

On the user page you mav use the same view (separate display listing titles as edit links) to let them edit their shipping addresses, and give them a link to add new addresses if necessary.


You can, if you write the code for doing that yourself. Core currently doesn't offer a way to do that automatically.

See Impossible to uninstall Flag and the linked issue for Simplenews for inspiration.


D7 module for payment associated to a node?

There are a number of options. Drupal Commerce is obviously really powerful, but if you want something light take a look at the Drupal Pay module. It is pretty light weight and integrates with webform and a number of other modules.


Views rewrite output including the wrapper divs?

I found the answer myself. I use the modul views_fieldsets.


Warnings still show on page even after setting Error messages to None in Logging and Errors

That's a pretty specific error message, and google says it is coming from this module:

https://www.drupal.org/project/netforum

at these lines: 808-812

  catch (Exception $e) {
    if (isset($cache_max)) { //this implies that we went even further back in the cache and could not connect, so call it quits
      if (variable_get('netforum_hide_error_messages', 0) == 0 || user_access('administer site configuration')) {
        drupal_set_message(t('Could not retreive data from server or cache.'), 'error');
      }

More specifically to your question, because the above module is using drupal_set_message it is not going to be effected by the 'error_reporting' level since that only impacts errors that would go to the logs. This makes sense as you would want to be able to suppress syntax or PHP errors while still letting system messages like "node was saved" or "subscription processed" still appear to the screen.

Your options to suppress this are to deal with the underlying cause of the error from the module (best case), or remove the 'messages' functionality from your theme, i.e. remove where ever it is that it says:

print $messages;

but again, that is probably not the best course of action here.


How can I expose a view with date filter?

In 7 you can do this with Better Exposed Filters by selecting the jQuery UI datepicker option in the screen of your screenshot. There is an alpha out for 8.

  The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience.

  Views Filters is a powerful tool to refine the results returned by a
  given view. When you expose a filter, you allow the user to interact
  with the view making it easy to build a customized, advanced search.
  For example, exposing the node type field as a filter lets your site
  visitor limit their search queries to just blog entries. Better
  Exposed Filters gives you greater control over the rendering of
  exposed filters.


How to change error message of the webform


In code, only create a revision if a field is changed

This may do the trick in a hook_entity_presave(), or get you close:

$old_dog = clone $dog;
update_the_dog($dog);

// Use == to allow for out of order keys.
$same = $dog->toArray() == $old_dog->toArray();

This is kinda of cheating, and you may want to filter the arrays for just the fields and not the properties.  It also isn't multilingual-safe.

To do it properly, start reading ContentEntityBase::hasTranslationChanges() and FieldItemList::equals().  The code above makes a lot of assumptions about fields and storage, which ContentEntityBase() does properly.


Programatically save node fields if fields is autocomplete?

@jsh I'd suggest to create a test node through the admin menu (i.e. node/add/content_type) then dpm/debug the $node object in that content type template and finally view the node and look through the object's output and see where your code differs from the object constructed by Drupal.


Retrieving customer information to use in drupal commerce payment module

The customer profile is attached to the order, and it has an address field that holds the information. To get it you could do;

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$address = $order_wrapper->commerce_customer_billing->commerce_customer_address->value();
$postal_code = $order_wrapper->commerce_customer_billing->commerce_customer_address->postal_code->value();
...

It's a lot simpler to use the entity metadata wrapper as shown above. What it does is that it loads the customer profile entity for you and let you access it's field.


If what you mean is the node contents, in D6, this would be as easy as $node = node_load(array('title' => $text)); and I would hope the same holds true it D7, but I've been known to misspeak a bit there :)  Just realize that titles aren't necessarily unique.  If you mean the page, with all the header, footer, css, js, blocks and so forth, that's another story in of itself.


EntityFieldQuery for getting the count of a user blog

Try this

global $user;

$query = new EntityFieldQuery;

$count = $query->entityCondition('entity_type', 'node')
 ->entityCondition('bundle', 'blog')
 ->propertyCondition('status', 1) // Getting published nodes only.
 ->propertyCondition('uid', $uid)
 ->count()
 ->execute();

print $count . ' blogs from ' . $user->name;


Sometimes I think people do not know how to use search in our time.
You can find the answer on stackoverflow, similar question has already been asked. Have a nice day.


View of related nodes by continent or country without taxonomy terms

There are like mostly in Drupal several possible solutions. One would be to filter Views views for each view and therefore you can filter any field you want the same way, like you do with terms (check the terms view pages as an example, how to build such filtered views).

Another option would be to create node relations like provided with the Relation module or the Entity reference module. The advantage of the relation module is, that the relations are own custom entities which are fieldable again, like term view pages. Thanks to @diqidoq for pointing me to this solution.


How to detect if "Show end date" is checked?

It's stored against the field settings in the field_config table. You can get access to it through the API with field_info_field()

$field_info = field_info_field('field_name');
$to_date_setting = $field_info['settings']['todate']; // optional, required, etc


Add a having condition that makes use of COUNT

Instead of putting everything in one expression. I was able to achieve what I needed by creating an alias for the COUNT like so

$query->addExpression('COUNT(DISTINCT incidenttype.field_incident_type_tid)','typeCount');

and then add a having Condition afterwards using the alias I created like so.

$query->addExpression('COUNT(DISTINCT incidenttype.field_incident_type_tid)','typeCount');


Is it possible to filter by Content Type Variant in Views?

i agree with Niall comment, if is only one contentype, use only one variant and control what to display in views, use content panes views, set contextual filters, relations, and how to pass parameters between views and panels in views ui middle column, pane views are design to "talk" with panels, make several views as needed, add them all to panel variant, and control wich pane to display in panel rules settings.
If there are more than one contentype, add a variant for each one.


Why does the Multifield module not show an "Add" option?

First you must add a Multifield field to a Content Type. For this go to:

admin/structure/types/manage/YOUR_CONTENT_TYPE/fields

And if you go to:

admin/structure/multifield

You will see your Multifield field and you will be able to "Add" (Manage subfields) the subfields


in views-view-grid--viewname.tpl.php, with print_r($variables), you will find the whole values in the 'view' array (is a very huge output, so I recomend only pull 1 item in this test).

here you will discover that 'result' carry the stdClass Object with the fields of views (not it all, seems that the images are not there), to print this you can use:

print_r($variables['view']->result);

with the id of the values, you can use these values for example, show a node title:

echo $variables['view']->result[$i]->node_title;

or you can use the id of the node to get, for example, images from nodes (seems that the images are not in result).

$nIdItem = $variables['view']->result[$i]->nid;
$node = node_load($nIdItem);
echo "<img src='/".$node->field_image[0]['filepath']."'>";

so with this way is possible to control each field, set of fields, and/or add conditions, functions.

I do not know the performance or security implications of using this way, this may be a new question.


Showing Forum Topic Count 0 because, content access module conflict with Advanced Forum

Finally, I find solution for my issue and post it on issue list of Advanced Forum. Also patch is created, and pushed in to future development.


FACEPALM

ok, I found the ideal solution. When I looked at my authored nodes in /admin/content, it listed them all as Status: Published. HOWEVER, when I selected all of them, selected "Publish Content" from the action dropdown, and hit "Apply to selected items", suddenly everything appeared in the view block field.

My guess is that something in the database needed to be updated. Seems like a bit of a bug, though - this should have been automatically handled by either Drupal or the block_field module.

Anyway, fixed now.


What does -1 signify in system.schema_version?

-1 means the module is not installed. Updates are only run on installed modules, which is why any update in a module with a status of -1 will not run. If the module is coded properly, when the module is installed, it will be installed in the same level as if all updates had been applied, as updates are used to bring the database in line with the current definition of it in hook_schema().


How to avoid Pathologic module to change a javascript src value?

You can try adding Javascript in your template files by using

<?php
drupal_add_js(drupal_get_path('theme', 'mytheme') .'/mytheme.js');
?>

also this works in modules etc as explained here: http://drupal.org/node/304255

sometimes it is comfortable to add whole JavaScript inline:

drupal_add_js('jQuery(document).ready(function(){
   // Your stuff
   })
', 'inline');

Hope that helps avoid that module behaviour.


The "Add another item" button doesn't work with field groups

another option is to use the field_collection as described here: http://openconcept.ca/blog/mducharme/creating-multiple-value-field-groups-drupal-7

i'd like to see this in field_group to though - as the detour of making collections under 'structure' isn't as intuitive as under 'manage fields'


How to restrict access to edit image file while still giving permission to edit image title?

It can be done using Image Field Permissions module.

The Image Field Permissions allows you to set permissions to view, create and edit the image file, title and alt attributes.


Modify existing block programmatically by block id

You might try with hook_block_view_MODULE_DELTA_alter which:

  Performs alterations to a specific block


What will happen to my existing panels if I reinstall the panels module?

You will lost your custom panel configuration. To prevent that you can export all your panels to code with features.

This is because modules should remove its own data on hook_uninstall.

Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

This way you will have a features module with all your panels configuration.

This are the steps:

Install features module.
Go to admin/structure/features/create
Give a name to the feature module.
Select panels configuration
Download the feature.
Move this module to the features folder (site/all/modules/features).
Uninstall panels
Enable panels
Active the feature on admin/structure/features

There are also 'export' and 'import' tabs/links on the Panels UI and Pages UI but this is a manual process and can be slower than using features.


How to have search results from a views defined block display on page?

This is from a project I worked on a while ago. It uses Search Api and has a full search page at product-search/% (a Search Api view). After the redirect in the block's form submit, it places the search term into the search box text field for the search page. It's not a direct answer to your question as you will have to adapt the code if you want to use it.

function MODULE_block_info() {
  $blocks = array();
  $blocks['product_search'] = array(
    'info' => 'Search Products',
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  return $blocks;
}

function MODULE_block_view($delta) {
  $block =  array();
  switch($delta) {
    case 'product_search':
      $block['subject'] = t('Search Products');
      $block['content'] = drupal_get_form('MODULE_search_products_form');
      break;
  }
  return $block;
}

function MODULE_search_products_form($form, &$form_state) {
  $form['search'] = array(
    '#type' => 'textfield',
    '#title' => t('Terms to search for'),
    '#size' => 28,
    '#maxlength' => 128,
    '#required' => TRUE,
  );

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

  return $form;
}

function MODULE_search_products_form_submit($form, &$form_state) {
  drupal_goto('product-search/' . $form_state['values']['search']);
}

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'views_exposed_form':
      if ($form_state['view']->name=='product_search_api_view' && $form_state['view']->current_display=='page') {
        // get the view argument if defined
        if (isset($form_state['view']->args[0])) {
          // Set form filter input value to term tid
          if (!isset($form_state['input']['search_api_views_fulltext']))
            $form_state['input']['search_api_views_fulltext'] = $form_state['view']->args[0];
        }
      }
      break;
  }
}


Maintenance page is not loading anything in the head tag

Here is the full source of a typical maintenance-page.tpl.php

<?php

/**
 * @file
 * Default theme implementation to display a single Drupal page while offline.
 *
 * All the available variables are mirrored in html.tpl.php and page.tpl.php.
 * Some may be blank but they are provided for consistency.
 *
 * @see template_preprocess()
 * @see template_preprocess_maintenance_page()
 *
 * @ingroup themeable
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">

  <title><?php print $head_title; ?></title>
  <?php print $head; ?>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<body class="<?php print $classes; ?>">

        <?php if (!empty($logo)): ?>
          <a href="<?php print $base_path; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
            <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

        <?php endif; ?>

          <?php if (!empty($site_name)): ?>

              <a href="<?php print $base_path ?>" title="<?php print t('Home'); ?>" rel="home"><?php print $site_name; ?>

          <?php endif; ?>

          <?php if (!empty($site_slogan)): ?>

<?php print $site_slogan; ?>

          <?php endif; ?>

      <?php if (!empty($header)): ?>

          <?php print $header; ?>

      <?php endif; ?>

      <?php if (!empty($sidebar_first)): ?>

          <?php print $sidebar_first; ?>

      <?php endif; ?>

          <?php if (!empty($title)): ?>
<?php print $title; ?>
<?php endif; ?>
          <?php if (!empty($messages)): print $messages; endif; ?>

            <?php print $content; ?>

      <?php if (!empty($sidebar_second)): ?>

          <?php print $sidebar_second; ?>

      <?php endif; ?>

        <?php if (!empty($footer)): print $footer; endif; ?>

Recheck your page against any missing variables.


How can I change the title of the site on Google search?

Meta Tag

The Metatag module allows you to automatically provide structured
metadata, aka "meta tags", about a website. In the context of search
engine optimization, when people refer to meta tags they are usually
referring to the meta description tag and the meta keywords tag that
may help improve the rankings and display of a site in search engine
results.

Basically it allows you to format your title and description that gets indexed by search engines.
Once you install it, you need to override the Global: Front Page and remove the [site:name] token.
Here is a Video Tutorial
PS: You will need to wait until Google crawls your site again to see changes.


You're right, something that is a 'descriptor' or category is best left as Taxonomy (i.e. Time > Morning/Afternoon/Evening) where they are used to enrich the meaning of data.

  Now I don’t want to create taxonomies for this classes as I’ll have URLs that don’t have anything on them

If access to taxonomy paths is a concern, you can install the Rabbit Hole module to disable access to it while preserving the functionality of taxonomy behind the scenes.

You can also use other modules like Taxonomy Views Integrator to 'change' the way taxonomy paths behave. In this modules case, you can display a View on these paths instead of the default page callback for taxonomy. The View can be anything you'd like.

Otherwise, if you attempt to create a custom table to store this data, you will need to use the appropriate hooks in the Views API to describe the table and it's data, and how it relates - which can be a lot of work. In the end, it sounds like you'd wind up duplicating taxonomy current functionality.


would like to replace node contents with pdf under some conditions

If you have to replace the entire page content, then you will have to alter the page.tpl.php conditionally, You can implement hook_preprocess_page for checking for node id or node type, Then modify the content printed in page.tpl.php.


Custom page containing list of nodes separated by content type and date like an Archive


Views with node references result redundant records

I have found the most possible answer. It may need to update the query from hook_views_query_alter(). The generated query from views is here :

SELECT node.nid AS nid,
    field_transport_node.nid AS field_transport_node_nid,
    field_transport_node__field_data_field_price.field_price_value AS field_transport_node__field_data_field_price_field_price_val,
    node.created AS node_created,
    'node' AS field_data_field_dept_time_node_entity_type,
    'node' AS field_data_field_travel_time_node_entity_type,
    'node' AS field_data_field_transport_type_node_entity_type,
    'node' AS field_data_field_price_node_entity_type,
    'node' AS field_data_field_travel_optr_node_entity_type,
    'node' AS field_data_field_ticket_office_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_transport} field_data_field_transport ON node.nid = field_data_field_transport.field_transport_nid
LEFT JOIN {node} field_transport_node ON field_data_field_transport.entity_id = field_transport_node.nid
LEFT JOIN {field_data_field_leg} field_data_field_leg ON node.nid = field_data_field_leg.entity_id AND (field_data_field_leg.entity_type = 'node' AND field_data_field_leg.deleted = '0')
LEFT JOIN {field_data_field_price} field_transport_node__field_data_field_price ON field_transport_node.nid = field_transport_node__field_data_field_price.entity_id AND (field_transport_node__field_data_field_price.entity_type = 'node' AND field_transport_node__field_data_field_price.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('transport')) AND (field_data_field_leg.field_leg_nid = '2' ) ))
ORDER BY field_transport_node__field_data_field_price_field_price_val ASC, node_created DESC
LIMIT 20 OFFSET 0

I just need to add a condition with "OR". It gives me the correct result.

AND ( ( field_transport_node.nid IS NOT NULL AND field_price_value IS NOT NULL ) OR ( field_transport_node.nid IS NULL AND field_price_value IS  NULL ) )

How can I add this kind of OR condition from views UI ?
How can I do it with query object of the views ?

function mymodule_views_query_alter(&$view, &$query){
    switch($view->name){
        case 'my_view_name' :
            $query->where[0]['conditions'][] = array(
                'field' => '',
                'value' => '',
                'operator' => ''
            );
            break;
    }
}


Cannot get translated value for an entity inside twig

You would need to prepare the taxonomy entities the same way like the nodes. But normally it's not your job to do either of this.

Use viewMultiple() instead of array_map() in the first php example:

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($ids);
$build = \Drupal::entityTypeManager()->getViewBuilder('node')->viewMultiple($nodes, $view_mode);
$variables['events'] = $build;

In Twig:

{{ events }}

Customize the twig of the view mode specific event content type and other templates like the taxonomy field template if needed.


How would files be uploaded to a 2nd domain?

Remote stream wrapper may help...also look Media Mover module...and, at the end, take a look on THIS post...


User to send a list of selected nodes via e-mail to the admin

If you don't have a custom module created yet, make one (always good to have at least one custom module for misc tasks).

Create a menu callback for sending the node information in you hook_menu().

function hook_menu(){
  return array(
    'user/%/sendNodes'=>array(
      'type'=>MENU_CALLBACK,
      'page callback' => 'hook_send_nodes',
      'page arguments' => array(1),
    ),
  );
}

Create the callback function to send the nodes.

function hook_send_nodes($uid){
  // Fetch all flagged nodes from database for this $uid.
  // Send this node information through drupal_mail().
  // After your nodes have been sent, use drupal_goto().
}

So now, you can create a link to the URL user/UID/sendNodes and that will send the nodes.
Obviously this is all pseudo-code, but the idea is there.


How to migrate custom user fields to Drupal 7?

An example migration is here (not my own) and there are some followup comments in that GIST:
https://gist.github.com/893241

What you are talking about is mapping old fields of data to new fields of data in drupal.

You do this by calling addFieldMapping() in your Migration class constructor. The migration __constructor() function typically has 3 big pieces.

Where is the data from. Your $this->source() SQL query.
What fields map from what to where -- per field.
Is there any default values or further cleanup needed of data. By using addField('new_drupal_field', 'old_value')->default('is_published', TRUE); or for instance addField('new_drupal_field', 'old_value')->seperator(',') for more than 1 entry per row.

See documentation on these pages:

MAPPINGS
Examples of Field Mappings
Advanced Field Mappings

The whole migration class, and more importantly its constructor, is basically a recipe of what drupal does per-row of the migration.

So after you have your source $query (basically a SELECT field1, field2, field3 from OLD_TABLE) you call the following:

// this is like saying field_first_name = old_field1
$this->addFieldMapping('field_first_name', 'old_field1');


What is the difference between watchdog Location and watchdog Referrer in dblog messages

The 'Location' is the URL a user/process was visiting when the watchdog entry was invoked.

The 'Referrer' is the URL that referred the user to the 'Location' URL.

So if a person goes directly from a link on http://www.google.com to http://yoursite.com/, and visiting that URL on your site generates a watchdog record, the 'Location' will be '/', and the 'Referrer' will be 'http://www.google.com'.


Is "access administration pages" a valid access argument?

That permission is defined from system_permission().

The access arguments that an access callback uses can be any value, as any access callback can define its own access arguments in the implementation of hook_menu().
If you are referring to the access arguments accepted from user_access(), which is normally the access callback used from most of the menus defined from Drupal modules, then the access arguments are just the string for the permission the user needs to have to access that menu. The "access administration pages" string is just a possible value, and third-party modules can extend the permissions adding new ones to the ones already defined from Drupal core modules.

To get all the permissions defined from the installed modules, and assigned to one of the roles used in your site, you can use the following snippet (it requires the Devel module):

$cache = array();
$result = db_query("SELECT rid, permission FROM {role_permission}");

foreach ($result as $row) {
  $cache[] = $row->permission;
}

dsm(array_unique($cache));

To get any permission defined from the modules enabled in your site, you can use the following snippet:

$permissions = module_invoke_all('permission');
dsm($permissions);

The difference between the snippets is that the first one can return also the permissions defined from a module that you disabled, as long as the permission has been assigned to a role; the second only returns the permissions defined from currently enabled modules. If you have temporary disabled a module, the second snippet will not return its permissions.


Do you really need the publishing date? or just the created date?

If you need the former, well that date isn't tracked by core - http://drupal.org/node/1838918

You could try a contrib module to start tracking that for you... http://drupal.org/project/publication_date

If you're not worried about deleted nodes you can just do what you're after by running a query to count all the nodes that have a created date lower than month X. Or just get all nodes back, and then loop over them in php, successively incrementing counters for each month for your graph.

Otherwise, yeah you're going to have to do something with cron and get snapshots over time. I haven't heard of an existing offering for this in contrib.


Skip a form step programmatically in simple_multistep module

I have solved it by using reduceStep() method to come back.

$skipStep->reduceStep();
$form_state->set('multistep_controller', $skipStep);
$form_state->setRebuild();

Hope this would help someone.


IMCE module button not showing for Editor role?

I was indeed missing a setting somewhere. You have to assign a user profile to the role before they see the button in site configuration -> IMCE.


How to increase the maximum upload size?

You need to make some changes in your php.ini file for Post max size and upload max size

Just follow this link for reference , Click here


Using Rules to publish nodes depeding value in Field

Rules actually can loop based on array, and you have a integer only. Try Rules Array Create. Here is a issue about that.


How to include block using machine name?

I dont think there are any machine names associated with a block. At least didnt saw it in the database. And by the way, why will you want to use the machine name when you already have an unique identifier like the "bid"/"delta" ??


Single SQL query to pull recent two nodes from each node type

$node_types = node_get_types(); // or create own object of node types
$query = $types = array();

foreach($node_types AS $type){
  $query[] = "(SELECT node.* FROM {node} node WHERE node.status <> 0 AND node.type = '%s' ORDER BY node.nid DESC LIMIT 2)";
  $types[] = $type->type;
}

$query = implode(' UNION ', $query);
$result = db_query($query, $types);

$items = '';
while($row = db_fetch_object($result)){
  $items[] = l($row->title, 'node/'. $row->nid);
}

print theme_item_list($items);

Execute time: 0.002s


There is a hook_feeds_after_import for this


I'm absolutely against to add code in templates...

but your problem is here:

<?php if ($row_id == 0): ?>
  <?php print render($page['ad_spot']); ?>

I think this is always FALSE.


How to make galleries relative to particular nodes?

The simplest way: Use colorbox module

In the structure of the content type add an image type (with multiple values allowed) and put its display type to be a colorbox gallery

The complex way: use view slideshow and computed field

Still add an image field to the content type, but set its rendering to hidden.

Add a computed field with the value equal to the node nid and the display a view that take the node nid as contextual filter and render the image field using the slideshow plugin.

Set the display of this computed field as unsanitized.

Computed code:

if (!$entity->nid) node_save($entity);

Display Code (PHP):

$display_output = views_embed_view('<your view name>','<your view display name>',$entity_field_item['value']);

You can get an example here: http://agriregionieuropa.univpm.it/content/event/test-antonello (tab "video ed immagini").

The video slideshow uses the second approach (in this case videos, in your case photoes, it's the same), while the photo gallery uses the colorbox approach.


D7 views node references. Do not displays first node

After hours of googling found how to deal with this issue.
Thanks to this Actual output in view is different than preview

In view settings go to other section -> query settings -> Disable SQL Rewriting.

After saving the view I've seen all my nodes into the node reference field.


Debugging is the art of taking away all possible causes ... in this case you want to make sure that the permissions are set correctly. so that for the user id you're using, it's allowed to post comments.

Not sure if it is "the" reason for your issue, but without appropriate permission Drupal seems to work as it should.

Another reason might be that you have "the field deactivated in the manage dispay settings of the related content type" (as per your comment below this answer seems to be your case).


How to use a between operator in an entity field query?

If you want to include 2 then simply pass 2.

$query->propertyCondition('nid', array(2));

While using between operator, it includes the range values too. So you can just pass the range values you want to include. Still if you want to exclude these range then add one more condition like :

$query->propertyCondition('nid', array(1, 3), 'BETWEEN'); // 1, 3 to get the nid 2
$query->propertyCondition('nid', array(1, 3), 'NOT IN'); // exclude these nids


How do i get the type attribute when adding javascript to drupal?

On the off-chance that you're using an HTML5 DOCTYPE, you don't need to worry:

  The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".

Emphasis mine

Source: HTML 5.1 Nightly - 4.3 Scripting


There are plenty of approaches to this, the main difference being whether you use the Media module or Drupal 7 core's built in image field. The image field route I think will be simpler as you have to create your own view mode to have custom image sizes with display suite and the 7.x-2.x version is still under heavy development. See the related Media modules for options. There are modules for multiple uploads and creating image galleries.

If you choose to use D7 core's image field you can add galleries to content types with the Views Galleriffic module.

Here are Step by step instructions for D7.

You can also switch between styles.

Default

Thumbnails above

For multiple uploads you can try Multiupload Imagefield Widget.

For a remote URL you can try Filefield Sources.

For an "Add image" button you can just create a link to the "/node/add/gallery" node or create a custom form.


Dynamic form fields using #states array on empty select field

Maybe you can try to add an id to your select field

$form['api_title_filter_widget']['api_title'] = [
  '#type' => 'select',
  '#title' => 'API Title',
  '#default_value' => $api,
  '#options' => ["" => "- Select -"] + $published_api_proxies,
  '#ajax' => [
    'event' => 'change',
    'callback' => 'callback_api_product_filter',
    'method' => 'replace',
    'wrapper' => 'api_products_controlled_by_filter',
  ],
  '#attributes' => [
    'id' => 'my_api_title'
  ],
];

Then you should be able to target it through its id :

$form['api_product']['#states'] = [
  'visible' => [
    ':select[id="my_api_title"]' => ['filled' => TRUE],
  ],
];


Why is the block template for User Login not used on user/login page?

The user_page() function returns the form directly (i.e. not in a block) for the user login page. As such it won't fire template_preprocess_block and your dpm() call will never run. If it wasn't called directly in this manner then the User module would inadvertently become dependent on the Block module being enabled, and this shouldn't be the case.

Also, just in case it helps: dpm() will only print out a message for users who have the correct permissions to view them. By default this doesn't include anonymous users.

If you want to change it (temporarily of course, anonymous users really shouldn't have access to variable printouts), go to http://mysite.com/admin/people/permissions and make sure the Anonymous User role has the "Access developer information" permission ticked.


That is going to be dependent on the name of the field you used for that field.  If you inspect, using your browser's inspection tool (right click on the element and choose "inspect element") you can search the DOM for the appropriate div to use to style the field as a whole.

Most likely the field name you are looking for will be similar to:

.field-name-field-description

It should use that naming convention with the machine name of the field at the end, with the spaces as underscores.

This will not exist in the flexslider.css file by default.  You will have to add this.  I would recommend that you add this to your theme css rather than the flexslider's css.

Try adding these attributes to your field's selector initially to get a good idea of where it sits on your page relative to the flexslider itself:

float: left;
width: 100%;
background: red;


Basic difference I run into some time ago: a menu can link to only one content where taxonomy term can refer to several nodes. So, if you need a relationship node -> term that allows one node to be marked with many terms (and, in consequence, have one term assigned to many nodes) then menus won't do that for you (at least not out of the box). Node -> menu relationship is more 1-to-1 where node -> term is 1-to-many.


How to get selected term ID from drop down while ajaxing?

I wasted too much time on this tiny task. However, I have done what I wanted.

Actually, I had to add $form_state['rebuild'] = TRUE; in my callback_function.

if(isset($form_state['values']['submitted']['company_name'])){
    $array_id[0] = $form_state['input']['company_name']; //$form_state['input']['company_name'] array holding the number I wanted.
    $company_ID = $array_id[0];
    $form['submitted']['company_name']['#value'] = $company_ID;
}


Does variable_get() first go to 'variable' table in the database or the $conf array in settings.php?

The function that is responsible for loading the values of the Drupal variables in memory is variable_init(), which executes the following code:

  if ($cached = cache_get('variables', 'cache')) {
    $variables = $cached->data;
  }
  else {
    $result = db_query('SELECT * FROM {variable}');
    while ($variable = db_fetch_object($result)) {
      $variables[$variable->name] = unserialize($variable->value);
    }
    cache_set('variables', $variables);
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

$conf, the value passed to the function from _drupal_bootstrap() is the array read from the settings.php file. The function that reads the configuration file is conf_init(), which is called from _drupal_bootstrap() before calling variable_init().
As you see in the code, the values read from the database are then overwritten with the values find in the $conf array.

Similar code is present in Drupal 7 (see drupal_bootstrap(), _drupal_bootstrap_configuration(), and _drupal_bootstrap_variables()).

The only way to use the value read from the database is to remove the value set in settings.php.


So, the solution was quite simple.

I just needed to remove the call to $form['field_user_address']

//<?php print drupal_render($form['field_user_address']); ?>
<?php // Print necessary validation fields and remove others
      unset($form['field_user_society_id']);
      unset($form['field_user_locations']);
      unset($form['locale']);
      unset($form['account']);
      print drupal_render($form);
 ?>


Customizing the display of properties on a rendered entity

We're trying to put an Entity Reference of this custom entity on a node and render only a few fields - with a form of preprocessing or something along those lines so that we can control the ultimate output.

Sounds like hook_entity_view is what you want. Use "teaser" or create a new view mode, and attach the reference using the given view mode, then implement your logic to render the properties as you like.

Alternatively / additionally, you could look at Display Suite and DS Extras which will give you more flexibility to expose properties via DS custom fields or in field templates.


I've got `PDOException: SQLSTATE[HY000] [2002] No such file or directory` when using drush

This was how I solved it on macOS:

sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

Source: Working with Drush on Mamp.


See what database a site is connected to

I think this is what you are looking for:

https://drupal.org/project/show_database_name

  Display the host and database name of the default database on the status report, toolbar (Drupal 7) and/or on the admin_menu bar if enabled (either Drupal 6 or 7) and/or in a block (to use with the admin module).

It is marked as dev but it looks like a simple use-case and I don't expect there should be any problems.


How can I authenticate against a non-drupal database?

My suggestion would be to take a look at LDAP integration or Lightweight Directory Access Protocol modules to see how they handle authentication.

My recollection is that they hook_form_alter the user_login form to add a new validation function that calls out to the LDAP server if Drupal authentication fails.  You should be able to do this for your own authentication.  We modeled a custom authentication on this method, but I don't recall all of the details.

Just remember that you want to use the external authentication in addition to and not instead of Drupal authenticaion so you don't lock out any admins if/when your other site is down.