Sending a message to users of a flagged node when it is referenced

I would do this by creating a component of type Rule and calling this component from a separate rule that fires on one of the node save or node is updated events.

First create the component with two parameters of node type and name them "referencing_node" and "referenced_node". Create conditions Content is of type [your content type] for both referencing_node and referenced_node (this will bring in data selectors you need for the flagging user list and replacement patterns to construct your email subject and body). Next add a loop under Actions and choose the data selector for referenced_node:flag [your_flag]:user (Users who flagged the entity with flag [your_flag]) and name the list "flagging_users". Now add an action under your loop System: send mail and in your data selector for the To: field, use [flagging-users:mail] and also build your desired subject and message body from replacement patterns.

Next create a rule that calls your component with React on event: After saving new content of type [your_content_type] (you can also create a separate rule later to react on event After updating existing content however you need to build in conditions to prevent repeat email messages when no new references have been added). Now simply call your component as an action and provide your component's parameter with the variables from node (for "referencing_node") and node:your_reference_field_name (for "referenced_node").

I hope this helps you get the solution you are after.


How do I add an image to a block in Drupal 7?

This answer may seem needlessly complex to answer such a simple question, but that is because I have no interest in giving fishes away, I want to teach fishing.

Other answers suggest you embed the image directly in the block with an <img> tag. Personally I oppose that solution because it's "one-off" and prevents the rest of your site's functionality from interacting with the image, such as automatic rescaling of the image.

Two suggestions:

Upload the image to a node, create a View that lists your image, and expose it as a block
Use Panels to control the rendering of your page, and add the image, also from a node

While I strongly recommend using Panels, it's usually quite complicated to setup and understand for Drupal beginners so you may want to skip that.


Can drupal commerce products become cheaper to the customer when they order more?

Assuming you're on Drupal 7 yes, I've done this with the Commerce Price Table module: https://www.drupal.org/project/commerce_price_table

"This is a contributed module for Drupal Commerce that allows you to use a secondary price field to supply an alternate price for a product based on the quantity of that product on the line item. It also provides a field formatter to display the price/quantity values as a table."


Create a taxonomy view
Add node group in relationship
Add term name and node nid fields for display
Enable aggregation in "Other" section (Use aggregation: Yes)
Click nid field settings icon, choose group type "count".

Find the export of views that worked for me.

$view = new view;
$view->name = 'term_node_count';
$view->description = 'Displays node count values for terms';
$view->tag = '';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'term_node_count';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '100';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['expose']['items_per_page_options_all'] = 0;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'name' => 'name',
  'nid' => 'nid',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
  'nid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
);
$handler->display->display_options['style_options']['override'] = 1;
$handler->display->display_options['style_options']['sticky'] = 0;
/* Relationship: Taxonomy: Node */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = 0;
/* Field: Taxonomy: Term */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['element_label_colon'] = 1;
$handler->display->display_options['fields']['name']['element_default_classes'] = 1;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = 1;
/* Field: Node: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['relationship'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count';
$handler->display->display_options['fields']['nid']['label'] = 'Count';
$handler->display->display_options['fields']['nid']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['nid']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['nid']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['nid']['alter']['trim'] = 0;
$handler->display->display_options['fields']['nid']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['nid']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['nid']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['nid']['alter']['html'] = 0;
$handler->display->display_options['fields']['nid']['element_label_colon'] = 1;
$handler->display->display_options['fields']['nid']['element_default_classes'] = 1;
$handler->display->display_options['fields']['nid']['hide_empty'] = 0;
$handler->display->display_options['fields']['nid']['empty_zero'] = 0;
$handler->display->display_options['fields']['nid']['link_to_node'] = 1;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$translatables['term_node_count'] = array(
  t('Defaults'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort By'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('node'),
  t('Term'),
  t('Count'),
  t('Block'),
);


You can use the Field Validation module

  This module adds an extra tab to each field instance, allowing you to specify validation rules for your field instances.

From there you could a custom PHP function/regular expression to match the URLs against the field value.

This will only editable by admin in the sense that they can also edit the PHP code/regular expressions in the field validation rule. I'm not aware of a specific module that will do everything that you want without any customisation.


What is the best way to minify drupal's aggregated javascript (automatically)?

I created a new module to tackle a lot of the aggregation issue & I hope to get a large chunk of it into D8; and yes it's a D6 module: http://drupal.org/project/advagg. Uses the jsmin+ lib for compression of JS and the CSSTidy lib for CSS compression. Main advantage of this is the css/js aggregate file doesn't change names unless it needs to; these files also have a 1 year cache lifetime & has imagecache generation so 404s to your CSS file should be a thing of the past.

Update: AdvAgg 7.x is being developed and comes with minification of JS as an optional sub module. Other D7 options:
http://drupal.org/project/speedy
http://drupal.org/project/uglifyjs


How to create a path alias with a query string in the target?

I think you can do this with the Redirect module (it won't provide an alias in its truest form but it will forward you on to the right page.

In .htaccess you could a custom RewriteRule before Drupal's main index.php rule:

RewriteRule ^myownstuff$ stuff?owner=myself [L,QSA,R=301] # QSA and R=301 are optional here

If neither of these work there is a quick and dirty way in a custom module:

function MYMODULE_init() {
  if ($_GET['q'] == 'myownstuff') {
    drupal_goto('stuff', array('query' => array('owner' => 'myself')));
  }
}

If you've got more than one path to forward/a pattern etc. you'll have to extend this a bit but the logic will work.

I think the .htaccess is probably the best way as it doesn't actually forward on to the URL but masks it internally which I guess is what you're after.

You might also want to look at hook_url_inbound_alter() which I believe you can use to get this kind of functionality...I've not used it before so I can't comment further though.


Difference and relationship between View, Page, Panel and Mini Panel?

Views are used to create lists of things.

One difficulty with Views, is that when used on their own, views tend to become fairly static. Let's say that you have a view that lists "Friends of user X". In your view, you must know define where to find user X. This will mostly be either a contextual filter, possibly using a relationship, but whatever configuration you have, it becomes a static part of the view. This leads us to Pages.

Pages provide the rest of your site with Context. Continuing on the example above, a Page can figure out how to find user X at run-time, and then feed that as an argument to other components, such as the friend view. This means you can re-use the same view, and all the rules that go with it, on both the same page more than once, but also across pages, and having it base it's results on different users every time.

If you want to show the browsing users friends, and my best friends friends, on the same page, you tell the current Page about those two contexts, use the same View twice, and give each instance of that View, a different context as argument.

A page on it's own however, doesn't have a visible interface, neither back- nor front-end, which is were Panels comes in.

Panels Provides a GUI on top of Panels, allowing you to configure Page manager, as well as adding further functionality to Pages, such as render caching.

Mini Panels Essentially embeds an "small" Panel rendering into another Panel. You can think of it as a very intelligent version of a block, capable of defining layouts, requiring parameters, and more.


How can I programatically change the (D8 core) workflow state of an entity with Content Moderation?

A great example could be found in Content Moderation module's code.

$entity->set('moderation_state', $new_state);
if ($entity instanceof RevisionLogInterface) {
  $entity->setRevisionLogMessage($form_state->getValue('revision_log'));
  $entity->setRevisionUserId($this->currentUser()->id());
}
$entity->save();


How to retrieve node body from nid with an SQL query in Drupal 7?

field_data_body does not have an nid field though.

Because a field can be attached to any entity, which may have a different primary key than nid.

If you really must use direct SQL, you can query the field like this

SELECT body_value FROM field_data_body WHERE entity_type = 'node' AND entity_id = 1

However, this bypasses several of Drupal's layers, so it's normally strongly discouraged to use direct queries.

Instead, it's better to

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('nid', 1)
;
$result = $query->execute();

$nodes = node_load_multiple(array_keys($result['node']));

foreach ($nodes as $node) {
  $bodies = field_get_items('node', $node, 'body');
  foreach ($bodies as $body) {
    var_dump($body['safe_value']);
  }
}

The EFQ version have several advantages

It's safe. You can't (easily) accidentally open injection attacks.
It outputs a safely escaped value, avoiding XSS attacks.
It works if a node has multiple values for the body field.
It works on sites with multiple languages.


Have you looked at the Variable Price module?
http://drupal.org/project/uc_varprice

It's ostensibly for donations, but I think it might be customizable for your purpose.


How do I remove the rollover effect from Rubik tooltips

I have not used this theme before, but there is a checkbox on the theme settings page to toggle "Display form field descriptions inline". I believe this is what you are looking for.


You probably have to be auth to be able to send mail from gmail's SMTP (smtp user/ smtp password).
Moreover, you have to "allow" the sender's email in your google account.

theMailYouSendFrom@whatever.com have to be allowed to send mail with account yourAccount@gmail.com; somewhere in gmail's parameters, you can validate this mail.

I remember there is a limit, 450 mails/day for each google account (this could have change now, that was 3 or 4 years ago), and more with payed gapps.


On content, choose the taxonomy parent and display all the children

For anyone interested in the future, I managed to solve this using the Entity Reference Tree Widget module, which provides the exact functionality as described on question.


How to make a non-Drupal page and where to place it?

You need to create a custom module and implement hook_menu() for you custom page.
Here you get details about hook_menu "https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu/7".

To get this link on user menu tab use type as
 'type' => MENU_DEFAULT_LOCAL_TASK
And write your page code by calling a function
'page callback' => 'user_details',

create user_details function and write code for custom page.


Internal URL or menu callback to use node/entity content without html/page wrapping

After some research I maybe found an answer by myself for this question, not sure yet. Maybe temporary or at first glance only.

While I embrace user5482's (Thanks for your fast reply!) approach using hook_menu() in a custom module, what I have considered already, I still have 2 worries. First: there is missing experience on my side and missing documentation on the functions side for its underrated delivery argument (take a look here). Second: Custom modules should only be considered for very rare individual situations, otherwise you fastly run into 10 custom modules on a project which need to be maintained on core updates. If the scenario what you are looking for is more common, the chance is 99%, that there is a module for that.

So, at first, I will try to achieve this with the JQuery_Ajax_Load module, which actually builds on the mentioned hook_menu() and I will report back when I have any news on this.


Ctools give you a modal frame api as well as many different ajax helpers. This is probably your best bet for implementing AJAX in your site.

As for listing all possible ways there are loads, ranging from custom implementations to contrib modules, your best bet would be to search drupalmodules.com for potential candidates.


You can build this without a custom module, and without a specialty contrib module specifically for "appointments".

I would build this using Entityform but you could also just use a basic content type with custom fields. Modules that would go into your recipe would be Date, Date Restrictions, Email field, Page break field, and perhaps Field Group and Display Suite for nailing that layout.

These modules together should allow you to construct an entity (node or entityform) with all of the functions of your screenshot, without custom modules or custom code. Also, you will want Rules to handle the actions that happen when the form is submitted.

You didn't specify if this is just an "Appointment request form" that is later confirmed by a salon employee, or if it is actually to book an appointment that is confirmed automatically. The latter would be much more complex as it would require that Drupal knows about all of the existing appointments and have the logic/ability to eliminate conflicts. For this, see Appointment Scheduling


Checking what user a migration is running as

In the interest of trying to up the percentage of Drupal Questions that have an answer, I'll post the solution that I came to as a result of Clive's comment.

I added a preImport and postImport method to my migration class as follows:

  public function preImport() {
    parent::preImport();
    $GLOBALS['user']->previousid = $GLOBALS['user']->uid;
    $GLOBALS['user']->uid = 1;
    if ($GLOBALS['user']->uid != 1) {
      throw new MigrateException('Run Staff Contributor Migration as user 1.');
    }
  }

  public function postImport() {
    parent::postImport();
    $GLOBALS['user']->uid = $GLOBALS['user']->previousid;
  }

This ensures that this particular migration is run as user 1 and returns the user value back to whatever it had been at the end of the migration.  It also throws an exception if for some reason the user switch failed.


How can I programmatically disable the "Preview" button in a content type?

For programming disabling use special variable:

variable_set('node_preview_' . $content_type, '0');

For default node options "Published" (status), "Promoted" (promote), "Sticky" (sticky) and "New revision" (revision) use variable "node_options_" . $content_type, which takes array as a value.
Example can be found in standard installation profile:

// Default "Basic page" to not be promoted and have comments disabled.
variable_set('node_options_page', array('status'));


Can't submit entityform after ajax callback on select element

It would be useful to have the actual code you wrote to check if there are some errors.
If you check my relative question you can crossreference your code to check if there's something wrong (mine is currently working).
I'd suggest to:

apply the patch of this issue
if still not working do the same workaround I've used: check the $triggering_element to populate the select options only in the opportune moments of the form build.


How to make different users profile pages for different user types in Open Atrium2?

I have not find a such module in the OpenAtrium bundle. You can use the contribute module https://www.drupal.org/project/profile2
Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)


'serialized' field in schema still needs manual unserialization?

This is just a guess, so correct me if I'm wrong...

I think that automatic unserialization is not possible because the schema is not loaded by db_query. While drupal_write_record() loads the schema definition before writing to the database, db_query simply executes the query string you put into it, without knowing which schema definition the query relates to.


Status report: Twitter module using unautheticated api

Twitter module was misconfigured, not updated.


The node from one content type doesn't appears in Nodequeue

Go to admin/structure/nodequeue/
Click 'edit' for the nodequeue in question.
Check 'Real estate' under 'types'.
Save.


How do I store the values submitted in a form in the session?

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

Drupal 7:

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

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

Drupal 8:

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

    return $value;
  }
}

Change record: Access session data through the Request object

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

Examples how to get the session:

Procedural

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

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

Controller

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

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

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

Form

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

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

Private Tempstore

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


What is the simplest way to flush cache at a predetermined date and time?

May be How can I schedule a rule to always be run at a specific hour of the day? can be useful , but using cron, build a module and in it's hook_cron function check for the current time, if it is your specific time use the cache_clear_all function and it's parameters to clear the page and else cache. just make sure that the cron is ran on Wednesday day at midnight. it's periodic run time should come to 24:59.

you can also check the clear drupal cache - php script for more options of clearing the cache statement.


File management- preventing the deletion of files referenced by nodes

This is for them primarily images and PDFs which they intend to add to the server via FTP.

No... I would advise installing the Media Entity and set of modules designed for handling media.

This will allow you to add media in a way that has better treatment than core. You will be able to:

Use one file in multiple places without uploading it again
Build displays based around media, if you need to
Add a button in CKEditor for referencing or uploading new media

If you only upload files in an FTP, you can't do basic things, like:

Resize an image with an image style
See how many times / where an image or file is being used
Generate different displays for different files
Create Views based around media which may be mixed with access grants later on (spitballing)

Core upload fields, or FTP copying, will not grant you anything - and giving non technical people access to FTP instead of a GUI backend like Drupal is far more error prone.

Also, there is a known core issue where files can be deleted without warning, and it is suggested to set the core file system setting of "Delete orphaned files after.." to "Never". No matter how you choose to approach media management, change this setting ASAP until it is fixed.

One of the major benefits of moving from a static setup to Drupal 8 are for reasons like this.


How can I add a custom form menu link to the administrative menu programmatically?

Create a new menu using hook_menu. Like this

$items['admin/config/my_form'] = array(
    'title' => 'My Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_id'),
    'access callback' => TRUE, // Give access as per your need.
    'type' => MENU_NORMAL_ITEM,
);

Using this your form will be created with the link / menu item under configuration menu.

Thanks.


Multiple field Settings not appearing on an entity referenced field

You could create a relationship to the referenced entity and then add a filter where field_FIELD_NAME:delta = 0. Then either add fields that belong to the referenced entity using the relationship or add a "rendered entity" field using the relationship.


you need to add new view 'admin/structure/views/add' and into Show select webform submission continue and edit ... you can get all the submission list into the view.

Add field webform submission data:value

Then select webform node and field you want.

You can see the fields like this

View result

Try it.


Is it possible to render an Adsense Block as a custom field block in Drupal?

You can use Block Inject to create an arbitrary region in your node body. Then place the adsense block in that region. (Please be aware of this issue.)

On a page by page basis, you can also use Insert Block, but there are limitations.


I'd put this in a comment but have no rep so I can't ...

Create a view of hotels as Robin said. The entity reference module provides views relationships that go in both directions , so add a relationship that corresponds to "entity referenced from field yadda yadda" -- sorry I don't know exactly how it'll be labeled offhand but with some trial and error you should be able to find the right one.

Add a contextual filter using the offer relationship on nid, default to content id from url. Be sure to choose the offer relationship when adding fields.

To attach the view to the node itself, you can either use Viewfield or just embed it directly in the template (or preprocess function) using views_embed_view (link)


How do I add an autocomplete to a form element that is not an entity reference?

To add an autocomplete to a form element that is not an entity reference element, you need to use two properties:

#autocomplete_route_name, the name of the route returning the autocomplete array as JSON
(optional) #autocomplete_route_parameters, an array of parameters to pass to the autocomplete route, in the format [<parameter> => <value>]

For example, the autocomplete controller could be implemented from a class similar to the following one.

/**
 * Defines a route controller for autocomplete form elements.
 */
class AutocompleteController extends ControllerBase {

  /**
   * Handler for the autocomplete request.
   */
  public function autocomplete(Request $request) {
    $results = [];

    // Get the typed string from the URL, if it exists.
    if ($input = $request->query->get('q')) {
      $typed_string = Tags::explode($input);
      $typed_string = Unicode::strtolower(array_pop($typed_string));

      // Use $typed_string to load data from the database.

      $results[] = [
        'value' => $value,
        'label' => $label,
      ];
    }

    return new JsonResponse($results);
  }

}

Notice that:

The value entered in the form element is available in $request->query->get('q')
The autocomplete returns an array containing entries with value (the value to use) and label (the value to show), converted in JSON


The exposed filter form is always going to add a query string to the current URL as it's a simple GET form.

You need a form with a submit handler that redirects to the argument based path. You could do this to the existing exposed filter with hook_form_FORM_ID_alter or create a custom form and expose it in a block.

To make the existing form redirect you'd need to do something like:

function mytheme_form_views_exposed_form_alter(&$form, &$form_state) {
  $form['#method'] = 'POST';
  $form['#submit'] = array('mytheme_redirect_taxonomy');
}

function mytheme_redirect_taxonomy($form, &$form_state) {
  $form_state['redirect'] = '/browse/' . $form_state['values']['category'];
}


I want to create a view with filters filters

Not sure how to close this question but I'll add my comments as answer so that Jumma can approve and close it.

You need to expose your filters using the Better Exposed filters module, see this tutorial.

To place your exposed filter in one region and the result of the view in another region you need to expose your filters in a block. See this tutorial learn how to do that.


How to select state on country bases in drupal webform

Use the Webform Simple Hierarchical Select and the Simple hierarchical select modules; just create a vocabulary and add countries and states hierarchically.

If you don't have vocabularies for countries and states, using the Taxonomy Manager module helps you to import countries and states from a simple list like the following.

United Stated
- Alabama
- Washington
Iran
- Tehran
India
- Mbambi


You need to modify these settings to CKeditor.

// The writing rules for the <p> tag.
writer.setRules( 'p', {
// Inserts a line break after the <p> opening tag.
        breakAfterOpen : true,
}

This can either be set programmatically, via JS or I believe you should be able to add it directly via the UI, if you visit the Ckeditor settings page, there should be a box where you can enter ckeditor settings.

For more info see ckeditor docs: https://docs-old.ckeditor.com/CKEditor_3.x/Developers_Guide/Output_Formatting


Why do some webforms have their elements value in translation UI (/admin/config/regional/translate)?

Apparently, this was a side effect of the "translatability" of the elements value. A patch has been created by jrockowitz on the drupal issue tracker which will prevent having those values editable in the translation UI: https://www.drupal.org/project/webform/issues/2965060#comment-12587556


Check the menu_get_active_trail() and menu_set_active_trail() functions. They should be of use for what you want (retreiving and changing your breadcrumb).

Try the following in your template.php in your theme :

/**
 * Implementing theme_preprocess_html
 */
function YOURTHEME_preprocess_html(&$vars) {
    $crumbs = menu_get_active_trail();
    $count = count($crumbs);
    // dpm($crumbs);
    unset($crumbs[$count - 1]);
    menu_set_active_trail($crumbs);
}

See how it goes.


Add condition group in Views filter handler

The answer turns out to be that  add_where() also accepts a DatabaseCondition argument, meaning I could do

$this->query->add_where(
  $group,
  db_or()
    ->condition($table, $vms_target, 'NOT IN')
    ->condition($table, $vms_target, 'IS NULL')
)


I good way to utilize Solr for search with Drupal, is to use the Search API, is has a Solr integration module, which will allow you to setup a View with exposed filters and full text search. With the flexibility of Views, you should be able to setup the view to allow the users to sort as they wish.


How do you get Solr Views to query Acquia Search?

Acquia search :
A search service provided by acquia which in-turns uses the Apache Solr search inside. Currently they are updated their acquia search with Solr 3.5.
Apace Solr Views module :
Module when enabled converts the views query from a database query to apache solr search query.
While enabling the Apache Solr Views module it will look for the apache solr configured in the drupal system automatically.


Rewriting a field in organic group member view

did you try https://www.drupal.org/project/views_conditional?

it allows to conditionally format/rewrite the output of certain views fields depending on the value of other fields that you have added in your view.


What is the best protocol for uploading images in batch via FTP?

I want to substitute all 1000x1000 images with identical images
  with same name but at size 400x400.

Since they are identical, simply use image styles. Create an image style of 400x400 and assign it to your content type's image field OR in your image field settings in a View.

Watch: How to apply image styles in Drupal


Path breadcrumbs Link title for webform submission

I was going to post something with Crumbs, but maybe you can start with something simpler:

I am trying to make this answer useful to different visitors who might have different ideas about their breadcrumb for webform submission pages.

Page access considerations

Do your visitors (those this is meant for) have access to pages like

node/28/submission/1/edit ? (I suppose the answer is yes)
node/28/submission/1 ? (Please check)

With hook_menu_alter()

I'm not sure what this does on a site without Crumbs enabled, but you can give it a try. This will change the page title / navigation title, which I think is used by core for building the breadcrumb.

This means if you had "Submission #1" as part of your breadcrumb, this will replace it with "Submission #2 by NAME".

Consider this code a stub. Especially the $submission->data[1][0]. This just happened to work for me, but might be different for you. devel dpm() is your friend!

/**
 * @param array[] $items
 */
function d7light_menu_alter(&$items) {

  if (!empty($items['node/%webform_menu/submission/%webform_menu_submission'])) {
    /* @see _d7light_webform_submission_title() */
    $items['node/%webform_menu/submission/%webform_menu_submission']['title callback'] = '_d7light_webform_submission_title';
  }
}

/**
 * @param object $node
 * @param object $submission
 *
 * @return string
 *
 * @see webform_submission_title()
 */
function _d7light_webform_submission_title($node, $submission) {

  if (empty($submission->data[1][0])) {
    return t('Submission #@serial', array('@serial' => $submission->serial));
  }

  return t(
    'Submission #@serial by @name',
    array(
      '@serial' => $submission->serial,
      // @todo Maybe something more generic than ->data[1][0]?
      '@name' => $submission->data[1][0],
    ));
}

With Easy Breadcrumb + hook_menu_alter()

Tbh I have only tested the code above with Crumbs enabled. So I don't know if it works without it.

I am also quite confident that it will work with Easy Breadcrumb, based on my understanding how it works.

With Crumbs + hook_menu_alter()

As said: You could try if enabling Crumbs makes a difference.

If you do, you might want to check admin/structure/crumbs/display and enable the "show current page".

With the Crumbs API.

This is an alternative to the method above, which does not change the page title but only the name in the breadcrumb.

Here is a starting point.

/**
 * A hook to register crumbs plugins.
 *
 * @param crumbs_InjectedAPI_hookCrumbsPlugins $api
 *   An object with methods to register plugins.
 *   See the class definition of crumbs_InjectedAPI_hookCrumbsPlugins, which
 *   methods are available.
 */
function MYMODULE_crumbs_plugins($api) {

  $api->routeTitleCallback(
    'node/%/submission/%',
    'webform_submission',
    function($path, array $item) {
      $node = $item['map'][1];
      $submission = $item['map'][3];
      if (0
        || !is_object($node)
        || !is_object($submission)
        || $node->type !== 'webform'
        || empty($submission->data[1][0])
      ) {
        return NULL;
      }
      $submission_name = $submission->data[1][0];
      return $item['title'] . ' (' . check_plain($submission_name) . ')';
    });
}

The same comment applies about $submission->data[1][0].

Changing the trail

Once you have tried those things, you can ask if you need more. I will then write more in this section.


$path = drupal_get_path_alias($_GET['q']);
$path = explode('/', $path);
print $path[1];


Form Alter: How to check if a node has a Field Type

If you are searching for specific field then see the code below

 function hook_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'form_id_name') {
        $abc = array();
        foreach ( $form_state['field'] as $key => $value ) {
            $abc[$key] = $key;
        };
}
    }

From this $abc variable you will get all the field name and then you can check from this array to see if the field you want exists or not using any of the php functions.
For e.g.
you can use array_key_exists('field_name', $abc);


It does not work because the rows are all unique to start of with. Switch on SQL preview in views settings, and you will see that it adds the node's nid to the result in the SQL. Now add nid to the fields, and you will see something like

Book, nid:5
Book, nid:7

Book, nid:5 is not equal to Book, nid:7. For distinct to work, whole rows need to be equal.

What you need is aggregation.

To do that, switch on aggregation for the view in the advanced pane. Then set aggregation to COUNT on the nid.

Now your result will look something like this:

Blog, nid:6 // ie 6 rows with field value blog
Book, nid:2 // ie 2 rows with field value book

Then, finally, to get the output you want, just hide the nid from the views display.

In essence, what you have done is to group by the field 'type', and to count how many nids (rows) there are in each group. And then hide the count as you don't need to display it.


Form, populate select lists values after unsuccessfull validation

Your use of [] in the select name most likely confused the form API.

Try something like this instead:

for($i = 0; $i < 3; $i++) {
  $form['register']['cocktails']['cocktail']['bartender_cocktail'][$i] = array(
    '#type' => 'select',
    '#default_value' => variable_get('bartender_cocktail_' . $i, NULL),
    '#options' => $cocktails,
  );
}

Then, you need to set #tree to TRUE, so that you your cocktails into an array.

$form['register']['cocktails']['cocktail']['bartender_cocktail']['#tree'] = TRUE;

Then, you should be able to access the vaules like this: $form_state['values']['bartender_cocktail'].


One option is to create a "views block" that shows comments, set it to use views infinite scroll, then add it to the bottom of the page (and disable the page from showing comments the normal way).


Pre-First back up your site.

First upgrade to the most recent version of Drupal 6. The follow instructions here to move to Drupal 7:

https://www.drupal.org/documentation/upgrade

Have trouble? Explain where you are in the process at that point so one might help.


Import to Entityform via Feeds? Feeds entity processor module?

CONFIRMED! Feeds entity processor module will allow importing directly into an Entity form via a feeds importer.


How to Output Realtime Computed Field Value

"How do I output a computed field value in real time?"
The answer is that you cannot.  The Computed Field module updates the value on entity save.  So, to get the most recent value, you have to save the entity.
If you are trying to show a value that you compute in a view, computed field is a bad solution because you will have to re-save all the entities whenever you display the view, which is horrible for performance.
Alternative solution idea
Since you're doing calculations based on time, one option might be to use Views filters.  Make a primary view that shows the default pins, and then embed or attach additional views that have filters that are set to find the pins for ending_soon and starting_soon.
If you need to override the Views filter calculations, you can do that in hook_views_pre_view():
Here's a code example from one of my sites where I override the filter value to use "midnight for the logged-in user's timezone)."
function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() === 'my_view' && ($display_id === 'my_display') {
    $filters = $view->display_handler->getOption('filters');
    if ($filters['field_datetime_target_value']) {
      $user_timezone = date_default_timezone_get();
      $current_timestamp = \Drupal::time()->getCurrentTime();
      $midnight_usertimezone_datestring = MYMODULE_get_midnight_datestring("$current_timestamp");

      $filters['field_datetime_target_value']['value']['value'] = $midnight_usertimezone_datestring;
    }
    $view->display_handler->overrideOption('filters', $filters);
  }
}


Render published content or comments on new created content using a link

You can use an Entity Reference field.  In Drupal, most of the "content" that you see, including nodes and comments, are entities.
Entities can be linked to each other with an Entity Reference field.
Here's a tutorial video.
One challenge when working with Entity Reference is that each field can only reference one type of entity-- so you can have an Entity Reference field for nodes, or for comments, but not both at the same time; to have both, you need two fields.
Out of the box, Entity Reference can be configured to select the content by autocomplete or by a select list, which can be the output of a view you have customized, so it's quite flexible.


I have discovered the problem. It is a malfunction of module or submodule Domain Locale. If you have a domain whose list of languages does not contain your default language (main site), then it doesn't work. All the project to the trash, months of development ruined.


Pre load entity reference fields into a node

Add an entity reference field to team members content type.
Using form alter:
Hide the above field in the add form.
Add an entity reference render element that points to the team content type.
In the submit callback load all the team members that in the selected team and add them to the entity member field.


Because you did not save it.

Add action of Save Entity.


You need the Sub-pathauto (Sub-path URL Aliases) module for that. Here is a quote about it (from the module's project page):

The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.


You will need to create a (1) custom table in the drupal database, (2) to adopt that table using the data module and (3) to create a view with that table as base the table of your view.

1) Create your custom table by using pure SQL (the fields order matters)

DROP TABLE IF EXISTS my_custom_table;
CREATE TABLE `my_custom_table` (
`node_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'The primary identifier for a node.',
`int_field` int(10) unsigned DEFAULT NULL,
`text_field_1` varchar(255) NOT NULL DEFAULT,
`text_field_2` varchar(255) DEFAULT NULL,
`long_text_field` longtext,
`term_tid_field` int(10) unsigned NOT NULL DEFAULT '0',
`term_field` varchar(255) NOT NULL DEFAULT,
 PRIMARY KEY (`node_id`),
 KEY `text_field_1` (`text_field_1`),
 KEY `text_field_2` (`text_field_2`),
 KEY `long_text_field` (`long_text_field`),
 KEY `term_tid_field` (`term_tid_field`),
 KEY `term_field` (`term_field`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You can peek at the drupal database for more field types

1.1) Continue by adding your data into that table by using SQL again:

INSERT IGNORE INTO my_custom_table(
SELECT
 int_field,
 text_field_1,
 text_field_2,
 long_text_field,
 term_tid_field,
 term_field
FROM
// Your query
);

2) Go to the data module's admin page admin/structure/data and adopt your custom table. The module is smart enough and your table will be displayed in the list, simple adopt it.

3) Create a new view admin/structure/views/add and if everything went well your table will be in the Show list with all other available tables. You should be able to see all the fields (1:1) from your table as fields in the view.

A drawback (if it really is) by following that method is that no other fields are available, like node fields, taxonomy, users etc, just yours. The same goes for contextual filters handlers, filters criteria handlers and relationships. That's all.


Taxonomy terms not mapping in D6>D7 migrate_d2d node migration

I was not properly implementing the prepareRow() method, missing this part:

if (parent::prepareRow($row) === FALSE) {
  return FALSE;
}


Getting password hashes and salts from Drupal 7

The password hashes & salts are stored in the pass column in the users table with the first 4 bytes being settings, the next 8 bytes being the salt, and the remaining the password. See the user_hash_password() &  _password_generate_salt() docs for how salts are generated.


How to generate an unique code for every node

With some PHP knowledge, you can implemented the field using the Computed Field module. You can also use the module Universally Unique IDentifier. This does not require PHP knowledge, but does not store the code as a CCK field.


Get value of programmatically (form_alter) added fields at form submit

A field added in the form_alter hook is not created on the entity. Therefore you cannot retrieve the value in either hook_entity_presave or hook_entity_insert.

What you want however you can do by creating an additional submit handler for the form.

function _MODULE_NAME_custom_submit_handler($form, FormStateInterface $form_state) {
  $email = $form_state->getValue('email_field_name');
  // send email.
}

You can also get the saved entity (which does not have the email field) using $form_state->getFormObject();


Issues with Composer at module dependencies

The error message could make you think there isn't any stable release of the module, but since there is a 8.x-3.1 version, that is not the case.

The possible causes are:

composer.phar require drupal/currency is not executed from the directory containing the composer.json file you are using, or the one Drupal comes with
The composer.json file doesn't list as repository the one having drupal/currency as package
The repository listed from the composer.json file as the one containing the drupal/currency package is the wrong one
The composer.json file is referring, in the repositories section, a server that is not anymore active, or where the packagist service has been disabled

Keep in mind that Composer, by default, looks at the packages in https://packagist.org. That is why the composer.json file that comes with Drupal 8.4 contains the following lines.

"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
]

If you were using https://packages.drupal.org/7 for Drupal 8, you would get the wrong modules. If you are using https://packagist.drupal-composer.org, that repository is not anymore working.

Keep also in mind that, if you were previously using https://packagist.drupal-composer.org, and you passed to https://packages.drupal.org/8, the package versions need to be accordingly changed; for example, using https://packages.drupal.org/8, composer require honeypot:1.27 is requiring version 8.x-1.27 of the Honeypot module.


Display menu items of unpublished nodes to users without "Administer Content" permission

I ended up using a module called Menu view unpublished which is a ...

Small module that allows users to view menu links to unpublished nodes.
The menu system from Drupal core hides menu links that link to nodes
that are unpublished. This modules provides a permission that undoes
this behavior, but only if the user has access to view the
(unpublished) node.


Inject service(s) into Drupal unit test?

If your new service is sufficiently independent (it doesn't have any or many of it own dependencies), then just create it the setUp().  And then if you have dependencies, you set up mocks (also called doubles).

An example of a this in core is TimeTest::setUp() does:

protected function setUp() {
  parent::setUp();

  $this->requestStack = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestStack')->getMock();
  $this->time = new Time($this->requestStack);
}

A mocked request stack is created, and the setup then directly instantiates the service class being tested (Time() in this case), passing in the mocked dependency to the constructor.

Then assertions in test methods are pretty simple

public function testGetRequestTime() {
  $expected = 12345678;

  $request = Request::createFromGlobals();
  $request->server->set('REQUEST_TIME', $expected);

  // Mocks a the request stack getting the current request.
  $this->requestStack->expects($this->any())
    ->method('getCurrentRequest')
    ->willReturn($request);

  $this->assertEquals($expected, $this->time->getRequestTime());
}

The mock simulates what the service's dependency would do, and then the service method is invoked directly.

If your service has a lot of dependencies, or mocking them is hard, then you should do a KernelTest instead of a TestCase or UnitTest.  However, that may be an indication that your service is too complicated and needs to be broken up (I am also having a problem thinking of a core service that is kernel tested and not unit tested).


The most obvious thing is that it does not follow Drupal's coding standards at all. It makes it very difficult to read.

hook_init() is it's own hook, it should not be used as an access callbacks. Access callbacks need to return either TRUE or FALSE.


Image slider in content type based on selected images from another node (same content type)

I presume that the "We also Recommend" is manually entered by the user and that you are not using any specific logic to do it.

If that is the case then your approach would be to add an entity reference field in the content type and reference the nodes you want from there.

Once you have that setup you can create a view to get the images from the nodes related the current view using relationship.

If you don't want to add the recommendations manually the you can use taxonomy to categories the contents and then display the images from the nodes tagged with the came taxonomy term.


Show a block on the front page, but only on the first page

Install and enable request_data_conditions module

Then on the configuration of your block add following settings

Pages as <front>
URL query parameters set

page as must not be set
page as  must equal  0
uncheck require all


How do i check the duplicate entry in the table?

One way of doing that is using the hook_form_alter and add the custom validation function, and in that custom validation you can check if the enterd email already exists in the database than set error, somewhat like below:

/**
 * Implements hook_form_alter.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check the form id of your form.
  if ($form_id === 'YOUR_FORM_ID_WHICH_YOU_WANT_TO_EDIT') {
    $form['#validate'][] = 'check_email_address_exists';
  }
}

function check_email_address_exists(&$form, &$form_state) {
  // Get the value of email field. if you are under than use: "dpm($form_state['values'])"
  $email_entered = $form_state['values']['EMAIL_FIELD_NAME'];

  // Generate the query somewhat like below, For Example I am using users table's "uid".
  $query = db_select('users', 'u');
  $query->fields('u', array('uid'));
  $query->condition('u.mail', $email_entered);

  // This will return the count of the fields found.
  $row_count = $query->countQuery()->execute()->fetchField();

  if (isset($row_count) && ($row_count > 0)) {
    form_set_error('EMAIL_ADDRESS_FIELD_NAME', t('This email already exists, please try with another email  address!'));
  }
}

In order it to work you have to change the values as per you requirement, and don't forget to modify the db_select query as per your requirement, and last CLEAR THE CACHE after implementing the same.


Geocoder not working with “Geocode from another field”

The issue can be solved by installing the other version of geofield module Geofield 7.x-2.0-beta1 (don't use the 7.x-2.x-dev version).


What is the template suggestion for node 'teaser' view mode?

I don't think there is one by default but you can easily add one in your template.php file:

function MYTHEME_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__teaser';
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->nid . '__teaser';
  }
}

That will let you use a template file like: node--[type|nodeid]--teaser.tpl.php


How to get the nodeid in node_grants so that it works in a view?

You actually need to implement two hooks:

hook_node_grants() which returns the grants a user has
hook_node_access_records() which returns the grants a node needs

It's the second hook that gets a node object, not the first. Keep in mind that you need to implement both the hooks.

As for hook_node_access(), this hook is called when a node is fully loaded, and it not called for node listings, as reported in the documentation.

  Also note that this function isn't called for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.) See Node access rights for a full explanation.

As for views, a view doesn't full load a node, but executes a SQL query to get node data. merlinofchaos clearly states it in Views does not respect hook_node_access.

  hook_node_access() is something that is run after a node is fully loaded. Since Views is loading nodes via query, you can't get the query to respect it unless you also use hook_db_rewrite_sql() which is what Views hooks into.

  This is not true of just Views, but any query that loads nodes. For example, the default Drupal front page will not respect hook_node_access() that isn't paired with hook_db_rewrite_sql() any better.

  hook_node_grants() and hook_node_access_records() will be used, however, if you set "Disable SQL rewriting" then you are specifically skipping that stuff.

Notice that hook_db_rewrite_sql() is not used from Drupal 7 and higher, though. The equivalent for Drupal 7 and higher is hook_query_alter().


If I haven't misunderstood your question and you're using Views, you could simply sort the view by your weight_field and then just assign the right weight parameter to the user.

If you prefer some kind of drag and drop functionality (which in my opinion is easier to manage than weight) you could use Draggable Views, this module will allow you to have a view where you can order your users display, a good tutorial I used as a first timer is this.


This is pretty much what hook_library is for.  You define your library

function mymodule_library ()
{
    $path = drupal_get_path("module", "mymodule");

    $libraries = array();

    $libraries["mymodule_util"] = array(
        "title" => "MyModule Utilities",
        "version" => "0.0",
        "js" => array(
            $path . '/UTIL.js' => array(),
        ),

        'weight' => -10,
    );

    return $libraries;
}

You can add CSS and declare dependencies, if needed.

Then you say you want to use it

drupal_add_library("mymodule", "mymodule_util", TRUE);

This ensures all of the dependencies get loaded exactly once.

Check out drupal_add_library for more details.  The core jQuery UI components are loaded this way, too.  The module is system and the names all begin with ui., eg ui.scroller.

I would also check out jQuery Update to upgrade things so you stay in sync with that other jQuery plugins need.


The problem here was due to Drupal failing silently (or obfuscating the error - maybe because I was running this in cron) but it was due to the address not having all of the required fields set to the correct values for the country in question - mainly using the actual country name instead of the country code.

Once the country code was swapped in it worked. I switched the country around to the country code like this:

function MY_MODULE_get_country_code($country) {
  $countries = MY_MODULE_country_list();
  $flipped_countries = array_flip($countries);
  $country_code = $flipped_countries[$country];
  return $country_code;
}

function MY_MODULE_country_list() {
  $countries = \Drupal\Core\Locale\CountryManager::getStandardList();
  foreach ($countries as $key => $value) {
    $countries[$key] = $value->__toString();
  }
  return $countries;
}

It worked correctly.


Configure web.config to redirect non-www requests to www for multi-site Drupal 7 Install

Some subtle differences between this and the rule above, but this officially works for my multi-site Drupal install on Azure IIS.

<rule name="WWW Rewrite" enabled="true">
          <match url="(.*)" />
            <conditions>
                <add input="{HTTP_HOST}" negate="true" pattern="^www\.(.*)$" />
            </conditions>
            <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" appendQueryString="true" redirectType="Permanent" />
</rule>


If you use print render($content); and your code is displayed as it is on an Informational page ("echo 'test';") you should check PHP code configuration page (?q=admin/config/content/formats/php_code).
Here you set the roles who can use this text filter (by default is the 'administrator') and you enable or disable PHP code evaluator. Ensure that 'PHP evaluator' checkbox is on.
I hope this will help you.


Is there a way to hide images from the media library?

Yes, in version 2.x of the media module the media browser is implemented as a view. This is the key to doing any sort of customisation to the browser. You should be able to see it in admin/structure/views and override it as you would with any other view.

The media browser view uses files as it's base type. It has some existing filters for filename, type etc. You can add another one that filters by path. If you use the starts with operator and value public://foo/. That will end up doing a SQL LIKE query on the uri column of the file_managed table, which should give you what you want.

It's worth noting that you can customise the media browser only for certain file fields. To do that, clone the view instead of overriding it, thereby giving you two media browsers. Then for each field that uses a media widget, you need to choose which browser(s) you want.


How to get the JSON/array value property name for a field instance?

I just tested using a variety of field types, and it seems to work OK for me. Here's the code I used for testing:

$node = \Drupal\node\Entity\Node::load($nid);

print $node->get('field_test')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
print $node->get('field_test_image')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
print $node->get('field_test_link')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
print $node->get('field_test_email')->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();

This returns value, target_id, uri and value as one would have expected. What kind of fields are giving you trouble? How do you get you BaseFieldDefinition class? What kind of entity are they connected to?

I notice that the Views way of getting the property name is also pretty pragmatic:

// EntityField.php line 1111
if ($main_property_name = $field_item->mainPropertyName()) {
  $values[] = $field_item->{$main_property_name};
}
else {
  $values[] = $field_item->value;
}

Clearly it's not completely unexpected to have this method return null.


Drupal Registration Module Email Registrants tab

Not being a developer I had to figure this out using hook_form_alter. Too some digging and a little help.

function ecg_registration_form_registration_registrations_broadcast_form_alter(&$form, &$form_state) {
  //dpm($form);
  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#description' => t('The subject of the message.'),
    '#required' => TRUE,
    '#size' => 80,
    '#maxlength' => 80,
  );
}

Hope that helps someone.


Is it necessary to "activate" a file input field after a jQuery insertion?

False alarm -- a bit more hacking showed that I was putting the field into a part of the page where it didn't want to be.  Why this resulted in the "Browse..." button not working is still a mystery, but all is currently well.


What may cause duplicate nodes to be created using a Rules action to Create New Entity?

According to the current status of issue # 2783453 (which IMO should be a support request), this looks like something else is happening in your site.

Something that will help you find the answer to your question, is to have a look at Rules debugging ... Within the Rules settings, experiment a bit with the debugging facilities that come with Rules. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

For way more details about Rules debugging, refer to the answer to "How can I display the value of a variable inside a condition?".


After logging off, user is able to see the workbench page by pressing back button of the browser

Used this in custom module and it works

<?php
/**
 *Implements hook_init().
 */
function MY_MODULE_init() {
  drupal_add_http_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, post-check=0, pre-check=0');
}


Livereload will only be added to the page if the Drupal instance can reach out to the livereload.js specified.  Note that loading it in your browser (remotely from the server) is different than Drupal loading it from the machine.  Drupal is running under Apache as a process on the machine.  What it sounds like is Drupal/Apache/PHP cannot access the settings you have in Omega.

If you are familiar with Linux command line.  Log into the machine and attempt to load the livereload.js file using wget from the machine using the exact URL you are using in Omega. If you do not get a return, you have found the problem.


What is the equivalent of hook_translated_menu_link_alter() to alter a menu link?

HOOK_link_alter would be one D8 equivalent to hook_translated_menu_link_alter:

/**
 * Implements hook_link_alter().
 *
 * @inheritdoc
 */
function HOOK_link_alter(&$variables) {
  $url = $variables['url'];
  // Check url is routed in Drupal.
  if ($url->isRouted()) {
    // Load the current user by user ID.
    $currentUser = User::load(\Drupal::currentUser()->id());
    // Check access.
    $urlAccess = $url->access();
    // Get url options.
    $urlOptions = $url->getOptions();
    // Your code here.
  }
}

See Drupal 8 class URL for more API info.

However, you could use Hook_preprocess_HOOK() as such:

/**
 * Implements hook_preprocess_hook().
 *
 * @inheritdoc
 */
function HOOK_preprocess_menu(&$variables) {
  if (isset($variables['menu_name']) && $variables['menu_name'] === 'menu_name') {
    foreach($variables['items'] as $key => $item) {
      $url = $item['url']->toString();
      if ($url == '/user') {
        // Remove menu item.
        unset($variables['items'][$key]);
      }
    }
  }
}

Just checking path above, but it shows you can hide a single menu item based on certain criteria.

For the access restrictions, depending on your needs, you might look at routing and permissions based on the entity instead of the menu item and let Drupal handle the menu item display.

For menu access by role look at this module: https://www.drupal.org/project/menu_item_role_access


Sounds like you want drupal-console.  This tool can quickly create working Drupal 8 sites interactively or via command line. More info here.

Another quick alternative is to use DrupalVM and Varnish to spin up a fully working D8 site.  The DrupalVM defaults are to create a D8 sandbox site.

I believe that DrupalVM now has Docker support so you might be able to have a single VM and just spin up a new D8 box.


Views: show nodes that share taxonomy term with user

Create a view showing requests.
Add a contextual filter for Field: Category.
When the filter value is NOT in the URL choose "Provide default value" of type PHP.
In the "PHP contextual filter code" write:

global $user;
$account = user_load($user->uid);
return $account->field_category['und'][0]['tid']; // this line may need changing based on your category field name


How do I group and add space between checkboxes?

You can normally do this already without any extra effort.

Each option should have a class assigned to it that you can target in your CSS.

You can then apply any spacing you like there.


For the first site:

drush qd --sites-subdir=<directory name>

For each successive site:

cd DRUPAL_ROOT_CREATED_ABOVE
drush qd --use-existing --sites-subdir=<directory name>

These will create sqlite databases.  Add --db-url with valid database credentials to use a pre-existing database.  Also add --db-su and --db-su-pw to make Drush create the database for you.

Haven't tried some of the steps in this workflow in a while; report any problems back in the Drush issue queue.  Also, you might want to use drush master instead of 6.x.  There's a issue in the queue that hasn't landed yet that makes drush qd better.

UPDATE: Drush quick-drupal does not appear to be well suited for multisite usage.  For subsiquent sites, call drush site-install with --sites-subdir and --db-url options.  See drush help si for more information on options that may be useful here.

For example

drush si --sites-subdir=<folder> --db-url=mysql://db_user:str0n6passw0rd@localhost/db_name


Drupal 7, Custom Content Type... Does an addon that does this exist?

The obvious choice for that functionality would be the conditional fields module. It's still under development for D7, but you can check if it already supports your use case, or maybe you could even help the maintainer get the D7 version to a stable state.


How to display a contact form as a node block?

For non coding solution, you can go with

Create the form using Webform and utilizing Webform Blocks and Token

  Webform is the module for making forms and surveys in Drupal. After a submission customizable e-mails can be sent to administrators and/or submitters. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has an extensive API for expanding its features.

Form Block

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

Worth mentioning, just might not do for this question's specific use case.

Do it programmatically by creating a custom block and fetching the form, you can find an example here Problems to integrate a form into a block


Can I upgrade from Drupal 7.10 directly to Drupal 7.12

You can update directly to 7.12 without any problems. Drupal 7.11 contains security fixes while 7.12 contains bug fixes. Updating to 7.12 would also add the security fixes from 7.11.


Show the first 4 items in a different format

You can use views attachment to have a different styles for the first few item in list. By default, the attachment will be displayed in every pages of list.

If you want to limit the attachment works on the first page only, please implement hook_views_pre_build() in your custom module.

Assuming views name is stories, main display ID is block_1 and attachment display ID is attachment_1.

/**
 * Implements hook_views_pre_build().
 */
function mymodule_views_pre_build(&$views) {
  if($views->name == 'stories' && $views->current_display == 'block_1') {

    // if 'page' is not defined, we assume it is the first page.
    if (empty($_GET['page'])) {

      // The offset number y should be equal to the number of items on
      // attachment. If we want to keep the total n items on list, the
      // number of items on main display should be (n - y).
      // Note: get_items_per_page() and get_offset() is not working here.
      $views->set_items_per_page(6);
    }
    else {

      // Remove attachment for other pages.
      $views->is_attachment = TRUE;

      // We don't need to handle the offset anymore.
      $views->set_offset(0);
    }
  }

  // We set the item number again because the it seems
  // be overrided by previous call of set_items_per_page().
  if($views->name == 'stories' && $views->current_display == 'attachment_1') {
    $views->set_items_per_page(4);
  }
}

Below is the steps of using views attachment

Add attachment display

In the attachment display, you need to specify how many items you want to have.

Then you need to attach the attachment display to the main display.

Remember to set the  offset in main display for preventing repeating the item in list.


A Drupal menu item can point to external URLs, URLs to files in the filesystem or an internal path. The latter has to exist before creating the menu item and access permissions are needed for the user creating it.

A path can point to a node or any other entity, or any path provided by a module (e.g a view from the Views module). Virtually any path can have any number of aliases but it's worth using the path in the menu items as aliases may change throughout the lifetime of the site, paths are less likely to change.


How to fetch the completed goal as an entity with the Rules module?

You could use the Views Rules to get this to work. Read on for more details about how to do so ...

Step 1: Create an appropriate view

Create a view of all goals completed by the current user, sorted (descending) by the date the goal was completed, and a "Rules" display type, in which you use a pager to only show 1 result (i.e. the most recent one ...).

Here is a view (in export format) with (a) a page display (to list all goals completed by the current user) and (b) a Rules display (to only list the most recent completed goal):

$view = new view();
$view->name = 'goals_info_about_completed_goals';
$view->description = 'A list of goals completed by a user.';
$view->tag = 'Goals';
$view->base_table = 'goals';
$view->human_name = 'Goals completed by a user';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Goals completed by a user';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'goal_img' => 'goal_img',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'goal_img' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Goal: Goal - completed by users */
$handler->display->display_options['relationships']['goals_completed_goals']['id'] = 'goals_completed_goals';
$handler->display->display_options['relationships']['goals_completed_goals']['table'] = 'goals';
$handler->display->display_options['relationships']['goals_completed_goals']['field'] = 'goals_completed_goals';
$handler->display->display_options['relationships']['goals_completed_goals']['label'] = 'Completed goal';
/* Field: Goal: Goal Image */
$handler->display->display_options['fields']['goal_img']['id'] = 'goal_img';
$handler->display->display_options['fields']['goal_img']['table'] = 'field_data_goal_img';
$handler->display->display_options['fields']['goal_img']['field'] = 'goal_img';
$handler->display->display_options['fields']['goal_img']['label'] = 'Goal image';
$handler->display->display_options['fields']['goal_img']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['goal_img']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['goal_img']['settings'] = array(
  'image_style' => 'goal_image',
  'image_link' => '',
);
/* Field: Goal: URL */
$handler->display->display_options['fields']['url']['id'] = 'url';
$handler->display->display_options['fields']['url']['table'] = 'views_entity_goal';
$handler->display->display_options['fields']['url']['field'] = 'url';
$handler->display->display_options['fields']['url']['exclude'] = TRUE;
$handler->display->display_options['fields']['url']['link_to_entity'] = 0;
/* Field: Goal: Title */
$handler->display->display_options['fields']['title_1']['id'] = 'title_1';
$handler->display->display_options['fields']['title_1']['table'] = 'goals';
$handler->display->display_options['fields']['title_1']['field'] = 'title';
$handler->display->display_options['fields']['title_1']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['title_1']['alter']['path'] = '[url]';
/* Field: Goal: Goal ID */
$handler->display->display_options['fields']['goal_id']['id'] = 'goal_id';
$handler->display->display_options['fields']['goal_id']['table'] = 'goals';
$handler->display->display_options['fields']['goal_id']['field'] = 'goal_id';
/* Field: Goal: User Points */
$handler->display->display_options['fields']['goal_userpoints']['id'] = 'goal_userpoints';
$handler->display->display_options['fields']['goal_userpoints']['table'] = 'field_data_goal_userpoints';
$handler->display->display_options['fields']['goal_userpoints']['field'] = 'goal_userpoints';
$handler->display->display_options['fields']['goal_userpoints']['settings'] = array(
  'thousand_separator' => '',
  'prefix_suffix' => 1,
);
/* Field: Goal: Goal Category */
$handler->display->display_options['fields']['field_goal_category']['id'] = 'field_goal_category';
$handler->display->display_options['fields']['field_goal_category']['table'] = 'field_data_field_goal_category';
$handler->display->display_options['fields']['field_goal_category']['field'] = 'field_goal_category';
/* Field: Goal: Goal Level */
$handler->display->display_options['fields']['field_goal_level']['id'] = 'field_goal_level';
$handler->display->display_options['fields']['field_goal_level']['table'] = 'field_data_field_goal_level';
$handler->display->display_options['fields']['field_goal_level']['field'] = 'field_goal_level';
/* Field: Goal - completed by users: Created */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'goals_completed_goals';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['relationship'] = 'goals_completed_goals';
$handler->display->display_options['fields']['created']['label'] = 'Completion date';
$handler->display->display_options['fields']['created']['date_format'] = 'short';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Field: Goal - completed by users: User */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'goals_completed_goals';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['relationship'] = 'goals_completed_goals';
/* Field: Goal - completed by users: Goal */
$handler->display->display_options['fields']['goal_id_1']['id'] = 'goal_id_1';
$handler->display->display_options['fields']['goal_id_1']['table'] = 'goals_completed_goals';
$handler->display->display_options['fields']['goal_id_1']['field'] = 'goal_id';
$handler->display->display_options['fields']['goal_id_1']['relationship'] = 'goals_completed_goals';
/* Field: Goal - completed by users: Goal - completed by users ID */
$handler->display->display_options['fields']['id']['id'] = 'id';
$handler->display->display_options['fields']['id']['table'] = 'goals_completed_goals';
$handler->display->display_options['fields']['id']['field'] = 'id';
$handler->display->display_options['fields']['id']['relationship'] = 'goals_completed_goals';
$handler->display->display_options['fields']['id']['label'] = 'Completed Goal Seqnr';
/* Sort criterion: Goal - completed by users: Created */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'goals_completed_goals';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['relationship'] = 'goals_completed_goals';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Goal - completed by users: User */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'goals_completed_goals';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'goals_completed_goals';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'user/%/completed-goals';

/* Display: RulesList */
$handler = $view->new_display('views_rules', 'RulesList', 'views_rules_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Goal: URL */
$handler->display->display_options['fields']['url']['id'] = 'url';
$handler->display->display_options['fields']['url']['table'] = 'views_entity_goal';
$handler->display->display_options['fields']['url']['field'] = 'url';
$handler->display->display_options['fields']['url']['exclude'] = TRUE;
$handler->display->display_options['fields']['url']['link_to_entity'] = 0;
/* Field: Goal: Title */
$handler->display->display_options['fields']['title_1']['id'] = 'title_1';
$handler->display->display_options['fields']['title_1']['table'] = 'goals';
$handler->display->display_options['fields']['title_1']['field'] = 'title';
$handler->display->display_options['fields']['title_1']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['title_1']['alter']['path'] = '[url]';
/* Field: Goal: Goal ID */
$handler->display->display_options['fields']['goal_id']['id'] = 'goal_id';
$handler->display->display_options['fields']['goal_id']['table'] = 'goals';
$handler->display->display_options['fields']['goal_id']['field'] = 'goal_id';
$handler->display->display_options['rules_parameter'] = array(
  'uid' => array(
    'enabled' => 1,
    'type' => 'integer',
    'label' => 'Goal completed by user with id',
    'name' => 'goal_completed_by_uid',
  ),
);
$handler->display->display_options['rules_variables'] = array(
  'url' => array(
    'enabled' => 0,
    'rendered' => 0,
    'type' => '',
    'label' => 'URL',
    'name' => 'url',
  ),
  'title_1' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => 'Title',
    'name' => 'goal_title',
  ),
  'goal_id' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'integer',
    'label' => 'Goal ID',
    'name' => 'goal_id',
  ),
  'field_goal_category' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => 'Goal Category',
    'name' => 'goal_category',
  ),
  'field_goal_level' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => 'Goal Level',
    'name' => 'goal_level',
  ),
  'goal_userpoints' => array(
    'enabled' => 0,
    'rendered' => 0,
    'type' => '',
    'label' => 'User Points',
    'name' => 'goal_userpoints',
  ),
  'uid' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'integer',
    'label' => 'Id of User completing goal',
    'name' => 'goal_uid',
  ),
);

Before trying to import the above view in your own site, make sure to define these custom fields for the goals you configured (these fields are select lists with a single value allowed):

Goal Category (machine name field_goal_category), eg with values such as "Privilege, Contribution, Participation, Moderation, None".
Goal Level (machine name field_goal_level), eg with values such as "Bronze, Silver, Gold, None".

Step 2: Create a rule that contains a Views loop

Create a rule which contains a "Views loop" as a Rules Action, which is similar to a regular Rules loop, but allows looping over rows of view results. Use the Rules Display type of the view created in the previous step. Obviously, because of the number of results we configured in the Rules display of the view, this list consists of only 1 list item (i.e. related to the most recently completed goal).

Within that "Views loop", perform a 1st Rules Action to "Fetch an entity by id", and with these additional details:

Parameter: Entity type: Goal
Identifier: [goal-id]
Provides variables: Completed goal (goal_completed)

Then add a 2nd Rules Action, within that same "Views loop", something like "Show a message on the site", with a message that looks something like so (note the 2 custom fields included, with machine names field_goal_category and  field_goal_level):

  Details about completed goal:

  Goal ID: [goal-completed:goal-id]
  Goal Title: [goal-completed:title]
  Goal Category: [goal-completed:field_goal_category]
  Goal Level: [goal-completed:field_goal_level]

Here is an export of a rule you can use for this (if you have both custom fields defined, you should be able to import this rule in your own site):

{ "rules_show_details_about_completed_goal" : {
    "LABEL" : "Show details about completed goal",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "rules", "goals" ],
    "ON" : { "goal_awarded" : [] },
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "goals_info_about_completed_goals",
          "DISPLAY" : "views_rules_1",
          "USING" : { "goal_completed_by_uid" : [ "awarded-user:uid" ] },
          "ROW VARIABLES" : {
            "goal_title" : { "goal_title" : "Title" },
            "goal_id" : { "goal_id" : "Goal ID" }
          },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "goal", "id" : [ "goal-id" ] },
                "PROVIDE" : { "entity_fetched" : { "goal_completed" : "Completed goal" } }
              }
            },
            { "drupal_message" : { "message" : "Details about completed goal:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- Goal ID: [goal-completed:goal-id]\u003Cbr \/\u003E\r\n- Goal Title: [goal-completed:title]\u003Cbr \/\u003E\r\n- Goal Category: [goal-completed:field_goal_category]\u003Cbr \/\u003E\r\n- Goal Level: [goal-completed:field_goal_level]\u003Cbr \/\u003E" } }
          ]
        }
      }
    ]
  }
}

Here are the "Replacement patterns for Completed goal" that are shown with the Rules Action to Show a message on the site:

[goal-completed:title]                  Title               Goal "title" property.
[goal-completed:created]                Created             The date the goal was created.
[goal-completed:changed]                Changed             The date the goal was changed.
[goal-completed:Goal ID]                Label               The human readable label.
[goal-completed:url]                    URL                 The URL of the entity.
[goal-completed:field-goal-description] Goal Description    Field "field_goal_description".
[goal-completed:goal-userpoints]        User Points         Field "goal_userpoints".
[goal-completed:goal-img]               Goal Image          Field "goal_img". The following properties may be appended to the token: file (The image file.)
[goal-completed:field-goal-category]    Goal Category       Field "field_goal_category".
[goal-completed:field-goal-level]       Goal Level          Field "field_goal_level".
[goal-completed:field_goal_description] Goal Description    Long text field.
[goal-completed:goal_userpoints]        User Points         Integer field.
[goal-completed:goal_img]               Goal Image          Image field.
[goal-completed:field_goal_category]    Goal Category       List (text) field.
[goal-completed:field_goal_level]       Goal Level          List (text) field.

Obviously, these Replacement patterns have been made available via the Rules Action "Fetch entity by Id" that precedes it. And with that, you have anything available to "find and use the fields of the goal that triggered the goal completed event" (as in your question).

Step 3: Demo

Here is an example of a message shown to a user, after the user completes some goal (if the above view and rule is enabled):

  Details about completed goal:

  Goal ID: 11
  Goal Title: Citizen Patrol
  Goal Category: Moderation
  Goal Level: Bronze

Note: For way more details on using Views Rules, refer to ("Option 2" of) my answer to "How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?".

PS: this answer applies to D7 ...


Is Display Suite compatible with Panels?

They are compatible in the sense that you can use Panel layouts on DS. (See picture below)

You can use DS for one content type and Panels for another content type. Not sure who would win if I enabled both for the same content type, but why would anyone do that?

Where it's not compatible is with mini panels, unfortunately you can't insert mini panels into a custom DS dynamic field.


Parent term doesn't show child term entities

I was able to solve it, although there may be a more elegant solution. I had to use two additional modules: Views arg parent term and Views Contextual Filters OR. There are a lot of LEFT JOINs so it's not very performance friendly.

The problem actually lies in listing the children terms (Yonkers, Albany, etc) of the term page you're currently viewing (Newyork), along with the term of the page itself (Newyork). Once you solve that it's simple to pull information about the terms from School term vocabulary that reference your City terms (through a Relationship).

List the term and its children on the term page

Start with Taxonomy Term View type (Block Display), filter to list only City vocabulary. Add Fields for Term ID or Term name to display Cities just to test that all are there (you should see all Cities listed).

You can add the relevant School terms (that reference the term listed) although it's not yet necessary, we can take care of it when we get the correct contextual filtering.
Add a Contextual filter Term ID from Taxonomy term Category, and configure it with these options:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from term page
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term
City
Filter value type: Term ID

You can now test this filter by entering a City term ID into the Preview field, it should limit the results list to show only that City views row. (You can see all of the results by entering all into Preview.)
To list child City terms add a Relationship Parent term from Taxonomy term Category, don't require it or it will limit the results beyond what is useful to this case
Add another Contextual filter Term ID from Taxonomy term Category, make it use the Parent Relationship from the previous step and configure it similarly to the last one, only change one option: filter Type:
Taxonomy parent term ID from URL
Under Views Query settings tick Contextual filters OR, best to apply it only to this Block so it doesn't interfere with your other Displays if you have them.

This will make all Contextual filters work with an OR operator instead of AND. In your case it will allow Views to filter by term ID of the page you're viewing OR it's child, so both options will be valid.

You can now enter a city term ID twice into Preview and you'll see both that term and its children. For example, let's say your Newyork term ID is 18, if you enter 18/18 into Preview you'll see all the terms from your City vocabulary.

Show which terms reference the ones listed
To show the School terms that reference City terms add a Relationship Taxonomy term using City. You can require it, this will exclude all City terms from the list that aren't referenced by any School terms. Since it's a School terms list we want in the end it doesn't make sense to allow any "empty" rows.
Add a Field Taxonomy term: Name and make it use the Relationship from the previous step (field_city).

You can now see the relevant School terms in your results! You can now remove the City TID and Name fields, if you don't need them for the testing, so you only end up with School terms.
Place the Block on your City term pages and it will list School terms that reference that term or its children. You'll probably only want to place it on first level term pages (Newyork) because it doesn't work in reverse, it won't display parent terms when you're viewing child term pages, it will only list their own related ones.

Add the third Taxonomy level
Just in case someone needs it, if the Vocabulary has the third level, to show grandchildren on parent pages you have to add another Relationship Parent term, make it use the earlier Parent Relationship, don't require it.
Add another Term ID Contextual filter and configure it like the second one, with Taxonomy **parent** term ID from URL, only make it use the second Parent Relationship.

You'll now have to enter the parent TID thrice to make the Preview work 18/18/18. (This doesn't affect the Block, arguments are handled automatically.)


You can add to your page something like

<script>
(function ($, Drupal, window, document, undefined) {
  $(document).ready(function() {
    $('.form-radio').click(function() { $('#edit-next').click(); });
  });
})(jQuery, Drupal, this, this.document);
</script>

This is better done by adding a .js file via drupal_add_js(). Be aware that, since you are forcing your user to submit a form, you should provide a way to get back and resubmit a different choice.


Taxonomy term empty fields in a ALL vocabulary

It's an issue caused by the Commerce Services module version 7.x-1.x-dev (25-Apr-2014): https://www.drupal.org/node/2024813


How to hide options in the second select before choosing option in first select

If I am not mistaken, you want to show in the second filter only the towns (villages) related to the selected city (ville) in the first filter. That means, the content of the second filter depends on the selection in the first filter. Am I right?

In that case, you might try something like the Views Dependent Filters module. See below its description:

  Suppose you had a view showing several kinds of products, such as
  cake, bicycles, and books, and an exposed filter on product type that
  lets the user refine the listing to one or more types.

  With this module you could add the following filters:

cake flavour, such as lemon, chocolate, coffee
bicycle size
book genre

  Each filter will only show when the type it relates to is selected in
  the filter for product type.


Print something in a tlp file if a field isnt empty

Try this code:

<?php
  if ($content['field_hotel_sat_nav'] != '') {

    //Do something

  }
?>


you can use array in static block(created through admin panel) also by choosing text format to "php Code". What exactly, you want to achieve ?


Save certain registration fields elsewhere in database

Wow. I puzzled on this all day and 30 minutes after asking this question, of course I find the answer.

Since the $form['submit'] part is an array, you can have more than one handler there! I changed the lines

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'New Submit Button',
    '#submit' => array('my_module_form_submit'),
);
unset($form['actions']);

to simply be

$form['#submit'][] = 'my_module_form_submit';

and that's it! Now it does the regular registration submission handler and also mine.

Thanks!


Load certain modules only if user is administrator

Modules are either enabled or disabled in Drupal. They then may use access control to determine whether the user has access to them.

If these are custom modules, you may wish to write them so that either the heavy processing is skipped for non-admins, or that the data is cached to avoid calculations on every page load.


You'll want to use the file_view_file() function provided by the File entity module. The function has three parameters: a file object, the name of a view mode (or an array of custom display settings) and optionally a language code.

If you only have a file ID then you can do a file_load on the ID to get a full file object to pass to the function.

Note that file_view_file() returns a array as expected by drupal_render() so, depending on how you are incorporating the file into your template, you may have to render the returned array using render().


Paid membership plans on registration page

For membership process you can use the (paid for) Moneyscripts module.

  Membership Suite is the most comprehensive subscription software for
  Drupal on the market and it is designed to seamlessly integrate your
  site with all of the features of a professional Paid Membership
  Subscription site. There is no other software available for Drupal
  that can provide the stability, ease of use, and features that
  Membership Suite offers.


dynamic options list based on the previous select box value


How do I pass a checkbox value to a Webform through URL?

Webform provides this functionality by itself.

Define in your checkbox field a default value:

%get[customkey]

The url will be:

http://example.com/node/1?customkey=one,two


Where do I put configuration files for testing?

One way is to create a small testing module that contains specific config you need for a test, then have the test use it as a dependency. In my case, I put that module itself under the tests directory and marked it as hidden in its info file.

Although a drawback would be keeping these config files up to date when the system changes - but failing tests should point you in that direction too.

For Kernel tests be sure to call and install the test modules config.


Is there a way to display the product image as a radio button instead of a select box when selecting a product in a product display?

You could do this through jQuery easily. All you do is add your own jQuery file through your theme info file:

https://drupal.org/node/171213

Then write some jQuery that adds a css class to the label when the page loads up and handles the clicking of the checkboxes/radios like:

(window).load(function() {
var myImageButton1_label = $('#some_drupal_label_ID');
var myImageButton1 = $('#some_drupal_checkbox_ID');
myImageButton1_label.addClass("button1_off");
myImageButton1.attr({'checked' : false});

myImageButton1_label.click(function(event){

if (myImageButton1.attr({'checked' : true})) {
myImageButton1_label.removeClass("button1_on").addClass("button1_off");
myImageButton1.attr({'checked' : false});
}

else {
myImageButton1_label.removeClass("button1_off").addClass("button1_on");
myImageButton1.attr({'checked' : true});
 }

});

Then hide the actual radio button with CSS and style your label to be an image. Then jQuery will handle the switching of classes and checking those radio buttons for you. Note this is a simplified example so you'll need to expand upon this for your needs. This an older article, but appears to be relevant: http://tutorialzine.com/2011/03/better-check-boxes-jquery-css/


I've always handled changing form values in the form build or form_alter function itself. I can't remember where I saw to do this, but I've never been able to alter the form in the ajax callback itself.

Have your form trigger an ajax callback. This should return the form or piece of the form in question, like your test_result_with_button() function.

When an ajax callback is triggered, the build method and alters are run again. Add logic in your build / form_alter to make updates to the form or form_state based on whichever action was triggered. Information about how the rebuild was triggered will be available in $form_state['triggering_element'].