Access Denied on file attachment when node state is Draft in Workbench

When using the private file system file_file_download() only checks access for files attached to the current revision of an entity (via file_get_file_references()).

This is to stop users who have access to view the node from viewing files attached to old revisions (that might contain out of date files), and other similar things.

If there are no current revisions that contain that file it returns NULL, which then in file_download() means that get access denied.

See a related drupal core issue: https://drupal.org/node/1453138
The D8 version of that issue is: https://www.drupal.org/node/1452100

In theory, you should be able to implement a hook_file_download() that checks all revisions by essentially copying file_file_download, but making file_get_file_references() return for all revisions.

The problem with that solution is it can introduce a security hole, which is that users who have access to view the published version of the node can also now view files attached to other revisions of the node, which depending on your use case may or may not be an issue but since you are using the private file system in the first place I assume it might be a problem.

To avoid that, you could then implement hook_file_download_access(), which does more complex access control than just calling node_access() like the node_file_download_access() function does.
In that hook you would want current revisions to run through node_access() and non-current revisions to use extra access control, like checking the users workbench permissions or node creation/editing permissions.


Customize Commerce Event Ticket PDF content

You can customize the PDF content by using the HOOK function <YourCustomModule>_commerce_event_ticket_pdf_alter($pdf, $ticket, $context) or for simpler manipulation use <YourCustomModule>_commerce_preprocess_commerce_event_ticket_pdf_info(&$variables).

Take a look at:
https://www.drupal.org/node/2407879 and https://www.drupal.org/node/2269659

It's also possible to replace the theme function by altering the theme registry:

function <YourCustomModule>_commerce_theme_registry_alter(&$theme_registry) {
  if (!empty($theme_registry['commerce_event_ticket_pdf_info']['function'])) {
    $theme_registry['commerce_event_ticket_pdf_info']['function'] = '<YourCustomModule>_commerce_commerce_event_ticket_pdf_info'; // Your function to alter the content...
}

You should also have a look at the repository on GitHub -> gausie/commerce_event_ticket


DS link to content - how to change the link?

Maybe display suite extras can help you achieve this with a combination of tokens.

After you enable the Display Suite Extras you could go to admin/structure/ds/fields and create a new code field.
Label your code field and tell you will be using tokens.

3 In manage Display of your content type disable the title and enable your new field that it was created by Display Suite Extras.

This tutorial helped me in doing something similar that you are trying to do.
Customize ULR/link display suite and tokens . I hope it helps :)


node aliased path as views contextual filter

First I have created a view that uses contextual filter content ID to filter the results by "node id" and can be called like this

/nodefilter/[NID]

After I made sure the view was working I modified the content ID contextual filter adding default query paramenter named url under WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value

then in a custom module used the views api hook_views_pre_view as follows

use Drupal\views\ViewExecutable;
function MODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if($view->id() == 'view_machine_name'){
    $url = \Drupal::request()->query->get('url');
    $path = \Drupal::service('path.alias_manager')->getPathByAlias($url);
    if(preg_match('/node\/(\d+)/', $path, $matches)) {
      //$node = \Drupal\node\Entity\Node::load($matches[1]);
      //$nid = $matches[1];
      $args[0] = $matches[1];
    }
  }
}

Now the view works with NID or the url parameter

/nodefilter/[NID]
/nodefilter/?url=/category/path-to-article


How do I programmatically get the URL of an entity referenced media image field using on a custom_preprocess_html() hook on THEME.theme?

ok, here is what worked for me. After digging through stack overflow, found that I was missing the ImageStyle and this resulted in not rendering the url.

I added

use Drupal\media\Entity\Media;
use Drupal\image\Entity\ImageStyle;
use Drupal\media_entity\MediaInterface;
use Drupal\node\Entity\Node;

and then on preprocess function, I loaded the media using the target_id that I got form the $node->field_image->target_id;

Then, I loaded the ImageStyle using

$media = Media::load($image_id);
$media_url = ImageStyle::load('TYPE_OF_CROP')->buildUrl($media->image->entity->getFileUri());
$variables['media_url'] =  $media_url;

Hopefully this helps people.


How to show the description of primary links

The answer in your previous question should help you with this. The $link['description'] will contain the description you set in the drupal menu item via the ui. You can then just print this below the title to achieve your example.

As a side note, you would be best amending your original question rather than starting a new one which is so similar.


Possible to create fields without admin?

Yes. Since fieldable things in D7 are called "bundles", you essentially 1. create the field and 2. attach it to the bundle that uses it (could be a content type, etc.) I wrote this function to quickly create and attach fields in my module's .install file:

function _add_field_to_bundle($field_name, $cardinality, $type, $label, $entity_type, $bundle, $field_settings=array(), $instance_settings=array()) {

  $new_field = array(
    'field_name' => $field_name,
    'cardinality' => $cardinality,
    'type' => $type,
    'settings' => $field_settings,
  );
  field_create_field($new_field);

  $field_instance = array(
    'field_name' => $field_name,
    'label' => $label,
    'entity_type' => $entity_type,
    'bundle' => $bundle,
    'settings' => $instance_settings,
  );

  field_create_instance($field_instance);
}

To use this function to attach a thumbnail image field to a (node) content type:

_add_field_to_bundle('field_thumbnail', 1, 'image', 'Thumbnail', 'node', 'content_type');


Views > Exposed Filter > How to disable output of options that aren't attached/used by a node

The concept's the same in Drupal 8 but the access of properties and handling is a little different from what's done on D7. Here's a working example of 3 exposed filters dependent on each other to allow only values available based on prior selections.

Tips:
- View is built with page that has exposed form in block checked to yes.
- Enable master display, make sure filter identify of exposed filter is same
- Use BEF (better exposed filters) for menu select and autosubmit
- See code comments

This is for D8:

/**

* @file
 * Provides functionality for handling exposed filters
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\ResultRow;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\views\Entity\View;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Entity;

/**
   * Implements hook_views_exposed_form_alter().
   *
   * alters exposed filter for equipment selector to limit filtered results in a new view
   */
function ahern_equipment_selector_form_views_exposed_form_alter(&$form,  &$form_state){
    if ($form['#id'] == 'views-exposed-form-ahern-exposed-filters-page-1') {
        // Get whatever values selected by user in all menus
        $input = &$form_state->getUserInput();

        // Form fields have given/arbitrary name from Filter identifier in Exposed filter settings
        $selected_what_moving = $input['moving'];
        $selected_where_working = $input['where'];
        $selected_height = $input['height'];

        // Again, form fields have given/arbitrary name from Filter identifier in Exposed filter settings
        // NOTE: make sure also match Filter identifier in Master display
        // Also keep in mind that any view duplicated/cloned from main view should be disabled as
        // it can/will affect results
        $form['moving']['#options'] = _get_associative_array_from_view(
         'ahern_exposed_filters', // viewi id
          'default', // view dsplay id
          $selected_what_moving,
          'moving_chosen'
        );

        $form['where']['#options'] = _get_associative_array_from_view(
         'ahern_exposed_filters', // viewi id
          'default', // view dsplay id
          $selected_where_working,
          'where_chosen'
        );

        $form['height']['#options'] = _get_associative_array_from_view(
         'ahern_exposed_filters', // viewi id
          'default', // view dsplay id
          $selected_height,
          'height_chosen'
        );
    }
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $contextualFilter, $menu_chosen){
//ksm($contextualFilter,'context filter');

  $associativeArray = array();
  $associativeArray['All'] = t('- Any -');
  $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);

  foreach($viewResults as $viewRow) {

    switch ($menu_chosen) {
    // views_get_view_result returns rows with original field name so don't use filter identifier name to acceess, use field name
        case 'moving_chosen':
            //ksm($menu_chosen, 'target menu to filter to');
            $term_name = $viewRow->_relationship_entities['field_what_are_you_moving']->getName();
            $term_id = $viewRow->_relationship_entities['field_what_are_you_moving']->id();
            if (!in_array($term_name,$associativeArray)) {
                $associativeArray[] = $associativeArray[$term_id] = $term_name;
            }
            break;

        case 'where_chosen':
            $term_name = $viewRow->_relationship_entities['field_attr_where_are_you_working']->getName();
             $term_id = $viewRow->_relationship_entities['field_attr_where_are_you_working']->id();
             if (!in_array($term_name,$associativeArray)) {
                $associativeArray[] = $associativeArray[$term_id] = $term_name;
            }
            break;

        case 'height_chosen':
            //ksm($menu_chosen, 'target menu to filter to');
            $term_name = $viewRow->_relationship_entities['field_what_is_the_working_height']->getName();
            $term_id = $viewRow->_relationship_entities['field_what_is_the_working_height']->id();
            if (!in_array($term_name,$associativeArray)) {
                $associativeArray[] = $associativeArray[$term_id] = $term_name;
            }
            asort($associativeArray);
            break;

        default:
            break;
    }

  }

    $associativeArray = array_unique($associativeArray);
    return $associativeArray;
}


How to extend Views Plugin ViewsSelection.php to have $form_state

There is no form state, at least not with autocomplete. And since the same code is designed to work with autocomplete and other widgets, it can't rely on form state anywhere.

If you have autocomplete you can possibly pass in the settings in the entity_autocomplete form element which should be passed to your plugin. Not sure about other widgets, you might need your own widget to be able to do that.


How to implement a horizontal set of translation links for every node?

Maybe Displaying and configuring a drop down using Language Switcher Dropdown helps to achieve what you're trying to do with this module anyhow.

If not then the answers to the question about How to theme language translation links in Drupal? may help to actually answer your qestion. Though that question is for D6, and hence its answers might need some review to also make it work in D7. Here is the relevant part of it that might do the trick:

$node = menu_get_object();
if ($node->links) {
  print theme('links', $node->links);
  }


How to display views exposed filter as links when the filter is a date field with year granularity?

You are almost there: you have to group your results by the year field.  In the settings of your display format just pick a grouping column:


theming field collection in node add form

You'll need to hook into the field collection entity on insert, and add a callback function to trigger the new row to appear via ajax in your table.

Check out field_collection.api.php in the field collection module for a full list of field collection api calls/methods.

Also, you may find the responses to this previous post as a good indicator of the direction to take: Perform actions on field collection insert or update


Show View When Empty and Hide View When Not Empty!

Limit submissions to "1 ever" when you configure the Webform. I'm not sure if Webform Block module would automatically hide the block if the form is not shown, but it should. Webform will not show the form if it cannot be submitted.


I think there are two approaches you could take here. In the past I've successfully extended the InlineParagraphsWidget field widget in order to alter the form display for Paragraphs. I think that hook_ajax_render_alter() might also be a good solution.

I have not used hook_ajax_render_alter(), but I have successfully extended InlineParagraphsWidget for the purpose of altering the AJAX response. Specifically, look into overriding the ::addMoreAjax() and ::formElement() methods.

Below is a simplified version of the ::addMoreAjax() callback that I used. Use $insert_element = parent::addMoreAjax($form, $form_state); to get a reference to the triggering element.

public static function addMoreAjax(array $form, FormStateInterface $form_state)
    {
        $insert_element = parent::addMoreAjax($form, $form_state);

        // TODO: This is NOT the cleanest way to find the wrapper ID.
        // Find a cleaner way to get these values.
        $wrapper_id = explode('"', $insert_element['#prefix'])[1];
        $pos = strrpos($wrapper_id, '--');
        $wrapper_id = '#' . substr($wrapper_id, 0, $pos);

        // If you needed the field name.
        $field_name = end($insert_element['#parents']);

        $response = new AjaxResponse();
        $response->addCommand(new InsertCommand($wrapper_id, $insert_element));
        return $response;
    }

You will probably also want to provide validation by overriding ::elementValidate().

You will also likely need to implement hook_field_widget_info_alter() in order to make your new widget active.

function my_module_field_widget_info_alter(array &$info)
{

    $info['entity_reference_paragraphs']['class'] = MyCustomInlineParagraphsWidget::class;
    $info['entity_reference_paragraphs']['provider'] = 'my_module';
}

Happy coding!


Deleting Aliases unchecks 'generate automatic alias'

Okay, never mind. I spent over an hour with this repeatedly happening, dug through pages full of people having the same issue and the opposite issue, flicked persistant state on and off, and it suddenly started working in the time it took me to write this. Caching I guess


How to alter add content form to include a new setting panel?

Your code works perfectly for me; dropped straight into a form alter hook I get the following on the article add page:

There are 3 reasons I can think of that might explain why you're not seeing the new tab:

You haven't cleared Drupal's caches since implementing the new hook (probably the most common cause for problems like this).
Your module isn't actually called "mltag", in which case your form alter hook will never actually be run.
Your code is in a file other than the main .module file. Hooks declared in files that are not explicitly included from the .module file will not necessarily be found when Drupal is updating the module_implements cache.


How to add a comment using service api when uuid_service module is enabled

First, when creating a comment you must use POST. Here's an example:

POST: ?q=[my_endpoint]/comment.json

{
  "subject":"Testing...",
  "comment_body":{"und":[{"value":"Hello world..."}]},
  "nid":"123"
}

Secondly, from my understanding the uuid will automatically be generated server side, so you should not need to send it up to Drupal. And lastly, you use the PUT http method to update a comment, and in that case you can send along similar JSON, but include the cid value (e.g. 456) and exclude the nid value in the JSON object, and change the URL path to ?q=[my_endpoint]/comment/456.json

{
  "subject":"Updating...",
  "comment_body":{"und":[{"value":"Hello world again..."}]},
  "cid":"456"
}


You must use the commerce_cart.cart_manager service instead.

So $this->cartManager->emptyCart($cart); should do the trick.

Update: The reason why you get an error is because you try to call emptyCart on $cart then it's NULL.

You must wrap the line where you empty the cart in an if statement, like this:

if (!empty($cart)) {
  $this->cartManager->emptyCart($cart);
}


Drupal in redirected site folder not working

Just add a rewriteBase to your .htaccess file

RewriteBase /subdirectory

Note that this goes into the .htaccess file in the “subdirectory”, not your website root .htaccess file!


How to migrate content of one content type to another content type

You can use Feeds module or Migrate module. First you export the Type A into a CSV for example, then build an importer that imports data into the Type B and use the exported CSV file.

Be careful you choose the correct bundle for the importer (Type B) and to create new nodes. Check that your Unique field really is unique.


Working with flags u should use "-", not underscores and there are should be class names started with flag-: flag-false-negative-flag-passed


Run feeds importer from outside the site

Since version 7.x-2.0-beta3, Feeds has Drush support. You could use the following command to trigger an import (where 'my_importer' is the machine name of your importer):

drush feeds-import my_importer

If the importer is attached to a content type, specify also the feed
node with the option '--nid':

drush feeds-import my_importer --nid=2

Note that a source for the importer in question must exist*. So you need to have gone through the import form at least once.

You could write a shell script that executes the drush command and that is triggered when the url is requested.

*The drush command 'feeds-import' has more options, allowing you to perform an import even when no source was created yet. But I don't think that applies in your situation. See https://drushcommands.com/drush-7x/feeds/feeds-import for more information.


Different front page for anonymous users and authenticated users

You can achieve this using Context Reaction: Front page module, which extends the great Context module.

Create a new context and:

Add a condition for User role
Add a reaction Front page putting the path for the roles you want to affect.

Save the context and all should be done.


How to set a value on a field collection using entity metadata wrapper

I found the documentation for field collections confusing as well.

Field collections need their own entity metadata wrapper. So, the following code would work for your example:

$collection = entity_create('field_collection_item', array('field_name' => 'field_user_location'));
$collection->setHostEntity('user', $user);
$fc_wrapper = entity_metadata_wrapper('field_collection_item', $collection);
$fc_wrapper->field_land_phone->set($object['Phone Number']);

I hope that helps for anyone else banging their heads over this.


How to hide the "trimmed version" from the preview page?

You tried CSS?

.preview h3 , .preview .node.node-article.node-teaser {display: none}

In my case the content type is an article and worked.


Drupal 7 views Contextual filters with Page & Blocks

Contextual filters works well for any display type that has a path. A path makes it easy for views to determine what information should be passed into the contextual filters.

The problem with blocks is that they don't have a path. Views does not look at the current url and automatically pass values to the filters because it has no idea which parts of the url to use.

You can get around this by using Default Values (or page manager/panels, but that's a whole other topic).

In the settings for your block contextual filter, you will want to override the configuration and select Provide a default value. Under type choose Raw value from URL and set the Path component to 2 (the path component will be different depending on your URL, but for domain.com/items/node-title the component is 2)

When you assign your block to a region, you probably want to set the allowed paths so this block won't show up anywhere else. The path component is "hard coded" so if your path ever changes you will need to adjust it.


How to create a read-only flag that can only be used by an admin to actually flag nodes?

Try setup Flag as "global flag" and then in "Flag access" setup "Roles that may use this flag" check-boxes only for Admin.

If in this case flag will not be shown for other users - you need create script that get flag value for each node and display this info.

$flag = flag_get_flag(FLAG_NAME);
$node->flag_value = $flag->get_count($node->nid);


Problem with "content access" (module) and permission "View own unpublished content"

I've just found some interesting information about my problem. Maybe it will help someone else.

In fact, it's seems impossible to resolve this problem in a proper way.

There is a very good article about that: Access Control module prevents View of user's own unpublished content, and an issue on drupal.org

If we want to see our own unpublished content in workbench, we have to go in view and make:

Go to query settings
and check Disable SQL rewriting option

It's not very good solution like he said but we can't do anything else for now.


drupal zen theme using sass - sub folder dont get regenerated

compass watch should only need to be run from your subtheme folder.  Files in the components and layout folders should use partials (files beginning with underscore).  Then you have to make sure to use @import "components/fixed"; inside your styles.scss for each partial you want to include.

When compass compiles the styles.scss file, the partials that you have @import's for will be automatically included in style.css


What's the equivalent of cache_clear_all()?

You can use Cache api. It would be somthing like

\Drupal::cache('bin')->invalidateAll();

Or if you want to remove the entries and not just invalidate them:

\Drupal::cache('bin')->delete('variables')

where bin is a valid cache bin such as menu, render, page ...etc.


I think the best way is to use Aggregator, you dont have to map into a new content type RSS Feeds like on Feeds module.

Follow this:

Active Aggregator core module.
Add a new chanel per each feed URL under /admin/config/services/aggregator, defining a name and time for importing by cron.
Create a view with a display of type "Aggreator", Here you can make a comun view, ordering by date, limiting by 1 result, and filtering by each channel.

I hope this help.


Using theme_get_setting getting empty value

Change the type of image input to managed_file. Check updated code below:
$form['mythemename_settings']['loaderImage'] = array(
  '#type' => 'fieldset',
  '#title' => t('Loader Icon'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);

$form['mythemename_settings']['loaderImage']['loader_img'] = array(
  '#type' => 'managed_file',
  '#title' => t('Upload Loader Icon Image'),
  '#default_value' => theme_get_setting('loader_img','mythemename'),
  '#description' => t("Upload your desired loader icon."),
  '#upload_location' => 'public://images/',
);

Values of theme settings are stored in variable table. Check theme_<THEME_NAME>_settings under name column & value is stored as serialized array in value column.
Update 1
To get file object use following sample:
$file = theme_get_setting('loader_img','tmhgs');
$file = file_load($file);


How to create multiple slideshows on my front page?

I would recommend using Views Slideshow as it is a very easy to install and configurable module if you are used to using Views in Drupal.

All you would have to do then is intwine your logic, looping through users and their associated uploaded images and place the block on your front page.

Here is a tutorial for drupal 8 and drupal 7 using views slideshow:

I hope this helps.


Boolean field: hide (in display) if unchecked

OK, so it is possible and actually rather simple. Here's how I did it in the end:

Edit the field's settings:
"value if checked" -> use the text you want to see displayed when checked
"value if unchecked" -> leave empty

And then under Content type > Manage Display, hide the label for this field.

This way, only the value of this field will be shown.
Since the value when unchecked is empty, nothing will be shown when the field is not checked.


Back button gets stuck in a loop after submitting a new comment

I did end up fixing it by using Ajax comments


How can I theme individual fields in a row?

You are on the wrong track. If you want to rewrite in twig how the fields are built to a row, you have to use the template views-view-fields.html.twig.

But the simplest method would be to rewrite the result of the fields in views ui. This is the option "Override the output of this field with custom text". If you apply this on the last field and hide all previous fields with the option "Exclude from display", you can see the twig variables for all fields in "Replacement patterns" and you are able to rewrite the complete row like the example you have shown in the question.


After taking a look at the php-mysql package for Buster it appears that the file is included with that package at /usr/share/php7.3-mysql/mysql/mysqlnd.ini.
I'd say that installing the virtual package should net you the module / driver you need. You'll likely need to enable the mysqlnd module and restart your FPM pools.
You can verify that the extension is loaded by
php -v # to get the version
php -i | grep mysqlnd

You'll probably want to enable it for cli as well as FPM.
Good luck!


I don't think there is an option to sort the exposed operators.

You can do it with a custom module using hook_form_alter().

Example:

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

  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'view_name') {
    unset($form['field_name_filter_op']['#options']['empty']);
    unset($form['field_name_filter_op']['#options']['not empty']);
  }

}

You can find the form details using "dpm()" from devel module.

dpm($form_id);
dpm($form);
dpm($form_state);


How to fetch customer shipping information from rule component?

A couple of things, you actually have two rules:

The first is the event rule that loops through the products
The second is the component rule that fires off each email

  Interesting side note, given your setup, you will likely be sending an email per product and not per product creator.

To get the shipping address in rules when you have access to an order entity, you simply need to add a condition "Entity has field" and check that the "line-id:order" has the customer's shipping profile field (by default this condition looks like this):

Here's an animated gif displaying the process:


I think your solution here is to also include user/* and messages/* in your list.

So the whole list would read:

node/78
node/19
user
user/*
messages
messages/*


How to write an Webservice API Wrapper the drupal 7 way

The standard solution is to use the Services module, which provides hooks for you to define your own endpoints.

There's also Restful Web Services which has similar functionality but is geared more towards entity API integration.

If you literally want to write your own API from scratch then just use your best judgement - there aren't any Drupal-specific standards for that.


Why is the CSS in my sub-theme not working?

The my_theme.libraries.yml isn't indented correctly.
global-styling:
  css:
    theme:
      css/my_theme.css: {}
  js:
    js/my_theme.js: {}


programmatically add body classes with template preprocessing

You can add your class to body element by adding THEMENAME_preprocess_html() to your template.php
Like :

function MY_THEME_NAME_preprocess_html(&$variables) {
  // Compile a list of classes that are going to be applied to the body element.
  // This allows advanced theming based on context (home page, node of certain type, etc.).
  $variables["classes_array"][] = "blue-bg";
  $variables["attributes_array"]["class"][] = "blue-bg";// For Omega based themes
}

Refer this link for more details.


Display Only the Product Add to Cart Button

Yes the link above resolved my question: Where is the "add to cart" configuration?.

There is a sub-menu link that I was missing.

This allowed me control of the display of the form items on both the product and node level. With this I am able to choose to show the variations and quantity fields. Thanks Patrick Kenny!


How can I show selected items without exposed filters?

Alternatively can you use "Promoted to front page" under "Publishing options" while adding content. This content will be the contents you need as important and will be visible to users.

Below that your view with exposed filter will be shown.
In View "Filter criteria" you can ADD "Content: Promoted to front page" option to show the non promoted contents, and also exposed filters.

You can apply this logic in your content type also, if you need specific fields such as "Mark as Important", give it some Boolean value and select it in filter criteria as mentioned above. If not can be added from "Contextual filters".


Print the error message returned from the SQL query

Try to follow below code..

   try {
        $query = db_select('node', 'n');
        $query->fields('n', array('nid'));
        $nid = $query->execute()->fetchField();
        drupal_set_message(t('Print your sucess message here'));
      }
    catch(Exception $e){
        drupal_set_message(t('Print your error message here'),'error');
    }


Flat Shipping price per product using Drupal Commerce

If you are using commerce shipping 1.x, you should do something like this:

Disclaimer, this is written by memory.

This is based on two fields on the product,

field_shipping_type containing the shipping type
field_flat_rate containing the actual rate for the product.

Create a custom module and add a folder for the shipping plugin, fx plugins/quotes/custom_shipping
Create the custom_shipping.inc with the plugin definition.

<?php

$plugin = array(
  'title' => t('Custom shipping'),
  'description' => t('Descriptive text.'),
  'handler' => array(
    'class' => 'CustomShipping',
    'parent' => 'quote_base'
  ),
  'price_component' => array(
   'title' => t('Shipping'),
   'display_title' => t('Shipping'),
   'weight' => -40,
  ),
);

Create the actual shipping logic in the CustomShipping.class.php file in the same dir. All you need is something like this:

class CustomShipping extends CommerceShippingQuote {
  public function calculate_quote($currency_code, $form_values = array(), $order = NULL, $pane_form = NULL, $pane_values = NULL) {
    $order = $order ? $order : $this->order;
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $price = 0;
    // Loop through the products, and add costs.
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      switch ($line_item_wrapper->commerce_product->field_shipping_type->value()) {
        case 'free':
          break;
        case 'flat_rate':
          $price += $line_item_wrapper->commerce_product->field_flat_rate->amount->value();
          break;
        case 'call_for_details':
          // Call for details
          break;
      }
    }
    return array(array(
      'amount' => $price,
      'currency_code' => $currency_code,
      'label' => t('Custom shipping method line item label'),
      'quantity' => 1,
    ));
  }
}


Is there a way to clone a content type and its fields?

The best way to do this is the entity_clone contrib module.  I downloaded it, installed it, hit the clone button and all of fields and form settings were copied to the new content type.  It worked very well.


Get Organic Group roles of the current user

Here is the data structure I ended up with:

Array
(
// Index 0 will be site-wide rid and roles
[gid] => Array
    (
        [rid] => 'OG Role Label'
    )
)

Here is the code I hacked together to get it to work. I placed this code into a custom module but I can't seem to get the function to get called from the desired location. I have a file ../sites/all/themes/THEME/templates/includes/toolbar.php. The function call is inside this file but for some reason is never executed. Any ideas on how to make the function call correctly??

function _MYMODULE_get_user_roles($scope=ALL) {
    global $user;
    $user_roles[]=$user->roles;

    if ($scope==ALL || $scope == SITE_ONLY)
    {
        $user_roles['SITE'] = $user->roles;
        switch (true) {
            case in_array ( 'System Administrator', array_values ( $user->roles ) ) :
                //drupal_set_message ( '
Load System Administrator Toolbar
' );
                break;
            case in_array ( 'Site Account Admin', array_values ( $user->roles ) ) :
                //drupal_set_message ( '
Load Site Account Administrator Toolbar
' );
                break;
            case in_array ( 'Site Content Admin', array_values ( $user->roles ) ) :
                //drupal_set_message ( '
Load Site Content Administrator Toolbar
' );
                break;
            case in_array ( 'authenticated user', array_values ( $user->roles ) ) :
                //drupal_set_message ( '
Load Member Toolbar
' );
                break;
            default :
                //drupal_set_message ( '
No Member roles found: Do Not load a toolbar
' );
                break;
        }
    }
    if ($scope==ALL || $scope == OG_ONLY)
    {
        $groups=og_get_groups_by_user();
        foreach ($groups['node'] as $group )
        {
            $roles = MYLEGACYMODULE_get_user_roles($group);
            $group_string = node_load($group)->title;
            $group_string .= ' (gid: ' . $group . ')';
            $group_string .= ' as ';
            foreach ($roles as $role )
            {
                switch ($role)
                {
                    case 7:
                        $role_string = '"Group Content Manager"';
                        $role_string .= ' (rid: ' . $role . ')';
                        $user_roles[$group]=array(
                                $role=>'Group Content Manager'
                        );
                        break;
                    case 8:
                        $role_string = '"Group Account Manager"';
                        $role_string .= ' (rid: ' . $role . ')';
                        $user_roles[$group]=array(
                                $role=>'Group Account Manager'
                        );
                        break;
                    default:
                        if (empty($role))
                        {
                            /*  Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
                             *  continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
                            *   The default value is 1, thus skipping to the end of the current loop.
                            *   --http://www.php.net/manual/en/control-structures.continue.php
                            */
                            continue 2;
                        }
                        $role_string = '"Unknown Group Role"';
                        $role_string .= ' (rid: ' . $role . ')';
                        $user_roles[$group]=array($role=>'Unknown Group Role');
                        break;
                }

            }
        }

    }
    return $user_roles;
}


How to select a node reference field when querying the database

I was able to join my node references using db_select, I just needed to add two relationships for each node reference (I have two node references (nested)), a first relationship to the specific table (which follows the pattern data_field_THE_NAME_OF_THE_NODE_REFERENCE_FIELD_IN_YOUR_CONTENT_TYPE) and a second relationship to the node itself with another alias (I mean by relationships JOINs).

Here's my code now :

$query = db_select("node", "n");
// joins
// setting up the first relationship
$query->leftJoin('field_data_field_X_ref', 'r', 'r.entity_id = n.nid');
$query->join('node', 'x', 'r.field_X_ref_nid = x.nid');
// setting up the second relationship
$query->leftJoin('field_data_field_Y_ref', 'r2', 'r2.entity_id = x.nid');
$query->join('node', 'y', 'r2.field_Y_ref_nid = y.nid');
// joining other fields
$query->leftJoin('field_data_field_field1', 'f1', 'f1.entity_id = n.nid');
$query->leftJoin('field_data_field_field2', 'f2', 'f2.entity_id = n.nid');
// ...
// fields
$query->fields("n", array("nid", "created", "type"));
$query->fields("f1", array('field_field1_value'));
$query->fields("f2", array('field_field2_value'));
// ...
$query->fields("x", array('title')); // title for the first node
$query->fields("y", array('title')); // title for the second node

// adding conditions
$query->condition('n.type', 'voiture_d_occasion', '=');

$result = $query->execute();

note that the two nodes references have a title, and in the query->fields() we mentioned that we want the title of both, drupal will return title for the first field, while the name of the field will be y_title for the second, you can use dsm on the query result to see the name of your fields.


Using cache for twig variables in preprocess function

Regions are not cached on their own. What you build in a region template will be part of cached pages. If most pages you deliver are cached, this might be OK.

To optimize it build the menu in a block plugin and place the block at the top of the region. The block plugin can get the blocks from  BlockRepository::getVisibleBlocksPerRegion. Use the access cache metadata this method provides for the region, add cache tags for all block entities and the tag config:block_list, so that the menu block gets invalidated when the block layout is modified.


It's not really a bug. Simply hide it in your theme instead. Just try to use technique a bit less obvious than display: none; as many bots know it already. Note that newest version of Spamicide module (7.x-1.0-beta3 at the moment of posting) does not even provide CSS file. All it does is:

/**
 * #post_render callback on the spamicide field. This will wrap the field
 * in a div so it can be hidden with CSS.
 *
 */
function _spamicide_field_post_render($content, $element) {
    return '
' . $content . '
';
}

See line 81 of spamicide.inc.


Why is Drupal urlencoding in tpl output?

Drupal is not URL encoding in the template output, it doesn't try to make that sort of blind string replace anywhere.

If the URL was prepared using any of Drupal's url() function, which is likely if you're using well written modules, then you should expect the query parameters to be properly encoded.

Drupal tries hard to conform to standards, you're probably going to find it more trouble than it's worth to get it to produce an invalid URL (which your desired result would be); it would be easier to simply write your own invalid version of url() and use that to prepare the content.


How to install Accelerated Mobile Pages (AMP) without composer

Since the AMP module requires the Lullabot AMP Library, there really is not a great way to install this without Composer. That is because Composer will update the autoloader information with that namespace and vendor information and fetch dependencies. Downloading the tarball of the module and the GitHub download unfortunately will not do the trick - you must use Composer. The module will block installation if it cannot find the class namespace of \Lullabot\Amp.

The Lullabot AMP Library also has its own dependencies listed in its composer.json, so Composer is required here.


You could create a user without any special admin privileges.  Then you can either view it from another browser as the normal user or use the Masquerade module to swap in and out of that user from the same session.


Drupal planet is built upon the core aggregator module, blogs are required to set up a special feed (generally tagging it drupal-planet) to be imported in the list.

That should be pretty simple to reproduce: What is Planet Drupal and how do I get added?


I added directions links to my markers, and to the view's attachment that contains a list of locations displayed on the map. To do this create the directions links:

Added my content type's Post Address field (from the addressfield module) to the views list of available fields.
Re-wrote the Post Address fields view output with the following:

Directions


Use Font Awesome classes to add the icons for the field label.


The form_id we want to alter is entity_form_display_edit_form
Because the settings fields are loaded through ajax, we first have to check if we are currently editing a field settings by checking  $form_state->get('plugin_settings_edit')
The fields we are looking for are then located at  $form['fields'][FIELD_NAME]['plugin']['settings_edit_form']
function fintech_form_entity_form_display_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $field_name = $form_state->get('plugin_settings_edit');
  if(!empty($field_name) && isset($form['fields'][$field_name]['plugin']['settings_edit_form'])) {
    $form['fields'][$field_name]['plugin']['settings_edit_form']['third_party_settings']['whatever_you_want_to_alter'] = '';
  }
}


How to know that the user has completed a quiz?


How to remove the Day field from the Date drop down?

if there is no validation on the form you could hide it with CSS.
Otherwise you can use a hook_form_alter


Use Services Views

After enabling that resource you would be able to do call to

http://example.com/<endpoint path>/<resource name>

After enabling "views" resource in your services endpoint you can do GET request to:

http://example.com/<endpoint path>/views/<view name>

This will execute a view and pass results.

Possible arguments:
- display_id: views display
- args: array of view arguments
- filters: array of view filter values
- offset: views offset
- limit: limit views number of results
- format_output: boolean whether we would like to get themed view or data

Example of calls:

http://example.com/rest/views/articles?limit=5&offset=2&filters[tags]=5
http://example.com/rest/views/articles?filters[tags]=5&display_id=block_1&format_output=1


Clear cache on view at a set date from a node field value?

If the node is scheduled to be published in the future then presumably the node will also be saved at that time, to update its status. So the cache can be cleared on node save at that point.


If you really do have Profile2 installed and enabled, then you shouldn't get getting undefined function errors.  Double check that it is enabled.

Otherwise, you are going about this in the wrong way.  You really don't need to do queries like this.  Leverage the API:

$account = user_load(10);
$profile = profile2_load_by_user($account);

If you have a single profile for the user, $profile will be a node object.  Otherwise, it will be an array of nodes.  Then you can do something like:

$resources = field_get_items('node', $profile, 'field_resources', $profile->language);

Also take a look at this article for a handy helper function or read more about the Field API.  If $resources are taxonomy terms, then take a look at taxonomy_term_load for loading the associated terms.


Only enable SSL for specific websites (Aegir)

You have to create a separate IP address for each site that uses SSL.  If you only have one IP address on the server and you assign it to SSL then the whole server is essentially using SSL.

So, solution is to assign a new IP address to the server and use that when you setup SSL for a site.

More info from this link: https://groups.drupal.org/node/74248

  all non-ssl sites will use the first ip address in the list.

  When a site has SSL enabled, it associates an IP address with the certificate it uses.
  Both the SSL and non-SSL versions of all sites using the same SSL certificate will use the assigned IP.

  You can only host as many SSL certificate addresses as IP addresses you have on the server.

  The site node also now provides you with the list of IP addresses the site is running on.


Bluehost cloud hosting, varnish caching issue authenticated user

Just to add that varnish only work for anonymous user not for authenticated.

There are various module available to purge varnish cached data on a particular event such as node insert, update, delete and many more.

Configure events properly in module configuration and that should do the needful.

Following are module :

expire

purge


Make a relationship to last element of a Field Collection

In order to show only the Field Collection item having the largest delta, you can use the Field Collection Views module as your formatter (i.e., Views field-collection items) in your View (i.e., parent View). With this formatter you can select another View (i.e., sibling View) to display your field collection items (so you will get a View within a View).

In the parent View you simply specify in the 'Multiple field settings' to display only the last result (i.e., Display 1 value(s), starting from 0, reversed checked), see screenshot below:

Note: in order to output the results in the order that is specified on your node, you have to set a relationship in the sibling View <view_name_for_field_collection> to 'Field collection item: Entity with the {Field Collection field}' and mark it as required. See this issue for the Field Collection Views for an extended explanation.

Let me know if you need any help with this.


Inject new variables in html.tpl.php based on current node content type

If I'm reading it right you've pretty much answered your own question there; only caveat being that I'm not sure if $variables['node'] will be set for that particular theme function.

If it's not you can use menu_get_object() to get it:

function mytheme_preprocess_html(&$variables) {
  if ($node = menu_get_object()) {
    if ($node->type == 'lighters') {
      $variables['classes_array'][] = 'myClass';
    }
  }
}

You can add anything you want to the $variables array and it will be available to you in the template file, as the variable is passed in to the preprocess function by reference. So if you set

$variables['my_var'] = 'something';

you will have access to $my_var, with the value you gave it, in the template file.


The submit handler is not executed when clicking on the start upload of the Plupload widget form, this only executes the ajax upload of the files (and the file validators).

To have a submit callback, and handle the logic of the uploaded files (i.e.: move files to a certain directory), you should add a button to the form.

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

The uploaded files are stored in the form_state under $form_state['values']['my_element'] (the name of your Plupload form field)

Update #1

Some sample code to trigger the form submit callback once the upload of the files is finished by the Plupload uploader. Basically what you need:

A submit button attached to the form to have a submit callback (which handles the uploaded files)
A custom javascript which intercepts the UploadComplete event triggered by the Plupload component
On the UploadComplete interception, trigger a click on the submit button

function YOURMODULE_form($form, &$form_state)
{
    // your form elements with plupload form element

    // add a submit button
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save file(s)'),
        '#submit' => array('YOURMODULE_form_submit'),
        '#attributes' => array(
            'class' => array('file-upload-submit'),
        ),
    );

    // attach the custom js to the form
    $form['#attached'] = array(
        'js' => array(
            drupal_get_path('module', 'YOURMODULE') . '/js/YOURMODULE.js',
        ),
    );

    return $form
}

function YOURMODULE_form_submit($form, &$form_state)
{
    // put uploaded files in a 'uploads' directory
    $directory = sprintf('%s://%s',
        variable_get('file_default_scheme', 'public'), 'uploads');

    // be sure directory exists (and create it)
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);

    // loop through each uploaded file
    $saved_files = array();
    foreach ($form_state['values']['files'] as $file) {
        if ($file['status'] !== 'done') {
            //handle error on upload fail
            continue;
        }

        // move files from tmp directory to defined directory
        $destination = file_unmanaged_move(
            $file['tmppath'],
            file_stream_wrapper_uri_normalize($directory . '/' . $file['name']),
            FILE_EXISTS_RENAME
        );

        $saved_file = plupload_file_uri_to_object($destination);
        file_save($saved_file);

        $saved_files[] = $saved_file;
    }

    // keep saved files in form state to be able to stuff afterwards (if needed)
    $form_state['saved_files'] = $saved_files;

    drupal_set_message(t('Files have been uploaded and saved.'));
}

The javascript (under js/YOURMODULE.js)

(function ($) {
    Drupal.behaviors.YOURMODULE = {
        context: null,
        attach: function (context) {
            var that = this,
                uploader = $('.plupload-element', context).pluploadQueue();

            this.context = context;

            if (!uploader) {
                return false;
            }

            uploader.bind('FilesAdded', function() {
                // start upload automatically once files have been added to queue
                that.start();
            });

            uploader.bind('UploadComplete', function() {
                // trigger click on submit button to submit form once upload completed
                that.complete();
            });

            return this;
        },
        start: function() {
            $('.file-upload-submit', this.context)
                .attr('disabled', 'disabled');
        },
        complete: function() {
            $('.file-upload-submit', this.context)
                .removeAttr('disabled')
                .click();
        }
    };

})(jQuery);


How to edit fields' display markup in a search view?

Select the field and drop down the "Style Settings" tab, here you can select an element and create new classes for the field, label or wrapper. You can also remove the css completely


Why doesn't the option "User:roles"  show in "Contextual Filter"?

You should add a relationship "Content:author"; then, the "User:role" filter will appear in "Filter criteria."


How to access Views administration in Commerce Kickstart 7.x-2.9

If you have not made any changes and are logged in as admin then the menu link should be under Site Settings -> Visual and Layout -> Views


Can't find my website page listed under admin/structure/pages

The /contact page is provided by the Contact module, which you must have enabled. It displays the contact_site_form form, which is declared in /modules/contact/contact.pages.inc.

Configuration options for this form can be found at the site.com/admin/structure/contact URL.

If you're looking to change form structure, you may need to create a custom module and implement hook_form_alter(). If you're after changing layout, you may be able to get away with adding/moving blocks (in which case have a look at Context for more options than the core blocks page), but more likely should use something like Panels to create a new page and insert a new contact block on it. You may want to have a look at the Webform module, which can be used to create & configure forms through the UI.


How can I copy multiple nodes and reset fields belonging to the copies in one operation?

In my opinion is easier if you write the code in a custom module.
You should create a custom form with form api with a button that call a function that select the nodes with db_select and after does the operations, copy :

// Load a node
$node = node_load(1);

// unset version and node id's
unset($node->nid);
unset($node->vid);
unset($node->path);

and unset values of the two fields for each node and save node

unset($node->field1);
unset($node->field2);
node_save($node);

After create a custom block and in block_view load the custom form.


MegaDrupal MD.Foto: Module dependency displaying incompatibility status

If you think Ctools 7.x-1.4 is the one you installed in your system and that Drupal wrongly detect it starts by clearing the cache. Then searh ctools.info file in your web root, if you find more than one, then you have duplicate installation of the Ctools module. Likely one of then is too old but is the one picked by Drupal. Remove it. If not, check the version in this file.


To force to create a line_item for every same product added to the cart you just need to uncheck the option "Attempt to combine like products on the same line item in the cart." in the Add to cart form settings  of your product reference in your product display content type.

In other words. You have to change the content type that you use to show your product, you had added a product reference to this content type. Then you just has to change in the "Manage display" of your content type, the settings of the "Add to cart Form" of the product reference field, and you have to uncheck "Attempt to combine like products on the same line item in the cart."

This is a screenshot of the manage display page:


Organic Groups and Workbench or Revisioning together. Will this work?

We've built a D7 site with Organic Groups and Revisioning and have found that installing Organic Groups causes a pretty major problem with Revisioning in that the Author and Moderator roles cannot see unpublished content.  We've confirmed on a clean Drupal installation that Organic Groups Access Control is the cause of the issue.

The only workaround that we found was to check the Bypass Access Control checkbox for those roles.  That means those roles bypass all security checks on content on the site so they can edit/delete/publish any content.  That is an okay work around for our site but did present a problem when we wanted a separate moderator role for just one content type.

See this post for full details -> http://drupal.org/node/1494232

We are planning on looking at Workbench for a different D7 site because Revisioning and Rules isn't going to be sufficient for the workflows.


Programmatically add a translation of month

Use string overrides directly in either your settings.php file or through the string overrides module. See this note for specifics, this also lets you migrate this string overrides snippet from site to site either through simple cut and paste or through the string overrides migrate extension. This also deals with strings not yet known to the locale UI through t().

Example:

 $conf['locale_custom_strings_en'][''] = array(
   'January'      => 'New string 1',
   'February'      => 'New string 2',
 );


Perhaps Services Views module could be of interest here:

  Views support for the Services module version 3.x and later.

  It has currently two features:
  - Create view based resource creating Services display in a view
  - Execute any view of the system via views resource call

  After enabling "views" resource in your services endpoint you can do
  GET request to:

http://example.com/<endpoint path>/views/<view name>

  This will execute a view and pass results.


Image upload in a node gives required error

Most probably the upload is limited due to php settings. There is not only a setting for max upload per file, but also a max for a post.

On this page you can find how to solve in this link

If this doesn't work, there might be a setting for max_execution_time in php.ini, which cuts off the upload script if it takes too long.


A few problems I can see:

The $model_options variable is used both in the form and AJAX callback function, but isn't defined anywhere. Same thing with the $platform variable in the AJAX callback.
You're putting a wrapper around a particular element, but instead of returning that element you're returning the entire form.
It looks like you're attempting to put form-altering logic into the AJAX callback function - it should be used only to return the updated element, the actual building of it should be done in the form function.
You're defining the AJAX callback wrapper as 'replace_model_div', and implementing it as a class name instead of an ID, and with a complete different name (model-wrapper).
The function signature for your form is wrong (in Drupal 7 it's:

function form_name($form, &$form_state)

You should get some joy with code a bit more like this:

function main_iosupload_form($form, &$form_state) {
  //Define SQL Lookup Query

  $sqlplatform = "SELECT vid, name FROM {taxonomy_vocabulary} WHERE vid >= 4";
  $sqlmodel = "SELECT tid, name FROM {taxonomy_term_data}";

  $result = db_query($sqlplatform);
  $options = array();
  foreach ($result as $row) {
    $options[$row->vid] = t($row->name);
  }

  $form['platform'] = array(
    '#type' => 'select',
    '#title' => t('Select a Platform'),
    '#options' => array(
      0 => t('- Select -')) + $options,
    '#default_value' => isset($form_state['values']['platform']) ? $form_state['values']['platform'] : 0,
    '#required' => TRUE,
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'ajax_select_callback',
      'wrapper' => 'replace_model_div',
      'method' => 'replace',
     ),
  );

  if (isset($form_state['values']['platform'])) {
    $model_options = function_to_get_model_options_by_platform($form_state['values']['platform']);

    $form['model_wrapper'] = array(
      '#prefix' => '
',
      '#suffix' => '
',
    );

    $form['model_wrapper']['model'] = array(
      '#type' => 'select',
      '#title' => t('Select a Model'),
      '#options' => $model_options,
    );
  }

  return $form;
}

function ajax_select_callback($form, $form_state) {
  return $form['model_wrapper'];
}


Show only used taxonomy terms in exposed filters

As Adrian said it was possible to change the code in the article a bit to make it suitable for Drupal 8. Here is my solution:

function MODULENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  //id of the form you want to alter
  $formId = 'views-exposed-form-agenda-page-1';
  //field tags
  $select_field = 'field_tags_target_id';

  /**
   * Apply the form_alter to a specific form #id
   * the form #id can be found through inspecting the markup
   */
  if ($form['#id'] == $formId) {
    $available_terms = _get_available_terms();
    if (isset($available_terms)) { // Unset the existing list and add new one with available terms.
      unset($form[$select_field]['#options']);

      if ($form[$select_field]['#options']['All']) {
        $form[$select_field]['#options']['All'] = '- Any Term -';
      }

      foreach ($available_terms as $available_term) {
        $tid = $available_term[0];
        $name = $available_term[1];
        $form[$select_field]['#options'][$tid] = $name;
      }
    }
    else { // Unset all options except '- Any -'
      unset($form[$select_field]['#options']);
      $form[$select_field]['#options']['All'] = '- Any Term -';
    }
  }
}

function _get_available_terms() {
  //table name of tags field
  $node_tags_table = 'node__field_tags';

  $db = \Drupal::database();
  $query = $db->select($node_tags_table, 'nft');
  $query->distinct();
  $query->join('taxonomy_term_field_data', 'tname', 'tname.tid = nft.field_tags_target_id');
  $query->fields('nft', ['field_tags_target_id']);
  $query->fields('tname', ['name']);
  $result = $query->execute();

  $term_list = [];
  while ($row = $result->fetchAssoc()) {
    array_push($term_list, [$row['field_tags_target_id'], $row['name']]);
  }

  return $term_list;
}


I'm a litle confused about your goal, but taking your question literally as I would like to extend the schema of another module, and assuming by extend you mean alter and not inherit from, then yes, it's pretty straightforward.

First of all, implement hook_schema_alter() so that Drupal knows about the change you're going to make to the table:

function MYMODULE_schema_alter(&$schema) {
  $schema['rooms']['foo_table']['new_column'] = array(
    // ...
  );
}

Then add an update hook to your module's install file to physically add the field to the table, e.g.

function MYMODULE_update_7100() {
  $schema = drupal_get_schema_unprocessed('rooms', 'foo_table');
  db_add_field('foo_table', 'new_column', $schema['new_column']);
}

It would also be advisable to implement hook_uninstall()/hook_disable() to remove that column from the table when your module is no longer active. Leaving it there probably won't hurt anything, but for the sake of cleanliness it's a good idea.


What is the simplest way to transfer webform /data/ from one instance to another?

Sometimes it is possible to export/import only selected tables on testing environments (not recommended on production sites).

A simple way is to use backup&migrate module (https://drupal.org/project/backup_migrate) and then export and import the webform tables you like. You can select this tables on the advanced options.


Maybe this can help How to upload file in drupal8 forms with form element type file?

I see for your use case it makes more sense to use Managed file type.

A couple of observations, something you should look at,

It seems you are getting SQL errors due to trying to upload a file which is already present in the table, you should check why this happens and perhaps programmatically change the name of the file if it already exists. See file_save_data
Errors from views, not sure where you are trying to submit this form, but it is clearly breaking something in views_data_export or it maybe because of the next point.
Lastly, check the link above for how to properly handle file uploads in form, it looks like file_save($file); is breaking for you due to missing uri


Is there an hook to react to custom entity updates?

If it can help other people :

hook_entity_update is working fine as long as it is declared in the .module file.

I putted it int an inc file so it was never fired !


There must be 2 variables holding the "submitted" string, $submitted and also $content['submitted']. You should either forget the $submitted variable and if you render($content['submitted']) then it should put that as #printed => true. Then later if you render($content) it shouldn't print the submitted text as it's already printed.

The second option would be to render($submitted) and then do hide($content['submitted']) before render($content).


Create relationship between node and menu link

To create a menu link for a node programmatically and to see it in the node edit form you have to connect the link uri to the node entity:

$item = \Drupal\menu_link_content\Entity\MenuLinkContent::create([
  'link' => ['uri' => 'entity:node/' . $node->id()],
  'title' => 'Menu item for node ' . $node->id(),
  'menu_name' => 'main',
]);
$item->save();


The main problem was with devel module.
When I disable it and try again all job everything works perfect.
So maybe was some bugs with devel module, but I am not sure.


Both the conditions should be nested under the "OR" line like this:

+ OR
  + Current day of the week (is Monday)
  + Current day of the week (is Thursday)

What you have at the moment is a clause that says "if the current day of the week is a Monday and one of the following conditions is true: the day of the week is Thursday"


Not able to map all the product variations fields in commerce feeds importer

Another user gave me this to answer my question:

How to use Commerce Feeds to Import Stock for the Commerce Stock module?

The user https://drupal.stackexchange.com/users/8943/watergate suggested this:

If you're using commerce_feeds 7.x-1.3, uninstall it.
Make sure you've updated the standard Drupal feeds to 7.x-2.0-beta1
Download commerce_feeds 7.x-1.x-dev

After I did that, I could use mapping and see all the target fields for my product variation, including those fields enabled when you use commerce_stock.


There is a way to programmatically print a block in a tpl file.

For 'module' defined blocks you can use block_load() see: block_load op api.drupal.org

If you have a block defined through the block interface, it is called a custom block you can use block_custom_block_get($bid) see: block_custom_block_get() on api.drupal.org

$block = block_custom_block_get(1);
$content = $block['body'];


How to charge a user to post a job listing in D7?

You can use a combination of Commerce userpoints and Commerce Node Checkout. This will allow them to purchase credits to be applied to publishing nodes.


The easiest way to add a JS file to your theme is to add it in the .info file:

scripts[] = js/my_script.js

Be sure to put your js file in a js folder inside your folder's theme.

Reference: Adding JavaScript to your theme or module  (works in D7 too)


How to wrap views-view-fields.html.twig with html container element?

Option 1

You can by copying (the entire code) from core views-view.html and paste it in your theme's template folder and rename it views-view--[view-name].html.twig and then add your class to this template file.

replace {{ rows }} with

<div class="slider-article">
{{ rows }}
</div>

Option 2

Copy from core views-view-fields and paste it in your theme's template folder, rename it views-view-fields--[view-name].html.twig

Then add your div with class before {% for field in fields -%} and add close tag after {%- endfor %}

Option 3 (maybe)

You can add it via the Views UI by clicking on "None". But this will add the wrapper to the entire view, which you may not want.


Autocalculated price field depending on language

Ok, I managed that with computed field. Money field was not needed.

In computed field I've posted code:

 $exchange_rate = CurrencyExchanger::load('PLN', 'EUR');
 $netto_price = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_name')));
 $entity_field[0]['value'] = bcmul($exchange_rate, $netto_price, 2);

It calculates currency in fly from currency module.


Get path from router and redirect after autocomplete selection

Try to use $build['#attached']['drupalSettings']['vartest'] = $test; to pass $test from PHP to JS. The variable $test contains the Drupal's path/routes.

Replace $build with the variable containing the form or the render array to which the settings are attached. In a form builder or hook_form_alter(), that would be $form.


Change allowed file types based on certain criteria

So, it's the rough instruction step by step as Matt asked:

Add new field where you can specify the allowed extensions of the files.
Alter the form of your submission via hook_form_alter() and find your file upload field
Specify your allowed extensions from your field with extensions into this point


How to block a content type from the RSS feed

I would have thought there would be an option under Content Types which says "Don't put in feed"

Yes, it's as simple as that. Simply uncheck the "Promoted to front page" from the content type settings and that content type's nodes won't be included in the RSS feed. :-)


Commerce Allows User to Edit Cart After Completion of Checkout

Hmmm, this is definitely something that deserves to be fixed in Commerce itself. I'm going to open an issue there and outline a strategy that essentially adds a form alter hook to the Cart module to redirect back to /cart in the event that the shopping cart form is being built / submitted for an order that is in an unsupported status. I can't say exactly how I'd do it yet, but I suppose it would involve iterating through the checkout pages to allow shopping cart form submissions for any order that hasn't yet passed a checkout page that doesn't have back buttons (e.g. the Payment and Completed pages).


The only module I can think of is Workbench Moderation. It may be much too large and complex for your needs, but within the node's "Moderate" tab, it provides a list of all editing actions including the change of the node's status.

Screenshot


Following the comment on the panels issue linked in the question, I managed to make the panels page override for term_view works.
This is the code added to mytheme/template.php

function MYTHEME_preprocess_page(&$vars) {
  // if this is a panel page, add template suggestions
  if($panel_page = page_manager_get_current_page()) {
    // add a generic suggestion for all panel pages
     $variables['theme_hook_suggestions'][] = 'page__panel';
    // add the panel page machine name to the template suggestions
    $variables['theme_hook_suggestions'][] = 'page__' . $panel_page['name'];
        if($panel_page['name'] == 'term_view' ) {
           $vars['theme_hook_suggestions'][] = 'page__term_view';
}
}
}

Then, inside the mytheme/templates/ folder, I added page--term_view.tpl.php with my custom page title display.


Complex Views / Field Collection question

After some direction from merlinofchaos, here is what I did:

Add the field as an exposed filter
Use form_alter to change it to hidden
Use javascript to set the value to 1, bound to a change event on the date select

Otherwise its like asking for a conditional filter (if filter X has value, then set these filters to Y) which is not so easy in UI.

You could also inspect $_GET and use hook_views_query_alter to add a $query->where, but I had better luck with Javascript.

Hope this helps others.


may be this will help you
views_conditional

How to use Views Conditional in your Views:

Create a view. Add some fields under "FIELDS".
Click on "ADD" next to fields. Scroll down to "Views: Views Conditional", probably found near the bottom of the list.
Add and configure fields
Choose a field to run a condition against, and provide values accordingly.
Save, views conditional handles the logic and returns as specified.
use replacement variables


When you edit your vocabulary, on "Structure > Taxonomy > Home page menu > Edit" there should be a "Select to rebuild the menu on submit" checkbox.  This helped in my case.

Because the following warning, you should consider making a backup before doing this.

  This will delete then re-create all of the menu items. Only use this option if you are experiencing issues like missing menu items or other inconsistencies.


Webform dynamic select options based upon another element's state

No one has contributed back a solution for Drupal 8. I think the best approach is going to be to organize cascading select menus using a CSV and implementing something like Cognito form's cascading dropdowns menus.

Another supported approach is the Webform Simple Hierarchical Select module but it requires a taxonomy.


How to control metatag module's tags from a page callback?

There's a hook for that. Here's my implementation.
<?php

function mymodule_some_page_callback() {
  global $metatagOverrides;
  // ... generate your page ...

  $metatagOverrides = [
    'og:image' => 'https://example.org/the-image.jpg',
    'og:description' => 'Some description',
    ...
  ];

  return $thePage;
}

function mymodule_metatag_metatags_view_alter(&$output, $instance, $options) {
if (!empty($metatagOverrides)) {
  foreach ($metatagOverrides as $tagname => $value) {
    if (array_key_exists($tagname, $output)) {
      $output[$tagname]["#attached"]["drupal_add_html_head"][0][0]["#value"] = $value;
    }
    else {
      $output[$tagname] = [
        '#attached' => [
          'drupal_add_html_head' => [
            [
              [
                '#theme' => 'metatag_property',
                '#tag' => 'meta',
                '#id' => "{$tagname}_0",
                '#name' => $tagname,
                '#value' => $value,
                '#weight' => 100,
              ],
              "{$tagname}_0",
            ]
          ]
        ]
      ];
    }
  }
}


Whether you're creating content or user Views, you have to add the Flags Relationship (User flag in your case). This is the first step to introducing the flags information into the Views, and in most cases you'll want to set that Relationship to Any user, and use Contextual filters to restrict the results to your needs.

List users flagged by a user

This answers your first question, a page you can add to user profile pages (as a Drupal tab for example).

Create user Views, Page Display
Add the User flag Relationship and configure it:
Include only flagged content
Follow
Any user
Add the Contextual filter User ID from the Flagging category (not the User Category!) and configure it:
It will use the Flags Relationship by default
When the filter value is NOT in the URL
Show "Page not found"
When the filter value IS in the URL or a default is provided
Specify validation criteria
User ID
Change the Path to user/%user/flags
Add a Menu tab if you wish to show on user profiles
Add No results behaviour This user is not following any others.
Add a Field Created from the Flagging Category to show when the flagging occured.

When you visit a person's page you'll see a list of users they follow.

List followers of a user

Duplicate the Page from above
Override the Contextual filters, remove the flagging one, and add User ID Contextual from the User Category and configure like the one above
Change Path to user/%user/followers and Menu tabs
Adjust the Title, No results text etc.
Override Fields, remove the Name (it will always show the user who's page you're viewing so it's redundant)
Add a Field User ID from Flagging Category (Label it Who flagged)

List content from users that are Followed

Duplicate the first Page from above (List users flagged by a user)
Add a new Relationship Content authored from the User Category, require it so you don't see people in the results that haven't authored any content
Edit the Path to user/%user/flags/content or whatever makes sense to you, add the Menu tab
Override the Fields and add the Title Field from Content Category
Remove the Field showing the date when Flag was created
You can Group by user Name under Format, to group Content by authors if you like

You can create Blocks instead of Page using similar logic, just configure the Contextual filters to react to use a default value from context, when it's not in URL.


The $_SESSION variable contains values set by Drupal; in your case, $_SESSION['batches'] is the value set by the Batch API. Drupal, although, doesn't use the session to store the user ID; that value is stored in the $user global variable, as cilefen correctly said in his comment.

global $user;
$uid = $user->uid;
$roles = $user->roles;

Keep in mind that the $user global variable doesn't contain a fully-loaded user object; to get that, you need to use the following code.

$account = user_uid_optional_load();

$account will contain every field associated with the user entity, and any property attached to the user object from third-party modules.


drush core-config causes 'Permission denied'

You are trying to edit a system level file (ex. /etc/php5/cli/php.ini) using Drush and you don't have access to it at your current permission level. You need to login using an account with higher permissions or use sudo.


Return both a form and content in a menu callback

In Drupal 7 drupal_get_form() returns a render array instead of a string, so you should return a render array as well:

return array(
  'my_content' => array(
    '#type' => 'markup',
    '#markup' => 'Some markup',
  ),
  'my_form' => drupal_get_form(...),
);


You need to create a relationship in Views. Then filter by creation date descending, and limit results to 1. 'Relationship' is how Views does a SQL JOIN.

It's non-trivial to describe, so I'll just link to a tutorial: http://drupaleasy.com/blogs/ultimike/2009/07/using-views-relationships-arguments-attachments


Creating a block programmatically in a theme on Drupal 8?


Node form with fields loaded from another node or other entity

Isn't module Inline Entity Form exactly what you are looking for? Here is a quote about it (from the module's project page):

Provides a widget for inline management (creation, modification, removal) of referenced entities.
The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.
Existing entities can also be referenced.


When you create a new content type, it should be visible in the "Content Type" page.

If they are not visible, then it could be a permission issue: You have to give permission for creating/modifying nodes using content types you added. The only exceptions are the first user created for a Drupal site (who always has all the permissions) and the users with the "administer content types" permission.


How To Create a Remote Views Search Form - D7

I would suggest writing your own form in a block which you can place on the home page. I don't see anything wrong with writing the form in HTML - though if you generate your form the Drupal way using the Form API then you'll ensure you get consistent themeing across your site, you'll be protected against XSS attacks and so on. How to use the Form API is beyond the scope of a single question ;
There is a module that allows you to use POST queries with views exposed filters : http://drupal.org/project/views_expost - hopefully this should deal with your long URL problem.


Force node render with a template (giving template url not suggestion)

I will skip theme suggestions since your title specifically say to.  There are several ways to use the menu router system to send the same node as an argument to different callback functions that handle the render process.

Most commonly used methods are Panels and Display Suite.

With Panels, you can have the panel sit at any url you want, take the node as an argument from context or url, and display parts of it or views related to it in a layout controlled by the panel manager.
yousite.com/display1/nid and  yousite.com/display2/nid

With Display Suite you have a similar display management, but the default (at least last time I used it) is to have the different custom displays as final tags in the url.
yousite.com/normal-node-path/display1  and   yousite.com/normal-node-path/display2

If you want to do it all by yourself with custom code, you can use hook_menu to register your own page callback(s) for your own url(s).  You can pass as many pieces of the url as you wish as arguments to your custom function, as long as they do not include the first word.  yousite.com/this-one  Menu_router does not like urls to start with variables.
Then, with the information that your callback preps, you can guide your node through a custom hook_theme to use your specific template


You need to write JavaScript in a js file in your theme, declare a library within your theme and attach it globally or inside of a theme page attachments hook. You also need to depend on jquery from core in your library yaml definition as well.

See: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


How to set 'html' email template for webform email setting?

HTML Mail will give you that option.  It integrates with Webform. To use HTML Mail you will also need Mail System.

Go to Configuration > Mail System and set the Site wide Default to be HTML Mail and the HTML Mail module to be HTML Mail.

And if the option "Send e-mail as HTML" does not appear while editing a Webform email. Go to: admin/config/content/webform check "HTML mail system".


ul list with ajax items is not build correctly

$drop_value=isset($form_state['values']['dropdown'])?$form_state['values']['dropdown']:$default_value;
$form['images']['drop_area'] = array(
'#markup' => '

    '.get_items($drop_value).'

',
'#prefix' => '
',
'#suffix' => '
',
);
function get_items($drop) {
  ...
  //builds li elements
  return $li_elements;
}

In your above code try after remove the "/" at the end of ul tag.

Then your code should be :


You need to FTP into your site and go to sites/all/modules/ckeditor/ckeditor.styles.js. There is not an admin option to do this, which it sounds like you expected.


This is probably a unit test (not mentioned in the OP). If so, the intention should be to test the methods of the TempTarget class, which means, that the first thing needed would be to instantiate an instance of that class, e.g.

/**
 * Instantiates and returns a TempTarget object.
 */
protected function getTempTargetInstance()
{
  $id = $this->generateId();
  $def = $this->generateDef();
  // This is where you mock the constructor dependencies/services.
  // You probably will need to create a mock like this:
  //   $this->getMockBuilder('Drupal\Core\Entity\EntityTypeManager')
  //     ->disableOriginalConstructor()
  //     ->getMock();
  $this->entityTypeManager = $this->getEntityTypeManagerMock();
  $this->entityFieldManager = $this->getEntityFieldManagerMock();

  // You can now call the constructor.
  $tempTarget = new TempTarget($id, $def, $this->entityTypeManager, $this->entityFieldManager);
  return $tempTarget;
}

At this point, your object should be instantiated and you can call methods on it to assert the assumptions you want to be testing. For example:

public function testDefaultConfigurationMethod()
{
  $tempTarget = $this->getTempTargetInstance();
  $formConfiguration = $tempTarget->defaultConfiguration();
  // Test different assertions given the $formConfiguration object.
}

However, at the time you call defaultConfiguration() you know that you need a container available that holds an entry for plugin.manager.feeds.target, so, you have to have that prepared in advance. The right place for that would be your setUp() method in your class, for example:

/**
 * {@inheritdoc}
 */
public function setUp() {
  parent::setUp();

  // Provide a mock service container, for the services our module uses.
  $container = new ContainerBuilder();
  $container->set('plugin.manager.feeds.target', $this->getFeedsTargetPluginManagerMock());
  \Drupal::setContainer($container);
  ...
  // Further setting-up of your testing class.
}

with getFeedsTargetPluginManagerMock() looking something like this:

/**
 * Creates and returns a mock for the feeds
 */
protected function getFeedsTargetPluginManagerMock() {
  $feedsTargetPluginManager = $this
    ->getMockBuilder('Drupal\feeds\Plugin\Type\FeedsPluginManager')
    ->disableOriginalConstructor()
    ->getMock();
  ...
  // Further mocking of the objects methods if needed.
  ...
  return $feedsTargetPluginManager;
}

Good luck!


How to get value from field widget during AJAX callback loop?

Looks like there's an existing answer on Multiselect issue queue: Changing multiselect options using #ajax, and it has the solution.


Check your variables by printing them with drupal_set_message().

function multi_reg_pagecreate_submit($form, &$form_state) {
  drupal_set_message('<pre>' . print_r($form_state['values'], true) . '</pre>');
}

Alternatively, you can use debug()

debug($form_state['values'], 'Debugging the form', TRUE);


how to get the bid ( id from multi-instances of block )?

You receive the block id via a form value in the blockSubmit function, so if you save it as configuration, you can use it in the build() function. Seems a bit weird to save the block id as another config value, but otherwise you can't access it. Also note that it is possible to use a block plugin without an actual block entity, see https://drupal.stackexchange.com/a/181458/11500

/**
 * {@inheritdoc}
 */
public function blockSubmit($form, FormStateInterface $form_state) {
  $block_id = $form['id']['#default_value'];
  $this->configuration['block_class'] = $block_id;
}

You should probably add it to the BlockBase::defaultConfiguration() function as well. Because this changes the configuration, you will have to save the blocks manually once (to activate the change).


How to record a log message when saving a Commerce Order via Drupal EntityWrapper?

You may need to set the revision and log properties on the default order object, instead of the wrapper.

e.g:

$order_id = 800;
$order = commerce_order_load($order_id);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->uid->set(1);
$order_wrapper->mail->set('test@example.com');
// Set revision details on order object
$order->revision = TRUE;
$order->log = t('Changed order owner and mail');
$order_wrapper->save();

As the order object is passed by reference, from memory the revision log info can be set that way.


How to put site in 'Safe-Mode' to troubleshoot Drupal if site encounters problem?

First of all, I reccomend you install drush. It provides a ton of handy command line operations for Drupal that will allow you to do things if your site goes belly-up.

You should troubleshoot by turning off modules with drush
pm-disable. Look in your error logs to see if any modules in
particular are the culprit.
You can also enable and disable modules in the database, instructions
are here. You can also get some major issues if you move a
module to another location and don't rebuild the module registry,
which can be done with drush rr.
Make a backup of your DB (and in general, ensure backups are made on
a regular basis) before doing anything. Do NOT drop any tables or
delete any rows if you don't know what you're doing!

When doing updates, I would advise that you update each module one at a time in a development version of your site, using drush pm-update. Once the module is updated, run drush updatedb and also drush cc all, then check around the site quickly to make sure no major errors have occured.

Generally it's best to do core, then security updates, then version updates. It's also worth checking the version jump (especially with important modules such as Features, or Context) and making sure there are no drastic changes. As an example, Features 2 recently changed the way it stored field settings and it requires some clean up operations that will have to be done manually.

So take great care when updating modules!


Create a new user from an entry submitted with the module "webform"

I am also looking for a similar solution and would like to reuse an existing one.
To assign a role on registration I would try some of existing modules.
Let me summarize what is available:

Auto Assign Role (D7, D6, D5)
Registration_Role (D5, D6)

To allow a user to choose a role on registration

User-Selectable Roles (D5, D6)

To provide a role using a key during registration

Registration Codes (D7, D6)

Sold Memberships

Ubercart (D7, D6)

Join role with a password

Join role with password (D7, D6, D5)

Apply for role

Apply for role (D7, D6)

Webform register

Webform register (see Open Issues for details)

See also integration Webform and registration module.


The way I would go would be to first create the desired views, then create custom "page–taxonomy–term–[tid].tpl.php" files, and in their code use the views_embed_view invoking the desire per-page view. I'm not sure though if this is the most effective way.


As you said you have configured the translations correctly.
On the account settings page you will be able to see the Translate Settings tab here /admin/config/people/accounts

After clicking on the link here you will find the enabled languages with options in front of them

Click on edit and then you will be able to see all the Account settings to be translated including mail where you can write / modify the text in mail like in following screenshot.


Can I run a site on AWS Elastic Beanstalk for PHP?

Yes, we are currently running site build on Drupal 7 on AWS Elastic Beanstalk for PHP.

I am strongly recommend to install and configure memcache for best performance.
PressFlow is not required replacement for standard Drupal 7 core (but for Drupal 6 is).

Also sites/default/files folder must be mounted from S3 bucket (read here how to manage it https://sites.google.com/site/truthkos/home/tutorials/amazon-web-services/working-with-ec2-instances/setup-a-s3-connection-to-ec2-instance-via-fuse)

For anonymous user Varnish will dramatically increase site performance.


How to calculate the average ratings for the post when the user submits 3 field ratings?

Use fivestar_get_votes to get individual widgets average and get average of them to have average rating of the entire node.


Print image field with multiple entries from field in twig template

Print the image field in the node template like any other field:

{{ content.field_gallery_images }}

And then use a field twig to loop through multiple field items:

field--field-gallery-images.html.twig

  {% for item in items %}

{{ item.content }}

  {% endfor %}


I am pretty sure that the Menu Attributes module will work for you.  It adds several options to the menu entries, including ID and class attributes.  You would just need to edit the menu entries that you need this class on.


Connecting different content types/tables in Drupal with primary/foreign keys

Following link has a long discussion about foreign key in Groups.Drupal

=>
 Add join/foreign key info to schema


How to create forms similar to admin block forms

Here you have two examples to learn how to build a custom module with drag and drop elements:

http://coffeeshopped.com/2010/09/drupal-drag-and-drop-tables-in-custom-modules

http://www.computerminds.co.uk/quick-guide-using-drupal-add-tabledrag-and-enjoying-jquery-drag-and-drop-loveliness

Oskar


custom field - How to get saved term selected for entity_autocomplete

with some help above from Ajay Reddy, I was able to finally get to something that worked... Here's what did it:

  '#default_value' =>
  \Drupal\taxonomy\Entity\Term::load($items[$delta]->description_term),


I think what you should be doing is something along the lines of the following:

  $node=$vars['node']; // or however you get the node object

  $source = 'node/' . $node->nid;
  $alias = $node->field_se_news_source['und'][0]['url'];

  if (!empty($alias) {
    $paths=array('source' => $source, 'alias' => $alias);
    path_save($paths);
  }

but I would do in it hook_node_presave() instead.

Also be aware that I imagine this won't work if the url in your CCK field is not local to the host system.

More info:

http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_presave/7

http://api.drupal.org/api/drupal/includes!path.inc/function/path_save/7

And oh, the error is because you were passing path_save() the return value of the array() constructor and not an actual variable.


how to create signup form with MailChimp module

I get it. You’ve just signed up for Mailchimp and set up your first list. You want to put a signup form on your Drupal 8 (probably works in D7 as well) website so visitors can start signing up for your newsletter or announcements. Here's how you place a signup block. I know this is a late answer, but hopefully it will help someone. To get through this process you have to clear cache a lot. Here's what worked for me.

Install and enable the mailchimp module and the Mailchimp_signup module. Set up the API key with your mailchimp API clear cache (on the command line you can type ‘drush cr’ or you can do it in the admin menu | config page | performance link | clear all caches button).

Go to admin/config/services/mailchimp/signup and add a signup form. Give it a name and remember the name since that’s what you’ll search for when you’re ready to place the block. Check the ‘Block’ checkbox. Choose at least one list that you’ve set up on Mailchimp’s website or on the Lists tab. Save the form.

Refresh cache ‘drush cr’ again.

Go to the Structure | Block layout tab. Choose a region where you would like the signup tab and choose ‘Place block’. Search for the name you used when naming your signup form. Choose it and ‘Save block’.

Now go to your site and observe your work. Your form will appear in the area you specified.


How can I show menu according their role?

Note: This answer is for drupal 7.

You can use Menu Block. And make blocks of menu and use on page. And you can set visibility settings for that block.


How to write a self join query in drupal 7 using db_select

A query using db_select is a lot slower than a 'vanilla' db_query call...for a query as simple as the one you're doing just run it through db_query:

$query = db_query('SELECT * FROM msg where sender = receiver');


Programmatically changing the global site name?

What is the value for the site_name variable in the variables table? (e.g. what's the output of variable_get('site_name')?)

If it's overridden from the value that you set in your settings file, reset it like so:

variable_set('site_name', $my_title)


You need a text filter to replace tokens in fields. You can configure them in admin/config/content/formats. In drupal 7 you can install the needed text filter with:

Token Filter

But this will not be ported to drupal 8 in the same way as in drupal 7:

Issue Token Filter in Drupal 8

As this is a very simple piece of code, there is an unofficial version for drupal 8:

token_filter-8.x


What is the best way to collect and report statistics from within views 3's exposed filter?

You can use GA Push module:

  GA Push offers an API to enqueue informations that are sent GA
  servers, and three submodules to track browser events (using jQuery),
  form validation errors and log exceptions.

Instead of saving the data in your custom table you can just send it to Google Analytics.

Collect your data in your PHP code and send it like this:

      $push = array(
        'eventCategory' => $category,
        'eventAction'   => $action.
        'eventLabel'    => $label,
        'eventValue'    => $value,
      );
      ga_push_add_event($push);

You may hook on the form submit instead of adding PHP code to the view.


Module name and name of the directory the containing it

Good conventions mentioned by Kevin aside, there's no technical reason for the names to match, no. What's important is the name of the .info.yml file, that's what defines the module machine name.

Drupal just interrogates the known module folder locations recursively looking for .info.yml files, so anything will get picked up regardless of folder name.


What is the best way to add a comment policy to the comment form?

You can do this easily with a form_alter hook.

<?php
function MODULENAME_form_comment_node_NODE_TYPE_form_alter(&$form, $form_state, $form_id) {
    //drupal_set_message('<pre>'.print_r($form, 1).'</pre>');
    $form['privacy-note'] = array(
          '#markup' => t('Comments are pre-moderated and may be edited before publication');

        );
}

Yes it sounds a little silly to make a module for this. But making a little module for every little work is also not a smart option.
If you have never created a module before, See this: http://drupal.org/node/1074360
Don't forget to change MODULENAME and NODE_TYPE with actual values. if you have any questions, I'd be happy to answer them here :)


I did some a quick search and stumbled onto this comment in this thread, which led to the Views arg parent term module. From what I read on the module page

..this module provides another default plugin argument, to get
associated parent terms.

I think it can be helpful in your case.


How do I unpublish a user's content with rules?

The configuration would look like this:

Build a view that, when given a user ID as input, lists all the
nodes that that user has posted.
Use view style bulk operations, and select the action unpublished
node.
Set up a rule that triggers on user updates. (Is there one? I'm not
sure...) As condition, compare the roles before and after user save
to see if anything should be unpublished. As an action, let it call
the view from.

Use this idea you can do that


Entity reference of a menu link gives Restricted access instead of the real data

Here is an issue I found on drupal .org: https://drupal.org/node/2153463

There is a patch inside to fix the issue but it doesn't seem like the final patch, so decide if you want to use it. Your alternative is to use an old version of entity reference which doesn't have this bug.


Views Entity reference (user): how to show profile values of respective user only

came up with a solution that works for me.
first, ive added to the view the username field for the referenced users. this outputs the (two) different usernames of the people who are referenced.

second, ive added a global field as a filter called "Global: Fields comparison" that compares the name of the team_member with the name of the referenced user. now this shows only one correct entry.

hope this helps someone.


How to query solr server from php in Drupal 8

I managed to fix the problems with SolrClient install: https://stackoverflow.com/questions/41052999/php-warning-unable-to-load-dynamic-library-usr-lib64-php-modules-solr-so-und%C2%A0

This is how I can now query the solr server from php (right out of php SolrClient manual):

$options = array
(
    'hostname' => 'localhost',
    'port'     => '8983',
    'path'     => 'solr/sbn01'
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('*file/10*');

$query->setStart(0);

$query->setRows(50);

$query->addField('id');
$query->addField('its_fid');
$query->addField('ss_uri');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response);


How to place size of file in the node in the title?

Install Token and you can use [file:size] in your title to fetch file size. Here is the list of all file tokens you can choose from.


There is probably a better way, but when I've had to do this I just change the page title for each variant.  Of course, you probably don't want to do this on a live site, but if you have a test site it's not so bad.

Alternately, you could also add a CSS class, etc.


It turns out that this hook is a part of features, so I needed to do a drush fr my_module.


What is wrong in my XML structure to add nodes using a RESTFul web service POST?

After a lot of research about my question I've changed to json format, which works fine.

I still think I have an error in my XML structure, but since it works with JSON now, I switched to using that instead.

UPDATE: With this json data it works fine.

{ "title":"Test page",
  "type":"page",
  "status":0,
  "language":"es",
  "author":1,
  "body":{  "value": "Aptent bene capto euismod ...",
            "summary":"",
            "format":"filtered_html"
         }
}