A custom Field with #submit function can't pass value

For validating the content of a field there is hook_field_validate(). As example of implementation of that hook in a module, you can look at taxonomy_field_validate(), or number_field_validate().

function number_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if ($item['value'] != '') {
      if (is_numeric($instance['settings']['min']) && $item['value'] < $instance['settings']['min']) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'number_min',
          'message' => t('%name: the value may be no less than %min.', array('%name' => $instance['label'], '%min' => $instance['settings']['min'])),
        );
      }
      if (is_numeric($instance['settings']['max']) && $item['value'] > $instance['settings']['max']) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'number_max',
          'message' => t('%name: the value may be no greater than %max.', array('%name' => $instance['label'], '%max' => $instance['settings']['max'])),
        );
      }
    }
  }
}

As far as I can see, fields don't add submission buttons. That is not the purpose of fields, which is to add fields to enter data for an entity (e.g. nodes, users, taxonomy terms).

In your case, the workflow is similar to the following one:

The user enters a cell phone number
The module tells to the remote service to send a verification code to that cell phone number
The user enters the verification code
The module checks the verification code is the expected one

Such workflow can work if it is done in two steps:

When the user first enters the cell phone number, the validation hook can just send the cell phone number to the remote service. It cannot wait the user receives the verification code, and enters it.
The second time, the user edits the verification code, and the validation hook will check the verification code is the right one.

You have to see if checking the verification code can be done synchronously, or asynchronously.


How to set the value of a field "reference to a term" with the use of entity_metadata_wrapper?

Strange. This is not working:

$node_wrapper->field_sector->set($brancheid);
$node_wrapper->field_dienst->set($oplossingsid);

But this is working:

$node_wrapper->field_sector = $brancheid;
$node_wrapper->field_dienst = $oplossingsid;


Output all instances of a repeating field together

This is going to be tricky, but you will need to think through the rendering layers via twig and work inside out.

Example, if you need all field tab titles in li's, the twig for field tab title (field--field-tab-title.html.twig) should look something like this:

{% for item for items %}

{{ item }}

{% endfor %}

In your Paragraph field twig, you would put the wrappers as needed, like:

  {{ content.field_tab_title }}
  {{ content.field_tab_body }}

The same applies to Body:

{% for item for items %}

{{ item }}

{% endfor %}

Here is a similar example perhaps you can follow. This isn't tabbed content, but it is accordion based, so it is similar. Still paragraphs.

Main container (paragraph--component):

  {% block content %}
    {{ content }}
  {% endblock %}

Main accordion paragraph twig, extends the main container (paragraph--component is a custom twig suggestion I made for easier theming):

{% extends 'paragraph--component.html.twig' %}

{% set attributes = attributes.addClass('c-accordion') %}

{% block content %}
  {{ content }}
{% endblock %}

The accordion item itself, containing a title and other fields:

  <input type="checkbox" class="c-accordion__trigger visuallyhidden" id="step-{{ paragraph.id() }}" />

    {% if paragraph.field_accordion_step_title is not empty %}

{{ content.field_accordion_step_title }}

    {% endif %}

{{ content.field_accordion_title }}

{{ content.field_accordion_body }}

When this renders, all X accordion items are rendered the same way into one container. Granted, in my example, the markup container for fields live outside of the field twig and in this twig here, because I chose to have 0 field markup in that project. You can go either way you want.


View contextual filter only applies to first filter AND/OR group

Updating Drupal to 7.28 and the Views module to 7.x-3.7 solved the problem, as barraponto suggested it might.


Example:

 $theme = \Drupal::theme()->getActiveTheme();
 $form['image_div'] = array(
 '#prefix' => 'getPath() .'/images/smile.png">',
        '#suffix' => '
',
    );


Only two filters can do that for you -

Content : Published(= yes)

OR,

Content : type(= Feed) And,
Content : field_car(= BMW)

OR,

Content : type(= Post) And,
Content : field_motorcycle(= DUCATI)

Apply pager for the view with 10 or 15 content on one page, etc.


I would recommend to take advantage of jQuery over Flash. As Mohammed suggested, you could try the TinyBox module.

But, the other option is the Splashify module:

  Display a splash page anywhere on your site by redirecting the user,
  showing a lightbox, or displaying a popup. This module is designed to
  be search engine friendly, mobile device friendly and offers multiple
  configuration options.


How can I have a taxonomy list that shows parent child relationship, but not allow the parent to be selected?

Download and install this module http://drupal.org/project/term_reference_tree and
 check the Leaves only(Don't allow the user to select items that have children) option under manage fields-> click edit on taxonomy field.

It will select only the children not parent.


You'll need to use hook_form_alter in a custom module to set the options as the form is loaded.

Something like this:

function my_module_form_alter(&$form, &$form_state, $form_id) {

  switch ($form['#id']){
    case "my_form_id":

      //use db_select to get the oldest and newest years,
      //loop through them to end up with an array like this one:
      $years_array = array('2009', '2010', '2011');

      //set the options to your array of years
      $form_state['input'][my_form_input_name]['#options'] =  $years_array;
      break;
  }
}


What is your way to add images into panels - simple and fast?

Using CKEditor with CKFinder:

On pane gear menu click add content
Choose 'New custom content'
In the body field use the image button to either find an existing image on the server or upload a new one.

CKFinder requires a licence, it's pretty cheap.


How do I find a vocabulary ID for use with tokens

Sure, just pop into the taxonomy_vocabulary table in the database and see what vid is associated with the correct vocabulary.

For the record if you do need to get it programmatically you can do so like this:

$vocab = taxonomy_vocabulary_machine_name_load('vocab_name');
$vid = $vocab->vid;


Responsive image style with srcset and without sizes

Define your own breakpoints group with "multipliers" settings in YOURTHEME.breakspoints.yml  (see D8 Docs)
Go to Admin > Configuration > Media > Responsive Image Styles and add a new image style.
When creating the responsive image style, select your breakpoint group created in (1.). When your YAML is correct, you should see a separate detail set for every multiplier (=dppx).
Select type " Select a single image style." and select your corresponding image size. Repeat for every DPI group defined in your breakpoints.yml
In your node's display settings, for your image field, select the responsive image formatter and choose your responsive image style created in (2.)


Does this look right for adding a terms of use checkbox to register form?

Yes, but I would change

$form['#validate'][] ='customfunctions_form_validate_custom';

to

$form['#validate'][] ='MYMODULE_user_registration_form_validate';

and

function MYMODULE_form_validate_custom($form, &$form_state) {

to

function MYMODULE_user_registration_form_validate($form, &$form_state) {

Nothing wrong with your code, but this just keep with the Drupal naming convention ie search_form_validate,  node_form_validate, etc

Also

'#title' => t('Terms of Use*'),

is bad

'#title' => t('Terms of Use') . "*",


Figured it out!

When defining the field in the MigrateSQLMap I can set a table alias for the field:

$this->map = new MigrateSQLMap($this->machineName,
    array(
        'labelId' => array(
            'type' => 'int',
            'not null' => TRUE,
            'alias' => 'l', // it's the letter small case "L", not the digit 1
        )
    ),
    MigrateDestinationTerm::getKeySchema()
);

The 'alias' => 'l' makes the labelId become l.labelId in the queries.


How to create a Pie chart using views google chart tools

I had the issue - though not in drupal, but a native php application. While I've read that large differences in values can trigger the "other" slice, this was not the case in my application.

The datatable rendered perfectly as ColumnChart, but failed to show slices as PieChart and only came back with 100% "other".
What resolved the issue for me was casting the values in php to integer with intval().
Apparently the CulumnChart visualization is forgiving, while the PieChart is not when it comes to values other than intergers.
Hope that helps clarify.


Why isn't Drupal aggregator configurable?

Use Feeds, it's import or aggregate RSS/Atom feeds to Drupal.


Is there a filter/search option available for navigating the 'Find Content > Files' page?

The best thing to do here is create a custom VBO view to suit your needs!
It can have all the filters and sortable columns you want, and ... checkboxes so you can perform actions on the selected items.

See a guide here for using Views Bulk Operations.

Don't forget to set the views access permssions as you want to create an admin only vbo view !


Paragraphs or Field Collection doesn't matter for your code. You need to add the newly created items to a field.

For example if the field collection field is in a node:

$node->field_collection_name[] = $new_item;

Not in a form alter hook, but in an entity create hook. See the linked question.


How to resend simplenews content for many times - Simplenews module

solution:
simplenews Status Reset module .


Using variation values in a template file

Here is the answer that worked for me:

product.field_accessories[0]['#commerce_product_variation'].get('field_images')[0].entity.fileuri)

And I looped over the product.field_accessories to get just the first image for each product


Taxonomy term custom view page for all sub terms

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

This module will help you for sure :)

Read the documentation at https://www.drupal.org/node/577646


How to show a field from the current node in quicktabs

Depend from requirements in the project, but Field Group can be an option too.


How to apply the attribute "rel=nofollow" to links in the comments?

Go to Configuration -> Content authoring -> Text formats -> Plain text (your format), then tick the Limit allowed HTML tags option.

In the filter settings at the bottom of the page is the Add rel="nofollow" to all links checkbox. Tick that... Since this is plain text, you will probably want to remove the contents of the Allowed HTML Tags field, too.


It's not quite the approach you had in mind (modifying the classes variable) but I would recommend you do as Bartik does and work with the Attribute object instead:

{% extends "block.html.twig" %}

{% set attributes = attributes.addClass('new-class-goes-here') %}

{% block content %}
  {% if site_name %}

     <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}

  {% endif %}
  {% if site_slogan %}

{{ site_slogan }}

  {% endif %}
{% endblock %}

I think the key thing here is that the variable you are modifying is initialized (and used) outside of the twig block. If the variable were initialized inside the twig block then I can see needing to override it inside the child templates's twig block as well.

More on working with Attributes in templates here: https://www.drupal.org/node/2513632


I have usually used the Boost module. It provides a lot of functionality and works really well, but can be a bit to set up since many times you have to modify .htaccess files when rules changes are made. I've used Boost for many sites where Varnish or some other server-side solution was not available and the results were satisfactory. Keep in mind that boost will not work when authenticated --- in fact many caching solutions will not. But Boost does have other modules to help cache authenticated pages for users.


Redirect all pages to a form unless the user has filled out some information (Drupal 7)

This should do it. although there might be a module that already does this as well.

https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_login/7


How to have a node creation form on a separate node creation form?

Check out References dialog also. The module extends entity reference field by adding links to add, edit and search (which links are available can be configured) for references through a dialog.


How can I enable moderator role's ability to administer users only apply to certain user roles?

There is quite a new contrib module called "Permissions subset" for D7 you could test if it meets your requirements.


How to uninstall a module that has added a basefield that has data

This is a known Drupal Core limitation that looks close to being ready so hopefully will be fixed in D8.5.  In the meantime you could apply the patch linked to the issue.


microblog module - problem with max characters

The title column of the {node} table is limited to 255 characters. Just because you change it in the UI doesn't mean that it can be saved like that in the database, unless you mess around with the database schema manually (and you should not do that).

I am not sure why that module is exposing itself as a node type, sounds rather strange to me. The only reason I can imagine is being able to rely on the node access system. But nodes are a rather heavy thing, there is a lot of overhead that seems unecessary to me for this use case.


Ajax on a webform affecting comment form and user-registration form

The problem can be that ajax functionality is attached to button by its id attribute. Seems all three buttons - for webform, comment and user-register have the same id "edit-submit".

To fix this - just add unique id for webform submit button.

function alterwebform_form_alter(&$form, &$form_state, $form_id) {

//see if webform_client_form_ is in the form_id
if(strstr($form_id, 'webform_client_form_')) {

  //get the nid so we can use it in the wrapper value
   $nid = $form['#node']->nid;

    $form['actions']['submit']['#ajax'] = array(
        'callback' => 'alterwebform_webform_js_submit',
        'wrapper' => 'webform-client-form-' . $nid,
        'method' => 'replace',
        'effect' => 'fade',

    );
    // Add unique id for submit button.
    $form['actions']['submit']['#id'] = 'webform-client-form-submit-' . $nid;

    $form['#validate'] []='alterwebform_test';
  }
}


Change OG Group River of News Per Group Basis?

heh heh i bloody done it!

Relationships
OG membership: OG membership from Node
(OG membership from node) OG membership: Group Node from OG membership

Filter criteria
(Group node from OG membership) Content: Placetype (= Blog)


Update user via REST (and under AngularsJS)

I suggest you first try to test it with a browser REST application extension.
I would recommend this for Firefox: https://addons.mozilla.org/he/firefox/addon/rest-easy/

If you still doesn't get any error, check your watchdog... there is no reason this shouldn't work.


Devel issue - "Rebuild the theme registry on every page load" won't work

Not a straight solution and not really the best one but it seems that the co-problem; clearing the cache after every css change, was mainly server-sided, rather than Drupal sided --- I store at siteground.com and it was a Cpanel tool named "Supercacher" that caused all this mess and apparent lifetime wasting (and yet it raises the chance for good SEO when you site is finished).

Anyway, When you develop, better turn it off in Cpanel.

Btw, this was enough by it's own for me... Neither Devel nor any other external module is needed for this solution to work... Just disable the tool at Cpanel.


Instructions to install a ready-made site in localhost

You need to tell Drupal where the database is that you imported.

Make sure to copy default.settings.php in sites/default to settings.php (if it does not already exist, in which case you can skip this step.).
Edit $databases array (lines 213 or so) in setttings.php. You should add the username and password of a user with full privileges on your MySQL installation (usually it will be user root, with password root).

For instance:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'NAME OF DATABASE YOU IMPORTED',
      'username' => 'USERNAME',
      'password' => 'PASSWORD',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

You should now browse to admin/reports/status which, will give you instructions to change file permissions for settings.php so that it is not publicly writable, and maybe to run Cron or Drupal updates.

Please also look at Migrating a site for more in-depth instructions.

Chances are that the default root username and password for your MySQL instance would be: root, and root. If it is not, then please open PHPMyAdmin and have a look at the User tab section/or google for assistance on how to create a new user with 'ALL Privileges'.


Show title of article instead of date in a Views block

Try the following steps:

Create new date format as you want (MM/DD/YYYY).
   admin/config/regional/date-time/formats
Create Date type and assign your format.
   admin/config/regional/date-time
In views: Select your date type under "Choose how users view dates and times:" when you add your date field under "FIELDS".
Add (Content:title)title field (after date field) and Enable the Link this field to the original piece of content checkbox.
Bullet point from your css


Redirect from within controller always goes to home page

When you call a controller as error page via the basic site settings this is not the controller of the main request, this controller is executed in a subrequest to get a themed output of the otherwise simple text message you see for non 4xx exceptions like a 500 error.

Better place the redirect in the main request, before the rendering of the exception is delegated to a subrequest by CustomPageExceptionHtmlSubscriber. You can use the default priority 0, because the core exception handler has -50.

@MarshallMorrise has posted the working code at https://drupal.stackexchange.com/a/290659/47547


Drupal error. Drupal safe mode possible?

Try deleting the row for the og module in the system table. Then run a query for each database table beginning with cache_:

TRUNCATE TABLE cache_*

This should make Drupal forget anything it knew about organic groups (this is how to clear the cache manually).

I'd suggest keeping your modules in the standard location which is /sites/all/modules rather than /sites/default. I don't know if thats part of the problem here but it might be.


Changing the player set to play files of that type might help. If not, installing one of the transcoders like ffmpeg or Zencoder will fix it. If that's not practical, you can use other modules besides Video, and create your own video field, for example the jPlayer module (which takes any m4v videos, a variation on mp4)


My first inclination is that this is a caching issue.

Other possibilities:

Is the node actually stored in the orders table?  Do you do the appropriate updates for the nodes table as well?
Is this in an incomplete transaction?  (db_transaction)
Have you checked the return value of the ->execute() to see if it is returning the right number of rows?

Without a full description of what the variable $context and the table orders contains, it is hard to give any better answers.


Json views not displaying in json format, instead displaying in web view

ya i got the solution. Just un_check the Viewa API
Hope this will help some one


I just had to download the translation file of the language and it was fixed by importing it through the "translate interface" area of the Drupal backend.


If you want to alter the cart item, then you can use hook_uc_cart_alter of ubercart.

  This is called every time the cart is rebuild (e.g. when products are
  added), so it's a good place to alter the cart item.

Code snippets to modify the qty of the item

/**
 * Implements uc_cart_alter.
 */
function mymodule_uc_cart_alter(&$items ) {

  foreach ($items as $index => $item) {

   //you can add condition for your product

    $items[$index]->qty = 2;
  }
}

For reference:

http://www.ubercart.org/docs/api/hook_uc_cart_alter


Alter webform value submitted by webform

List of issues with your code (random order):

You are taking $form by value, not by reference, so all changes you make to it are local, scoped to function body only. Make it my_module_validate(&$form, &$form_state) if you want to have a chance to alter form - but see next points, too.
You are passing values around using $form instead of $form_state - things that can change in the form's lifetime belongs to $form_state rather than $form (yes, simplification, but a good starting point). In specific case of Webform module that may be needed, but you are coding against expected practice, so you should expect some difficulties when doing so.
You are using validate hook for something that is not validation. You should rather prepend additional save handler for this purpose.
You calculate on input. Usual practice in Drupal is to save user data "as is", and do formatting and calculations at output. It allows greater flexibility and retroactive changes if algorithm change. Again, it's not set in stone, and your situation may need other approach. It's OK, as long as you remember that's not quite the way Drupal was designed to work.

Tobias Kirsch posted nice summary, and I fully agree with it:

  What this means in your case: neither the validation nor the submission function of your form might be the right place for you to achive this. Maybe it would be better to add this calculation when the user is shown his submitted values. Honestly I think webform as a beginning might not be the right module to achieve this


Exposed form for contextual filters when using non-taxonomy filters?

To find "... some way to change the filters once they're on the page ..." (as in your question), it may help if you take a look at the (free) video about Contextual filters with paths. It covers these topics:

Using contextual filters for filtering Views result.
Using input from the view path to set contextual filter values.
Using contextual filter values for changing the view title.

You may also want to watch some (or all?) of these related videos, also about contextual filters, sometimes called "arguments" also (quotes are from the links mentioned):

Action if no contextual filter value is present, with these topics:

  Different views behaviours if no contextual filter value is present.
  Some words about why 'provide default value' is a bad concept.
  The provide summary option.

Contextual filters and menu tabs, with these topics:

  Using contextual filter values inside a path (instead of at the end of it).
  Re-using existing site paths to get contextual filter values.
  Creating menu tabs in Views.
  Creating a menu tab on user pages, to display all articles created by the user.

Default menu tabs, with these topics:

  How to use the default menu items in Views.
  How to create sub tabs.
  How to use default menu items together with contextual filters in the path.

Validation of contextual filter input, with these topics:

  How to validate input for contextual filters.
  Some options for how to validate the input.
  Why it is a good idea to validate contextual filter input.
  Views behaviour if the filter input doesn't validate.
  Some words about not being able to validate contextual filter input with multiple values.
  Perhaps some words on filter validation being able to alter the filter value.

Contextual filters and default values, with these topics:

  What default contextual filter values are.
  How to set default contextual filter values.
  Some examples of extra settings for default contextual filter value.
  Some words about why it is a bad idea to let the view make assumption about the context where it is embedded.
  Some more words about why it is a bad idea to let the view make assumption about the context where it is embedded.
  Some words about using default contextual filter values when creating Views blocks.


How to Pass a Variable to Commerce Order Twig Template

I think this should work, in THEME_NAME.theme add

function THEME_NAME_preprocess_commerce_order_receipt(&$variables) {
  $variables['test'] = "test";
}

Note: replace THEME_NAME with actual name of theme

Then doing {{ test }} should output "test".

Note: remember to flush all cache to see changes.


If you trace the code from the system_performance_settings, you'll see that is uses system_settings_form for form generation, which uses system_settings_form_submit form submit handling, which in turn does

foreach ($form_state['values'] as $key => $value) {
  if (is_array($value) && isset($form_state['values']['array_filter'])) {
     $value = array_keys(array_filter($value));
  }
  variable_set($key, $value);
}

So to find any individual variable name, your best bet is to

drupal_set_message($key);

in that function.


If you are using Drupal 7 you may change the teaser format for the content types promoted on front page. Navigate to "Home » Administration » Structure » Content types » YOUR CONTENT TYPE » Manage display" and click the "teaser" sub tab; then change the format for the body field from "Summary or trimmed" to "Default".

Notice that this will affect some other pages (taxonomy and views).


So first you want to define a block that contains a form. You define the contents of a block in $block['content'].

/**
 * Implements hook_block_info().
 */
function MYMODULE_block_info() {
  $blocks['your_block_name'] = array(
    'info' => t('Name of your block'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function MYMODULE_block_view($delta='')
{
  switch($delta) {
    case 'your_block_name':
      $block['subject'] = null;
      $block['content'] = drupal_get_form('MYMODULE_form');
      break;
  }
  return $block;
}

An after that you need to define your form. In Drupal you use the Form API to build forms. In the example above we fetch the form called MYMODULE_form. And the form is defined by implementing hook_form().

/**
 * Implements hook_form().
 */
function MYMODULE_form($form, &$form_state) {
  $form['MYINPUTBOX'] = array(
    '#type' => 'textfield',
    '#title' => t('My label')
  );
  return $form;
}


The 'drupal' way to implement delete button UI

What you listed is what we normally do.

A menu router item (what you define in hook_menu actually serves a lot more than just pointing logical actions to functions/methods. It also makes sure than the items exist, they are accessible, and delivered correctly.

In hook_menu, you can definite how the access should be granted (with permission system or anything else). You can use wildcard loaders to load items, so you don't have to throw 'page not found' errors yourself.

You don't have to put your logic in the URLs. If you deal with entities, have your entity build the operation URLs, so they become part of your entity class, and not part of the template (the "View" of traditional MVC).

When the entity gets complicated, I often end up writing a single menu router to handle them all. The operation argument of a menu path (edit, delete, clone, disable, etc) can be a wildcard loader as well, and you can easily validate it using a method_exists() call.


Change CSS class based on number (length) of entity reference items, in a paragraph entity

{% for action in paragraph.field_call_to_actions %}
    {{ paragraph.action.value }}
{% endfor %}


How to associate a node with a menu without adding it to the menu

I am not exactly sure of what you are trying to accomplish here, but it sounds like you are trying to use menus to alter the breadcrumb behavior

If that's the case, you should try the menu breadcrumb module - http://drupal.org/project/menu_breadcrumb or the custom breadcrumb module - http://drupal.org/project/custom_breadcrumbs

Hope this helps


Found this module cURL HTTP Request via this thread and it worked like charm. The issue was with HTTPS hence the HTTP proxy module wasn't able to help me on this.


Programmatically subscribing user to a organic group

Ok got it working, its still the og_group() function.

function group_membership($type, $gid, $uid){
  $group_type = 'node'; //All our/my groups are of type node
  $entity_type = 'user'; //All our/my members are type users
  $values = array(
    'entity_type' => 'user',
    'entity' => $uid,
    'field_name' => FALSE,
    'state' => 1,
  );
  $return = FALSE;

    switch ($type){
        case 'subscribe':
          $values['state'] = 2;
          og_group($group_type, $gid, $values);
        $return = 'SUBSCRIBED TO TEAM';
          break;
      case  'approve':
          $values['state'] = 1;
          og_group($group_type, $gid, $values);
        $return = 'APPROVED TO TEAM';
        break;
      case 'delete':
        og_ungroup($group_type, $gid, $entity_type, $uid);
        $return = 'REMOVED FROM TEAM';
        break;
      default:
        $return = 'FALSE TYPE';
        break;
    }

  print json_encode($return);
}

Not that pretty but it works for now.


Drupal7: Private/Password Protected Section in a Drupal Website

Drupal has only a very course access control structure for viewing content.  For the any user role, you can set permission to 'access content' (Drupal 6) or 'view published content' (Drupal 7), but that's about it.

Most inportant, out of the box, Drupal does not have any setting that let you set the permission "access content/view published content" for a particular content type.  It is all or nothing. I.e. if you untick "access content/view published content" for the anonymous user, no content on your site will be available to those that are not logged in.

Assuming that you're looking for more fine-grained access control, (where only a section of your website is private) you need to install a node access control module.  Many such modules exist. There is a page at the Drupal.org wiki giving an overview of node access modules.  You may start by reading that and try to find a suitable module.

To make a recommendation, I'll say that the one named Content Access seems to match your requirements.  It lets you control access per role and per content type.  I use this module to create premium or private content for logged in users on my sites.

To use it, install and enable it.  Create a new content type for the private pages - let's say you call it "Private page". Then (assuming Drupal 7) navigate to Administration » Structure » Content types and click "edit" for the "Private page". There is now a tab "Access control" that lets you control all types of access (Including "View") for this content type only.

As for menus, Drupal will usually manage this for you.  Any menu items that leads to content that is inaccessible, will not be visible for the roles that are not allowed to see it.


How to implement revisioning in my own module?

As Clive says, you need to create a custom entity (with the API) to hold the data. Then Drupal will create the necessary tables and take care of the versioning for you.

If you need to do special things (that is not already done by Drupal's built-in versioning), you can intercept both saving of new revisions and reversals with hook_entity_update.

AFAIK, there is no simple way to tell a new revision apart from a reversal.  Technically, a reversal results in a new revision with a new version ID (vid) being created, where the content of the new revision just happens to be identical to some old revision.

If it is really important for you to tell them apart, I guess you could keep a table with SHA2 (or MD5) hash signature for each revision, and look up the signature in that table to identify a reversal.

For the sake of completeness, I'll also mention that I've observed than when someone do a reversal, a log message is generated and placed in {node_revision.log} (E.g. "Copy of the revision from Thu, 2014-06-19 13:53.". Otherwise, this field is filled in with a user-written change notice (or left blank). You may be able to use this to detect reversals, but IMHO this method is not reliable as the string can easily be spoofed by a user who knows about this.


Date field displayed with wrong timezone with PHP's date_create + date_format

Looks like your date field is configured to use either site zone or user time zone configuration.

So, while saving the node drupal expects the entered value in usertime zone or site time zone and then convert it to UTC before saving it to database.

While showing it views consider the timezone configuration and format the date as per current user viewing the date field.

The timezone you see as 'America/NewYork' in the dpm result is the timezone configuration of the user created the node.

In order to show the date with format you can use format_date, something like below.

$user_time_zone = drupal_get_user_timezone();
format_date(strtotime($node->field_date['und'][0]['value']), 'custom', 'm/d/Y h:i:sA', $timezone = $user_time_zone);

Important thing is to choose the right configuration for your field timezone settings, if the date field is irrespective to current user timezone keep the timezone configuration to UTC.


Proper directory permisions for module installation?

The module directory has contested ownership. In your case, using the FTP set up from the browser, the modules directory (and subdirectories and files) need to be owned by the FTP user you are logging in with.

For example: if you are ftp-ing in with myusername then the ownership on the directories and files are most likely be myusername. That is the default configuration for most FTP servers (ProFTPd for example).

$ chown -R [myusername] [pathtomodules]

If you are updating Features (or configuration in Drupal 8) from the Drupal backend you'll want the modules directory owned by the same user as your web service runs as. Then you can have your permissions set to something more reasonable.
If you grep ps for Apache, nginx or httpd you should discover the user that's running the process.

$ ps aux | grep -i 'www\|apache\|nginx'
$ chown -R [username] [pathtomodules]

And finally if you are using drush dl you'll need the owner to be your SSH user.

In all cases you can set the strongest permissions with the following. Remember the webserver needs read on all files and execute on all directories. This command will give you 755 on directories and 644 on files.

$ chmod -R u+rwX,go+rX,go-w [pathtomodules]

The first two numbers in your ls command are user and group. That may be a numeric match for your web service user above. The third column is size.


How to add predefined text to contact form?

You can create a module, hook on hook_form_alter and add a #prefix to the first input field.

More simple: Create a block with your paragraphs and switch it on for region "(main) content" on the contact page (no programming needed).


How to enable user registration, but don't allow any of those users to login?

You could use Rules

Event: After saving a new account

Action: Block a user >> data selector: account


Some of node links of content types are corrupted

I've hit redirecting-to-front-page nodes in the past when I've stripped out use of the PHP filter input format. Turns out there was conditional logic that sometimes printed javascript redirect code.

Does the pages in question use the PHP filter format? If the admin blocked eval() perhaps it could stop execution of PHP and just render redirect code?

You can check disable_functions value in /admin/reports/status/php to confirm your suspicion about disabled functions.


Get field value from referenced entity in twig loop

You want to work with node instead of content.
something like this should work
{% for item in node.field_workers %}
 {{ item.entity.field_name.value }}
{% endfor %}

See Entity API Cheat Sheet and Twig and Entity Field API or how to take control of node.html.twig (my blog post) for more information.


Automate clear of mysql database in drush site install

Chapabu is correct, but if you're using drush 5.7, this is unnecessary with site-install. If there's an existing db, drush will warn you it will drop all tables in the existing database.

For example:

drush dl drupal --drupal-project-rename=test
cd test
% drush site-install standard --db-url=mysql://root:root@127.0.0.1/test --site-name=test
You are about to create a sites/default/files directory and create a sites/default/settings.php file and DROP all tables in your 'test' database. Do you want to continue? (y/n): y
No tables to drop.                                                                          [ok]
Starting Drupal installation. This takes a few seconds ...                                  [ok]
Installation complete.  User name: admin  User password: 6SkT989sPX

So let's rerun the site-install command over the now existing "test" directory

% drush site-install standard --db-url=mysql://root:root@127.0.0.1/test --site-name=test         130 ↵
You are about to DROP all tables in your 'test' database. Do you want to continue? (y/n):


Testing the value of Fields stored on Taxonomy Terms

Panels is very good for overriding Taxonomy pages. You can have different page and layout variants per vocabulary, user, theme, site etc. You can then include your code in a custom panel pane for taxonomy pages, together with whatever layout or views necessary, or write your own CTools content type for Panels.


Drupal Print PDF module with Chinese characters

Well I sort of solved it by using @font-face directly in the template file. Not the ideal solution, but it's working.


Does "composer remove drupal/module" actually uninstall the module first?

No, Composer doesn’t install or uninstall modules in the site itself.

It’s a dependency manager; all it does is compute your requirements, then download them.

You might be able to add a post install/update command to automate it, but trying to make it generic would probably be a pain.


You can see an article on the subject here without using Events

https://chromatichq.com/blog/replacing-hookboot-and-hookinit-functionality-drupal-8

Possible that it will meet your needs.

  Replacing hook_boot and hook_init Functionality in Drupal 8

  The change notice page states:

  Using StackMiddleware

  This comment on the hook_boot change notice page provides an example
  of using StackMiddleware. It provides 95% of the functionality needed
  to run logic on cached pages by utilizing a tagged service with the
  http_middleware tag. Since the new class is a service, it will have
  full access to other core and contrib services, allowing for much
  greater functionality. The example shows the following for a module’s
  *.services.yml file:

services:   http_middleware.mymodule:
  class: Drupal\mymodule\StackMiddleware\MyModule
  tags:
    - { name: http_middleware, priority: 180, responder: true }

  This is a pretty standard service definition, but note the items added
  to the tags property that register our service with the
  http_middleware tag and also set a priority. In order to bypass the
  page cache, understanding the page_cache.services.yml file is helpful.
  There, a similar definition can be found, but with a higher priority
  value.

services:   http_middleware.page_cache:
    class: Drupal\page_cache\StackMiddleware\PageCache
    arguments: ['@cache.render', '@page_cache_request_policy', '@page_cache_response_policy']
    tags:
      - { name: http_middleware, priority: 200, responder: true }

  Higher priority services are run first. So to trigger logic before the
  page cache module takes over the request, a priority greater than 200
  is needed.

services:   http_middleware.mymodule:
    class: Drupal\mymodule\StackMiddleware\MyModule
    tags:
      - { name: http_middleware, priority: 210, responder: true }

  With this change in the services files, and proper setup of the
  service as described by the comment, the http_middleware.mymodule
  service should now be called on every page load, even on fully cached
  pages.

namespace Drupal\example\StackMiddleware;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

/**
 * Performs a custom task.
 */
class ExampleStackMiddleware implements HttpKernelInterface {

  /**
   * The wrapped HTTP kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $httpKernel;

  /**
   * Creates a HTTP middleware handler.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $kernel
   *   The HTTP kernel.
   */
  public function __construct(HttpKernelInterface $kernel) {
    $this->httpKernel = $kernel;
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
    // Custom logic goes here.

    return $this->httpKernel->handle($request, $type, $catch);
  }
}

  Verifying the Results

  A quick and easy way to test all of this is to simply add
  \Drupal::logger('test')->notice(‘not cached’); into the functions
  triggered by each of the approaches above. Ensure that the Drupal
  cache is enabled, and simply refresh a page while watching your log
  (drush ws --tail). Then verify the logic is being called as expected.


How can I debug why user_save() is being called twice?

It turned out Rules was the culprit.  I didn't realized that using the Set a data value action could cause user_save() to be called twice.


For completeness: If what you need is to change the facet alias, not the machine name, then the FacetAPI Alias module seems to do exactly this.

If you also consider using facetapi_pretty_paths, this issue might be interesting: Is facetapi_alias compatible with facetapi_pretty_paths ? (compatible, overlapping functionality, compliment one another?)


How to add Specific Class to Each Drupal Menu Anchor

You can do that by using Menu Attributes module.

  This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.


Conditional Show/Hide Child Terms on Edit Page

Off the top of my head, I would say that you can do this more cleanly with two '#type' => 'select' elements.
The first one would just contain the parent terms.
The second one would be set to
'#states' => [
  'disabled' => [
    ':input[name="parent_term"]' => ['value' => ''],
  ],
],

Then you could use Drupal Form API #states to conditionally set the value of the second select element to the appropriate child terms, depending on which parent term is selected.
The most obvious alternative approach would be some hacky JavaScript.


Searching for nodes from another site in a multisite installation

You could do that easy enough with Google Custom Search, e.g:

http://www.google.com/cse
http://drupal.org/project/google_cse

Basically can search a range of selected sites from one interface, using the power of Google search.


Oh, this turned out to be easy. Use hook_entity_property_info_alter() to define a new property.

/**
 * Implements hook_entity_property_info_alter().
 *
 * @see profile2_entity_property_info_alter()
 */
function MYMODULE_entity_property_info_alter(&$info) {
  // Add related profiles to the user object.
  $properties = &$info['user']['properties'];
  $properties['MYMODULE_profile2'] = array(
    'type' => 'profile2',
    'label' => 'Profile 2 (MYMODULE)',
    'description' => 'The first profile2 profile that can be found on the user.',
    /* @see _MYMODULE_get_profile2() */
    'getter callback' => '_MYMODULE_get_profile2',
    # 'bundle' => $type_name
  );
}

/**
 * Entity property callback.
 *
 * @param object $account
 * @param array $options
 * @param string $name
 *
 * @return object|null
 *
 * @see profile2_user_get_properties()
 */
function _MYMODULE_get_profile2($account, array $options, $name) {
  $profiles = profile2_load_by_user($account, NULL);
  return reset($profiles) ?: NULL;
}


Load Bootstrap CDN only if not is loaded before from another project

One approach:
Attach the modal-page-bootstrap library as you are doing, and don't also load bootstrap.js in another way.
Don't worry about adding libraries multiple times to the same page. Drupal is smart enough to only load that library once, and at the right time and order.
The conflict will only arise if you are loading bootstrap.js some other way besides attaching a library. If this is the case, then as @leymannx says above you need to find where the extra bootstrap is coming from.
If the Bootstrap CDN is loaded by a script tag in a Twig template, just remove that script tag and only load the CDN via the library, allowing Drupal to keep track of it.
Another approach:
If another_project is a theme or contrib module, then it has probably already defined the Bootstrap CDN as a library. If this is the case, you could just attach that library wherever you need it to prevent conflicts. Take a look at the another_project.libraries.yml file to see the name of the library, and then load that library wherever you need it in your custom theme or module. Again, as above, this will allow Drupal to manage the library so that it will only be loaded once, and only where it is needed.
Note, however, that by doing so you will create a dependency on another_project. If you do this in a custom theme or module, then you should make that dependency explicit by declaring the dependency in your info.yml. Otherwise, if another_project is not present for any reason, you won't be able to load the library.


Is there a drush script to disable all caches?

You need to set several variables to turn off caching on your dev site...

 drush vset cache 0
 drush vset preprocess_css 0
 drush vset preprocess_js 0
 drush vset page_cache_maximum_age 0
 drush vset views_skip_cache TRUE

It's even easier if you have conditional config in your settings.php file. Then you can refresh the DB and the changes will stick!

$conf['cache'] = 0;                       // Page cache
$conf['page_cache_maximum_age'] =  0;     // External cache TTL
$conf['preprocess_css'] = FALSE;          // Optimize css
$conf['preprocess_js'] = FALSE;           // Optimize javascript
$conf['views_skip_cache'] = TRUE;         // Views caching

... though if you just turn off various caching through the admin UI and clear cache once then you can theme away without turning off the rest... since script it less likely to change.


How to change this "Anonymous's Blog" link to another name?

The link name is derived from the author of that node. The variable should be $content['links']['blog']['#links'] array, which can be found in node--blog.tpl.php. You can manipulate the data at that point, which is best kept as simple as possible, due to being in the tpl file itself.

If you're looking to do complex changes, I would suggest a _preprocess_node in your template, which is probably ideal if you're doing anything more than an unset or simple truncation.

More information can be found at https://www.drupal.org/node/1783428 and Preprocess function for node.tpl.php file respectively.


How to create a Custom Content type without Title?

You can use the Auto Nodetitles module.

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).


How to render the main menu in alphabetical order regardless of menu link weight?

I found that if the menu link weight is the same, then the alphabetical order will be applied.


Getting Feed Aggregator to ignore certain incoming data

OK, so I'm considering deleting this but it was such a source of frustration for me I guess I'll leave it up in case someone else ever comes across this. This answer, to me, seems like more a workaround (mainly because I am still lacking a basic understanding of why it's happening) so if anyone else has a better answer or more information please do post your own answer.

It seems like you can't have complete control over how Views or Aggregator arranges elements from the XML feed. It also seems (from my fruitless Googling) that this isn't usually a problem. I don't really know if this is an issue with how the RSS feed we have to use is configured or if it's a Drupal thing but I know the answer is in gaining control over where and when the different XML elements appear.

Most people seem to use a module called Feeds to gain control over this type of thing (and do other stuff). From superficially looking into it, it seems like it could fix my problem but it creates a separate node for each incoming item, which is not ideal for my special case. The feed on the site I'm working on just keeps up with the latest 20 items and then discards them so I didn't want to have to deal with a separate node for each thing.

I've decided to try a different module called Views RSS which sounds like it can simply solve my problem (here's some more info). I haven't tried it yet but it looks promising. Thanks to anyone who read this and to anyone who might be able to contribute in the future.


$form_state['rebuild'] is used extensively in multistep forms. Take a look at the more advanced examples in the Form Example in the Examples project.  It's used in AJAX forms, as a special case of multistep, so you may want to look at the AJAX example.


How do I display, in a ColorBox popup, a caption AND a title (caption from image 'alt' attribute and title from 'title' attribute

Add "colorbox" class to your element. You could also select by document.getElementsByTagName("img"), but we don't really want to select every single img tag.

var cbox = document.getElementsByClassName("colorbox")

for (var i=0, i < cbox.length; i++) {
  cboxTitle = cbox[i].title;
  cboxAlt= cbox[i].alt;

  cboxTitle = "" + cboxTitle + " " + cboxAlt + ""
}

You then just got to make colorbox print out the title tag and style it the way you want.


Is it possible to create a table from Paragraph fields in Views?

You need to enhance your view with Relationships.

Let's say you have a content type Client with a paragraphs field Mail, which allows embedding instances of the paragraphs bundle Client_Mail. When you create a view on all Client nodes, you should find a Relationship to the field (Mail) which contains your paragraph bundle (Client_Mail).
After adding this relationship, the fields making up the paragraphs bundle will show up in the field list. You can add and arrange them like regular node fields, but make sure that the paragraphs relation is chosen in the field settings.


The block is already created; you just need to place it following these steps:

Go to Structure > Block layout
Click on _Place block; you will get the list of available blocks
Search for the facet block and click on Place block


Views Infinite Scroll content doubles up at end of scrolling

After going through the code, I see it is because they don't handle the Responsive Grid Views extension, which I am using.  I just hid the duplicate items with CSS for now, and I'll go back and submit a patch to the maintainer later.


How can I highlight only the contents that have been never published yet in the Views?

To display unpublished  content using views you  have to add "Node: Published" option as "No" under "Filters".


403 forbidden error when loading images in test server

This is a typical result of an incorrect url path.

That folder may/may not exist on the test server, but because it's outside of your user's folders, you 'don't have permission to access' it.

For example: Typical user's folders for cPanel are /home/USER/ with the site root at /home/USER/public_html. But, typical for a local machine is /var/www/....

So when you call sites/default/... from a local machine, it is possible that it's actually looking at /var/www/sites/default/.... When doing that on the test server, the path would be outside your user's folder and therefor no access permission.

It could be as simple as a missing ../ on your relative paths.
So you could try 1. adding ../ to the start of your paths and see if that takes it to the correct location.
or 2. Try explicitly setting the base url in your settings file $base_url = 'http://foobar.com'; to force a starting point for relative paths.


temporary://fileh4Oxvi could not be copied, because the destination directory is not properly configured

...could not be copied, because the destination directory...

The temp folder is the source in this context, Drupal is complaining that the destination is not writable.

You need to make your public file system (usually sites/default/files) writable by the web server user.


So, it took a while to figure what I needed was to add a custom local task navigation tab. To handle adding local task you need to learn the hook_menu() function, right after you learn to build your first hello world module. P.S. having the Test 1 and 2 menu items is what tells Drupal to create the outcomes tab.

/**
* Implementation of hook_menu().
*/
function outcomes_menu() {
  $items['node/%node/outcomes'] = array(
        'title' => 'Outcomes',
        'type' => MENU_LOCAL_TASK,
        'access arguments' => array('access content'),
  );
  $items['node/%node/outcomes/test1'] = array(
        'title' => 'Outcomes Test1',
        'type' => MENU_LOCAL_TASK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments'=>array('drupalform_form1')
  );
  $items['node/%node/outcomes/test2'] = array(
        'title' => 'Outcomes Test2',
        'type' => MENU_LOCAL_TASK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments'=>array('drupalform_form1')
  );

  return $items;
}

Hopefully, this helps someone else.


set specific time to cron for specific php script

Set system cron to every 5 minutes, and use Elysia Cron to manage particular tasks:

  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

  [NEW IN 2.0] Set the timings and frequencies of each cron task (you can run some jobs every day at a specified hour, other only monthly and so on...). For each task you can simply choose between some frequently used options ("once a day", "once a month" ...), or use a powerful "linux crontab"-like syntax to set the accurate timings. You can even define your frequently used options to speed up site configuration.


If I understand you correctly:

Use Taxonomy: Term ID as argument.

Write php to get taxonomy term/terms from current node and return them.

Configure this view to display node types you want to display.


Another solution is assigning the created property of the $node object before calling $node->save.

e.g.

$body_text = 'This is the body text I want entered with the node.';
$created_time = time();

$node = new stdClass();
$node->type = 'article';
node_object_prepare($node);

$node->title    = 'Node Created Programmatically on ' . date('c');
$node->language = LANGUAGE_NONE;

$node->body[$node->language][0]['value']   = $body_text;
$node->body[$node->language][0]['summary'] = text_summary($body_text);
$node->body[$node->language][0]['format']  = 'filtered_html';

$path = 'content/programmatically_created_node_' . date('YmdHis');
$node->path = array('alias' => $path);

$node->created = $created_time;

node_save($node);

For more information please see the API docs on node_save().

The solution above has the added bonus of not requiring additional databases queries to clean up the timestamps after the node was created.


Use taxonomy_get_tree() to extract term names?

Nevermind... this works:

foreach($tree as $value){
    print($value->name);
}

Thankfully, it looks like I'm not the only idiot out there. Sigh...


Creating content regarding to node address arguments

Path aliases must be exact, thus if you want my-fancy-page/tt3741 to work you need to create an alias for it. If you link to the node path node/6 then node/6/tt341 will work. This has to do with how hook_menu works vs how path aliases work.

If you wish to hack around how path aliases work you can try out the PURL's Path Extensions feature http://drupal.org/project/purl or use hook_url_inbound_alter() to get the correct node given the unique alias.

Boost will work as long as each URL is unique (same as drupal's core cache). Good luck.


Override Domain-Restricted Content in a View

I posted this on the Domain Access issue queue as a support request and got this helpful answer:

You can only accomplish #2 under three conditions:

The content is marked "Send to all affiliates"; or
The view is a page marked as a Special Page Request (which disables Domain Access rules); or
The view is set to ignore node access control -- this is an advanced Views configuration.

Option 3 can create security issues if you are using other node access modules.

To make the content link to the appropriate domain, use Domain Source, which lets you specify a canonical URL for each node. If you don't use Domain Source, the canonical URL is calculated for you.


Commerce Customizable product (Example: add/remove topics for pizza)

I think this Josh Millar video will help.

Customizable Product with Drupal Commerce: Pizza Store


How to load a form/page into a div via AJAX?

Core does not provide an HTML format for non-dialogs, but you can create your own custom format.
mymodule/js/custom-ajax-loader.js:
(function ($, Drupal) {
  Drupal.behaviors.myCustomAJAXStuff = {
    attach: function (context, settings) {
      $("a.use-custom-ajax", context).once('mymodule-ajax').each(function(i, ajaxLink) {
        const $linkElement = $(ajaxLink);

        const elementSettings = {
          url: $linkElement.attr("href"),
          event: 'click',
          progress: {type: 'throbber'},
          element: ajaxLink,
        };

        const myAjaxObject = Drupal.ajax(elementSettings);

        // Declare a new Ajax command specifically for this Ajax object.
        myAjaxObject.commands.insert = function (ajax, response) {
          let target = $linkElement.attr("target");
          $(target).html(response.data);
        };
      });
    },
  };
})(jQuery, Drupal);

mymodule.libraries.yml:
mymodule.ajax:
  js:
    js/custom-ajax-loader.js: { }
  dependencies:
    - core/drupal.ajax

Add the library wherever needed: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal module
Then when you create your link
<a href="/admin/people/create" class="use-custom-ajax" target="#some-div-id">
    Add user
</a>


How to add existing product variations to a new product?

The option you're looking for is not present on purpose (and the widget itself is different despite how it worked in Drupal 7). Every product has its own variations that cannot be shared, so there's no way to reference the same variation from multiple products.

If you need to sell the same thing from multiple contexts, what you probably need is some other entity that references the same product, not a standalone variation. Products:variations have a very clear parent:child relationship ... they're "variations" of the main "product".


Entity View Attachments (EVA) with multiple contextual filters?

Querying the configured multiple contextual filter isn't working as i expected first and I spent lot of time to figure out why, then finally the solution was found:

Instead of Content: The name of Taxonomy (taxonomy_vocabulary_#) you need to select Content: Has taxonomy term ID Contextual filter and enable Allow multiple values to able to use multiple values in the form of 1+2+3 (for OR) or 1,2,3 (for AND).
If You have another Contextual filter configured, you can separate the query with "/".


How to update a field programmatically and keep the fields format and array structure?

Calling node_save() won't automatically re-load the node so you'll need to do it manually if you want to see the computed field values:

$node = node_load($my_node_id);
$node->body['und'][0]['value'] = 'My new text.';

node_save($node);

// Re-load the node from the db
$node = node_load($node->nid, NULL, TRUE);

// $node->body now has the values you would expect.

I just tried that and can confirm I get the same behaviour as you (the safe_value is not updated) if the call to node_load() is commented out.


Error when upgrading to Drupal 8.7.1 on module menu_link_content

I got this error, but when I had run the update with drush updatedb -y command, I resolved that.


Need help creating a Commerce Order from Commerce Customer shipping profile

Things like this, is much easier to accomplish with a bit of custom code. You could add a form on the order view page, with the order as the context. This can be done by using hook_commerce_order_view.

All you really need to do, in the submit handler would be something like this.

$old_order //
$new_order = commerce_order_new();
$new_order->uid = $old_order->uid;
$new_order->commerce_shipping_profile = $old_order->commerce_shipping_profile;
commerce_order_save($new_order);
$form_state['redirect'] = 'admin/commerce/order/' . $new_order->order_id . '/edit';

The code above is from memory, should be in a form submit handler and is written from memory, but should work, if I remembered correctly. As you can see, it's pretty simple to accomplish.


Saving form data and running custom queries in mysql

Short simple answer is Views to display output of Entity Form inputs.


Changing a redirect depending on selection

You can add your own submit handler to your form. In the submit handler function you will be able to access the value that was entered by the user.

The code could look something like this (to be put in a custom module).

    /**
    * Implementation of hook_form_alter()
    */
    function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
      if($form_id == 'MY_FORM') {
        // Adds our own custom submit handler to the form MY_FORM
        $form['#submit'][] = 'MYMODULE_MYFORM_custom_submit';
      }
    }

    /**
    * Custom submit handler for MY_FORM
    */
    function MYMODULE_MYFORM_custom_submit($form, &$form_state) {
      $form_state['redirect'] = 'my-path';
      $form_state['rebuild'] = TRUE;
    }

Replace 'my-path' with the value the user entered. Look inside $form_state['values'] to find it. Don't forget to check that the value is valid so no funky stuff is done here :)

Good luck.


Just because this comes up high on google when searching for the answer (and I just figured this out):

Run cron
Run update.php

Your fields will then appear. This is a Drupal 6 Features issue only. With Drupal 7 the fields should show instantly.


According to Kaltura module documentation here http://cgit.drupalcode.org/kaltura/plain/README.txt?h=7.x-3.2

You should download the php version of API from here   (http://cdnbakmi.kaltura.com/content/clientlibs/php5_16-12-2014.tar.gz) and place it under DRUPAL_ROOT/sites/all/libraries/KalturaClient directory.

Note: The directory name is case-sensitive.

Alternatively you can use drush for this.Here is a command for drush.

    Drush kaltura-client-install


Show users a view of nodes tagged with the terms they flagged - Drupal 7

Here is how this can be done:

In the View, add a Relationship to the node's taxonomy term (using  "Content: Taxonomy terms on node")
Either add a filter criteria for the term, or add a contextual filter that would limit the terms to those flagged by the particular user.


How to change URLs of Mini-Calendar Block View?

In mini-calendar view go to advanced -> other -> Link display and change it


Add a custom line item type with custom fields when my module is active

As stated by @pcambra, the hook to define custom line items is hook_commerce_line_item_type_info.

The base key is used to build the name of some callback functions. If not specified, it defaults to the line item type name.

One of the possible callbacks is "configuration", and it is invoked when the line item is first detected by Commerce. In this callback is where you should create the fields/instances related to your line item type. Commerce already does it in commerce_product_reference module. See commerce_product_reference_commerce_line_item_type_info and commerce_product_line_item_configuration for reference.

Also, you can consult this blog post for some tricks to ease the creation of fields/instances.


You can just remove the default Display a translatable Add to Cart message action and add a custom message that you want to be displayed yourself.

You can do this at /admin/config/workflow/rules/reaction/manage/commerce_cart_add_to_cart_message.


problem with drupal_http_build_query output

You are getting that result because you build $result as an array whose values are array. Since drupal_http_build_query() contains the following code, the result you obtain is by design.

  foreach ($query as $key => $value) {
    $key = ($parent ? $parent . '[' . rawurlencode($key) . ']' : rawurlencode($key));

    // Recurse into children.
    if (is_array($value)) {
      $params [] = drupal_http_build_query($value, $key);
    }
    // If a query parameter value is NULL, only append its key.
    elseif (!isset($value)) {
      $params [] = $key;
    }
    else {
      // For better readability of paths in query strings, we decode slashes.
      $params [] = $key . '=' . str_replace('%2F', '/', rawurlencode($value));
    }
  }

You should change the code to the following one.

foreach ($querydata as $qvalue) {
  $key = 'mapField' . $i;
    $result[$$key] = $qvalue->data;
    $i++;
}


How to limit the list of nodes in a view based on a text field value?

Create a new view that displays content of all types.
Add your text field to 'Filter Criteria'. It looks something like this...

Content: My Text Field Name (field_my_text_field_name)
Select 'is equal to' and enter 'barcelona001' to the 'Value' field.
Press Apply (twice).
If you have the value already on some contents text field it should now display a list of matching content in the preview.

You would probably also benefit from contextual filters. Remember first to remove the field from 'Filter Criteria' if you added it earlier.

Choose 'Advanced' from the Views settings page. It should now show you 'Contextual Filters' setting.
Add your field.
Click Apply.
You can now write 'barcelona001' in the 'Preview with contextual filters' field.
It should display the result in preview.
See the 'Path' value in the views settings. You can go to that path and put whatever value you have used in the textfield after the path like this .com/my-page/

I hope this helps!


Order Status is Pending after Paypal Payment

Ubercart does not make orders completed on it's own. It seems to be a well known problem, already discussed on stackoverflow and on ubercart.org. It seems manually setting up Conditional Actions is a must in most cases.


How can I track download statistics for private files?

Give these modules a try
Download Count

The download_count module tracks downloads of private files attached
to nodes via the core upload or contributed filefield modules for d6
and private core file fields for d7.

File download count

An API for tracking file downloads. Recommended use is by using
file_entity's file/[file:fid]/download callback page. Basically the
difference between this and other file download tracking modules is
this module does not intend to track every single time the file is
viewed. It only wants to track when a file is actually triggered for
download. It is up to the site to implement links to the file download
URL.

AJAX Download Counter

This module uses AJAX to count file downloads. It's optimized for
medium to large sites (such as my own site, OpenGameArt.org) where the
total number of file downloads might be in the hundreds of thousands
or even millions. Using this module has some advantages and some
limitations versus other methods of counting downloads:


What is the correct core update workflow?

I presume that you are using drupal-composer/drupal-project as the basis for your project.  If not, take a look at that project, and compare it with yours.

Also, you said that you want to use composer to manage Drupal 8 dependencies, so I presume that you have selected your contrib modules via composer require drupal/devel rather than drush dl devel.

If you are doing all of these things, then you should use composer update to update Drupal core and all of your contrib modules.  As long as you retain your composer.lock file, composer install should not change the version of any of your dependencies.  You should not use drush pm-update at all.  It should not matter to you whether or not files in the core directory are updated or not, as this directory is managed by Composer.  You are better off not committing composer-managed directories to your repository, although you can if you wish.

Of course, you should run drush updatedb whenever composer update replaces Drupal core or any module.

To avoid getting development versions, set your minimum stability to 'beta' in your composer.json file using Composer stability flags.

If you are using drupal-composer/drupal-project to manage your site, then all of the root-level files such as README.txt, .htaccess and index.html become owned by your project. That means that you should check them in to your git repository; Composer will not update them, you must update them yourself when they change.  These files should change only rarely, but drupal-composer/drupal-project has a script to update these files.


How do I block google analytics from my development sites?

just add the following line in in hosts file in computers which you want to exclude analytics tracking:

127.0.0.1 www.google-analytics.com


How to display a Leaflet map in modal window?

I found similar issues either with Leaflet or Google maps, like this one here. So I have to reload or re-render the map after the modal window become visible. For this purpose I inserted this jQuery code which does the trick:

drupal_add_js('
jQuery(function($) {
$(document).ready(function(){
$(\'#myMap\').on(\'shown.bs.modal\', function(){
var map = Drupal.settings.leaflet[0].lMap;
map.invalidateSize();
});
});
});
', 'inline');


I would imagine that if your users can just refresh the page to become logged back in, that they're almost certainly not being logged out in the first place. Far more likely that they're being served a cached version of the page.

Consider this situation:

User visits home page as an unauthenticated user
Cache headers tell the browser to keep that page for at least x minutes before refreshing
User visits the login page and authenticates.
User re-visits the home page
The browser cache kicks in, and the user is shown the cached version of the home page they saw the first time round
User refreshes the page - the browser cache is cleared, and they now see the index page as an auth'd user

  There must be a logical explanation and definitive way to stop it, surely?

Absolutely there will be - but you need to identify which part of your setup is responsible for the problem. As described above, it's probably a caching issue, so that's where you debugging should concentrate. I've seen this sort of behaviour more often when a reverse proxy is in front of Drupal, so if you have one enabled, start debugging that first.

If you're not comfortable debugging caching issues in that manner, you'll really need to hire someone who is to do the job. It's not something you can do half-heartedly, or without a reasonable knowledge of caching in general (not just in Drupal). If you happen to have a Pantheon account, ask them about it - they plugged the same bug in their Varnish config some time back (I have no idea how though, didn't ask).

I'm not sure that any more specific advice can be really be given, without having access to the server. I'm by no means a caching ninja though, so maybe someone else will be able to offer a specific part of config you can change, test you can do, etc.


Does Commerce Kickstart distribution include "advanced search" capabilities?

Commerce kickstart includes the commerce search API module. http://drupal.org/project/commerce_search_api

Automatically created Search API db server, if none is found.
Auto-generated search index that includes all product display node types* and related product data.
Auto-generated facets for all node type categories and product attributes.
Optional integration with Search API Ranges (allowing for a price slider, for example).
Search API Filter class for product display node types* (allowing for an index composed only of product displays)
Facet API Filter class for removing facet items that do not change search results.
Facet API Filter class for hiding certain facets on the initial search (so that product attribute facets are only shown after the initial search, for example).


As @Clive said you can use hook_form_alter() or hook_form_FORM_ID_alter() and add extra submit handler to send email notifications.

function YOURMODULE_form_system_site_maintenance_mode_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'email_system_settings_form_submit';
}

function email_system_settings_form_submit($form, &$form_state) {
  // Add your email code here
}


Delete old columns from table using hook update

You can use function db_drop_field()

/**
 * Implements hook_update_N().
 */
function mymodule_update_7001() {
  db_drop_field('my_table', 'my_column');
}


Openlayers3 - Tiles not Loading - Failed to load resource: net::ERR_NAME_NOT_RESOLVED

You can find the solution with the patch, HERE.

MapQuest, which is the default map of Openlayers, doesn't work.
You need to switch to another map, e.g., Openstreetmap.


Using hook_query_TAG_alter to add 'OR' queries to EntityFieldQuery

Solution to using 'OR' queries with EntityFieldQuery:

The query, note the addTag() and addMetaData():

$query = new EntityFieldQuery();
$query->propertyOrderBy('created', 'DESC');
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'news')
    ->propertyCondition('status', 1);
if(isset($keywords)){
    $query->addTag('search');
    $query->addMetaData('terms', $keywords);
}
$result = $query->execute();
if(isset($result['node'])){
    $nids = array_keys($result['node']);
} else {
    $nids = array();
}
$news = node_load_multiple($nids);

Then, within a module or something, the hook_query_TAG_alter looks like:

function MODULENAME_query_TAGNAME_alter(QueryAlterableInterface $query){
    $terms = $query->getMetaData('terms');
    $words = "%".$terms."%";
    $query->leftJoin('field_data_field_subtitle', 's', 'node.nid = s.entity_id');
    $or = db_or()->condition('s.field_subtitle_value', $words, 'LIKE')->condition('title', $words, 'LIKE');
    $query->leftJoin('field_data_body', 'b', 'node.nid = b.entity_id');
    $or->condition('b.body_value', $words, 'LIKE');
    $query->condition($or);
}

Above example shows how to join custom field tables and query them using 'OR' along with title and body fields.


create a downloadable file after submit webform

This module may be used for your idea please use and try this module

Webform2PDF

The Webform2PDF Drupal module is an extension of the Webform module. It can be used to generate PDF document from the results of a form. The generated PDF document can be attached to the form summary e-mail sent by Webform module, or it can be downloaded from the /Results/ page. Different PDF templates can be set for each form. The templates can be formatted with HTML tags, and they can be edited with WYSIWYG Drupal module, making the template creation easy and the templates highly customizable. The output documents will be created by using these templates.


Views hook_views_data add multiple joins to custom table based on row condition

You can try code

file my_module.views.inc

/**
     * Implements hook_views_data().
     */
    function my_module_views_data() {
      $data['custom']['views_handler_custom_field'] = array(
        'title' => t('Custom views field'),
        'help' => t('Field custom handler'),
        'field' => array(
          'handler' => 'views_handler_custom_field',
        ),
      );
    }

file my_module.module

/**
 * Implements hook_views_api().
 */
function my_module_views_api() {
  return array(
    'api' => 3
  );
}

file views_handler_custom_field.inc

class views_handler_custom_field extends views_handler_field{
  function query() {

    $this->ensure_my_table();
    $alias = 'custom_table';
    $this->query->add_field($alias,'node_id');

    // Month, you can copy it
    $aliasNode = 'node';
    $definition = array(
      'table' => $aliasNode,
      'field' => 'tid',
      'left_table' => 'custom_table',
      'left_field' => 'node_id',
      'type' => 'LEFT OUTER',
    );
    $join = new views_join();
    $join->definition = $definition;
    $join->construct();
    $join->adjusted = TRUE;
    $this->query->add_relationship($aliasNode, $join,$this->relationship);
    $formula ="";
    $this->query->add_field(NULL,$formula,'node_id');

  }

  function option_definition() {
    $options = parent::option_definition();
    $options['alter']['contains']['alter_text'] = array('default' => TRUE);
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
  }

  function render($values) {
    var_dump($values);
  }
}

The API


try integrating the Views Send Module, the instructions specifically mention VBO:

  Views Send enables you to send mass mailing from a View.

Since you aren't able to install new modules, it could be done this way:

Create the view as a table of fields, include the email address as EMAIL PLAIN TEXT
add the VBO field, Save Content (you can choose anything you want, but this seems the least offensive)
add some css:

#views-form-email-test-page #edit-select {   display:none; }

This will hide the VBO button since we are overriding its functionality manually
add a header, Global Text:

<button type="button" onclick="emailUsers(); return false;">email users</button>

add a modified version (modified for view and field names) of this JS to your html.tpl.php, or drupal_add_js, or by whatever other means you want:

function emailUsers()
{
    var toField = '';

    jQuery('#views-form-email-test-page table tbody tr').each(function()
    {
        if(jQuery('.views-field-views-bulk-operations div input', this).is(':checked'))
        {
            toField += jQuery('.views-field-field-address', this).html() + ',';
        }
    });

    if(toField.length > 0) window.location.href = "mailto:" + toField;
    else alert('Please select at least one user to email!');
}

This all assumes:

the View machine name is name email_test
the View is a page
the field holding the email address is field_address

EDIT FROM OP:

  Thank you very much Geoff, your solution works very well, I've learned
  a few things and I hope it will be usefull for others in the futures,
  indeed I was quite surprised not to find anything when I searched
  befor posting. Since my email field was also a link I've used the
  following code

  tmp = jQuery('.views-field-field-applicant-email', this).html(); tmp2
  = jQuery(tmp.replace('mailto:','')); toField += jQuery(tmp2).attr('href') + ',';

  instead of

  toField += jQuery('.views-field-field-address', this).html() + ',';

  not very elegant may be (I'm not a programmer) but it works! for some
  strange reasons I cannot upvote your answer, sorry.


How can I create unique path alias for image styles?

Is a little difficult because image_style_url() uses internally image_style_path() who creates the path /sites/default/files/style/[style_name]/path/to/...
Maybe you can use File (Field) Paths module:

The File (Field) Paths module extends the default functionality of Drupal's core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.
In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

If you only want to change the path alias you can use hook_node_insert() or hook_insert()
/**
 * Implements hook_insert().
 */
function mymodule_node_insert($node) {
    // Set the URL alias
    if (empty($node->path['alias'])) {
        $node->path['alias'] = 'image/' . my_random_function();
    }
}


How to fetch records from entity base on only Day and month?

Here we are doing a LIKE query as the question stated that it wants to fetch record on basis of current month and day only not a year .

 $query= \Drupal::entityQuery('user')
     ->condition('field_dob','%'.date('m-d').'%', 'LIKE')
     ->execute()


Can the Devel page generation times be placed at the top of the page?

The devel_timer() function present in the devel.module file returns the page execution time for every page which is as below:

/**
 * Displays page execution time at the bottom of the page.
 */
function devel_timer() {
  $time = timer_read('page');
  return t_safe(' Page execution time was @time ms.', array('@time' => $time));
}

as the function is present in the module file(which is available on all pages) therefore you can call the function anywhere you want something like below:

$page_execution_time = devel_timer();
print $page_execution_time;

UPDATE: another way of doing it with the JS is to get the value of page execution time from the default wrapper and display it in the custom wrapper as below:

I have tried it in the custom block(whose format was FULL HTML) that I placed in the header and it was giving the correct result (as the page execution displayed in block was same as displayed at the bottom of page), however it would be good to move the JS code to JS file (for testing I have tried this).


The Menu Trail By Path module will accomplish this:

  Menu Trail By Path sets the active-trail on menu items according to
  the current url.

  For example if you are at yoursite.com/blog/category1/article1
  Menu
  Items with these paths will get the active-trail class on them and
  expand accordingly.

  blog blog/category1 blog/category1/article1


Flag lists visible for one authenticated user but not for others

I found a solution to this problem, although I can't say I fully understand why it was happening. Seems to be a case of too many relationships in the View, causing some type of conflict that appeared only in some cases. During the building phase I had added a batch of 6 relationships, trying to get it to work but ended up with more than were necessary. I eliminated them one by one and tested, until the truly necessary ones were identified. It really only needed 2: "Flag lists: User" and "(List user) Flags: User's flagged content (current_user_flag)."


Why use constuctor injection in controllers or forms?

As soon as you start to test MyController you will run into problems

The test harness must be able to instantiate the minimum amount of stuff  around your class to still be able to put it through its paces.

It is easier to mock up and inject a simple container.. rather provide \Drupal::service as it will rapidly spiral out of control and your test harness will have to provide a full drupal environment.

In more formal language you have just "tightly coupled" MyController to the drupal eco-system, and so you have made your code less reusable.


is it possible to have multiple image styles for one uploaded image in drupal 8

You can reuse images using different image sizes - as far as I am aware there isn't a way to do this using the Drupal Field UI - but you could (for example) override the node display using views for more customisation including the ability to use the same image field using multiple image styles.


Maybe it's a cache issue, so you can try to externalize your script and call it with random parameter

<script type="text/javascript" src="path/to/my/script.js?itok=1561313215" defer="defer" async></script>

You can generate a random value with php with microtime by sample

Try it and let us know if helps you


This is not so much an issue of suing Apache Solr as it is one of working with the database query system.  To do what you want you will have to become very familiar with the Views module.  I recommend watching the nodeone.se series 'Taming the Beast'

Views is a UI for making sql queries.  You create a view definition with a path you assign to your look-up page.  It will include filters to sort content by types.  The various categories of information at Drupal.org are basically different content types. The various displays lists etc. used to provide the information can be provided by a variety of modules.  I would recommend exploring Panels and Page Manager to provide and display the information.  Nodeone.se also has an excellent series called 'Learn Page Manager' that can help you master those issues.

If you want custom functionality and know your way around PHP you may want to look at the Drupal Forms API, the Search module, and Search API module for additional functionality in creating customized searches and forms.


Is it possible to change fieldset title if collapsed with #states

It is true that there were some issues with #states and fieldsets, such as #states can't hide/show fieldsets, but in your case the code doesn't work because #title is not an handled state, and #collapsed is not a handled state for the remote condition.

The list of the implemented states is given in drupal_process_states():

enabled
disabled
required
optional
visible
invisible
checked
unchecked
expanded
collapsed

The states used for the remote conditions are the following:

empty
filled
checked
unchecked
expanded
collapsed
value

It would also be hard to implement that, as the state needs to be boolean, and the remove condition says the value of the state for the other form field.

For example, if foo is a select list, the state for a form field could be the following one.

'#states' => array(
  // Show the settings if 'bar' has been selected for 'foo'.
  'visible' => array(
    ':input[name="foo"]' => array('value' => 'bar'),
  ),
),

This state would make the form field visible when the value selected from the list is bar.


How to resolve the error "Base table or view not found"?

You need to switch the database back before it carries out any operation that requires the Drupal database.

// Switch to your custom database.
db_set_active('mykey');

// Work with that database (select/insert/update).
...

// Switch back, before you use the Drupal API again
db_set_active();


Create order in drupal commerce programmically with product cost change in order

finally this is my solution for do this job

before I create a product, save it product id,  in my custom function I change it's cost and add to order

global $user;

  // Sanitize just in case
  //862 create by myself as custom porduct
  $product_id = 862;
  $price=  floatval($form_state['values']['field_suggest_your_price']['und'][0]['value'])*100;
  // Load product
  $product = commerce_product_load((int)$product_id);
  $product->commerce_price_usd["und"][0]["amount"]=$price;
  commerce_product_save($product);
  if((empty($product->product_id)) || (!$product->status)){
    drupal_set_message(t('Invalid product id'));
    drupal_goto(); // frontpage
    return FALSE;
  }
//$product->commerce_price["und"][0]["amount"]=$price;
//$product->commerce_price_usd["und"][0]["amount"]=$price;
//dsm($product);

  // Attempt to load existing order for user from session
  $order = commerce_cart_order_load();
  if(!$order){
    $order = commerce_cart_order_new($user->uid);
  }

  // Save new order to get order id
  if(empty($order->order_id)){
    $order->revision = FALSE;
    commerce_order_save($order);
  }
  $order_id = $order->order_id;

  // Wrapper for easy field access and adding line items, order passed by reference
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  // Create new line item based on selected product
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  // Save new line item to get line item id
  commerce_line_item_save($line_item);
  // Add line item to order wrapper
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save order with new order number and line item added
  $order->revision = FALSE;
  $order_wrapper->save();

  if(!empty($order->order_id)){
    drupal_set_message(t('Thank you, your %product is ready for checkout.',
                         array('%product' => $product->title)));
    drupal_goto('checkout/'.$order->order_id);
  }else{
    drupal_set_message(t('Sorry, there was a problem building your order. Please try again later.'), 'error');
    drupal_goto(); // frontpage
  }


I found the answer! I was using latest stable release 7.x-2.0-rc1. It does not support i18n but they add a sub module which its name is entityform translation in dev version (7.x-2.x-dev). Once this module is enabled, a translate link appears on the table list of entity form types.


Sounds like i18n_panels would be overkill. You can do it like this:

/**
 * Preprocess panels panes to translate their title.
 */
function MY_THEME_preprocess_panels_pane(&$variables) {
  $pane_config = $variables['pane']->configuration;
  if (!empty($pane_config['override_title'])) {
    // Translate pane title via t().
    $variables['title'] = t($pane_config['override_title_text']);
  }
}

Or, if appropriate, just:

/**
 * Preprocess panels panes to translate their title.
 */
function MY_MODULE_preprocess_panels_pane(&$variables) {
  $variables['title'] = t($variables['title']);
}

The first will process the title only if defined in the pane settings as a title override. The second will translate the title regardless of whether it's the override title or original title from elsewhere.

Tested under Drupal 7, the same or similar approach would probably work for Drupal 8.


Upgrading procedures and what essential directories to copy over?

As Kevin has stated in the comment, the "official" procedure should be found here, and it's ever evolving. I don't believe any safe automated way currently exists 100% of the time (such as with Drush/Drupal Console/Composer/etc.)

In short, upgrading D8 sucks. At least as far as I can tell. If you plan on using composer with it, you can't rely on "drush up", lest you want it all to get wiped, etc. (Actually, I'm kind of confused as to why you're not using "drush up" on your D7 sites, since you clearly have drush installed.)

In short, the process is still very similar to what you're already doing with D7. The file structure has changed in D8 though, and you need to be aware of things like modules/themes/libraries being in the root directory, rather than the sites/ directory. All that is covered in the documentation.


Adding rating and commenting to individual fields

The best way to solve this would be to use the Field Collection module. All you would need to do is create a field collection with a rating and an image in it, and every time a new image is added, there would be a new rating next to it. The latest D7 version has come a long way and should work for what you need.


This is bypassable by cloning the views you need from the four views that the module provides, disabling the original views, and doing all your work in your clones which are 100% trackable.


You can do it in hook_views_pre_render() like this:

/**
 * Implements hook_views_pre_render().
 */
function MODULENAME_views_pre_render(&$view) {
  if ($view->name == 'VIEWNAME') {
    if (!user_is_logged_in() && !empty($view->field['FIELDNAME']->options['alter']['path'])) {
      $view->field['FIELDNAME']->options['alter']['path'] = 'user/login?destination=' . $view->field['FIELDNAME']->options['alter']['path'];
    }
  }
}

Where in this case I would say 'title' is your FIELDNAME.

This will, if the user is logged out, replace whatever you have for your link in the rewrite settings, with a link to the login page, with your original path as the query destination, which will be used to return you to that page after the login form is submitted.

Also, there is the modal_forms module, which might be worth trying for a pop-up solution.  However then you need to take them to the comment reply page after the modal form closes.


In general, it would be a bad development practice. The whole purpose of t() is to provide human-readable translated text. As such, it can't be guaranteed as consistent switch logic because the translation context might differ.

In practice (e.g. a input button submit value on a basic form with little-to-no translation contexts), you might get away with it, but you're adding technical debt; if your application grows and other features start to rely on the switch logic, it's only a matter of time before the inconsistent logic will bite you.


Run a check on every page load programmatically

(I'm assuming Drupal 6)

Looking at bootstrap.inc, hook_boot is called on all pages, as long as agressive caching hasn't been turned on.

At this point the global $user variable should already exist (page_get_cache, which is called before hook_boot, makes use of it for example). module.inc has also been included, so you can use the functions included in that file to check for module existance and load them if necessary.

So, hook_boot looks like a good choice.


Alter all images styles to add a particular effect before all others?

Yes,  you can do this with hook_image_styles_alter.

I'm not so sure it's a great idea since you'll be enforcing adding your effect no matter what the user might try to configure via the interface, but it will definitely let you do what you want to do.


Webforms: pages 1,2 of 4 not being displayed

I was looking in the wrong places...

The element editor in Webforms includes an Access tab. For the pages that were not being shown I had removed all the permissions, which included the permissions of ‘Administrator’, the user I was logged in as. So – obviously – those pages were not shown.

Duuhh.


Inside your view under the advance tab

Click on "no result behavior"

Chose " Entity: Rendered entity "

Add a label

Entity type "node"

Entity id "enter the node id" for the node you want to show if no result was found.

chose appropriate view mode.

here an export of a view that returns node 1 if you have no articles in your system

$view = new view;
$view->name = 'retrun_homepage';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Retrun homepage';
$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['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* No results behavior: Entity: Rendered entity */
$handler->display->display_options['empty']['entity']['id'] = 'entity';
$handler->display->display_options['empty']['entity']['table'] = 'entity__global';
$handler->display->display_options['empty']['entity']['field'] = 'entity';
$handler->display->display_options['empty']['entity']['label'] = 'Show homepage';
$handler->display->display_options['empty']['entity']['empty'] = FALSE;
$handler->display->display_options['empty']['entity']['entity_id'] = '1';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);