How can I stop a Rule action from being executed, programmatically?

Once happened, you can't stop an action.

The only thing you can prevent from happening is executing the action at all. In case of e-mails, you can only stop an e-mail with rules if it has been sent by a rule. Then you need to add a condition to that rule to prevent it from executing the action that sends the mail.

To prevent a mail that is sent directly in the code, you need a custom module, implement hook_mail_alter() and redirect it to a dummy address, you can't really stop it there either.


Hide certain nodes in view listing for anonymous users

Drupal doesn't evoke hook_node_access() when executing a view; it's querying the DB directly to get the data. As such, you're not going to be able evoke the same PHP snippet to have Views filter the result.

The "best" way (read: simple) is to have views create a query filter that does the same thing; you can add a  Content: Country Hide filter (or whatever your custom field is named) with the Operator set to Is equal to and the Value set to GB.

That will filter the nodes as you need, but you'll still need to provide the context (i.e. is the user anonymous or not). Here it's unclear. There's no "best" because there's not one way to provide context and it will depend on your needs.

One idea that comes to mind is to add 2 View blocks, one with the GB filter and one without, and set the block to display depending on the user role. But again, this will depend on your requirements. There's always custom Views integration or, if you want to go the site builder route, other modules that provide context like Context, Panels, etc.


What to replace entity_uri() with in Drupal 8?

Try with this code:

$link = $node->toLink($node->getTitle(), 'canonical', $options);

Get more information about Node object here: "Node Object"


You need to use CCYY-MM-DD format

So use is between 2016-01-01 and 2017-01-01 which will print all 2016 nodes, don't worry, it will not print any 1st day of 2017 nodes. (tested it)

Use a group filter so you can change the name, if you expose the filter that is.


How can I have a second alias for a node to be displayed in a different view mode?

There are many approaches in aliasing and routing, but I think splitting the task between both is the most effective:

Add an internal node route for the second view mode:

mymodule.custom_node:
  path: '/node_custom/{node}'
  defaults:
    _entity_view: 'node.custom_view_mode'
  requirements:
    _access: 'TRUE'

Then change the source path to /node_custom/123 before Pathauto saves the second alias in hook_pathauto_alias_alter().


Get the displayed node of a commerce_line_item in a component rule using 'commerce_display_path', doesnt work

In fact returning variables (providers) from a custom php code doesn't work !
If you do it in a module the same code works !
Rules bug ??


How can I find out if the present theme version would work

Install the Upgrade Status module and then visit /admin/reports/upgrade-status and scan the Adaptive Theme and your sub-theme and get a report on all problems regarding Drupal 9 compatibility.

  This module scans the code of the contributed and custom projects you
  have installed, and reports on any deprecated code that must be
  replaced before the next major version. Available project updates are
  also suggested to keep your site up to date as project will resolve
  deprecation errors over time.

  Due to third party PHP library dependencies, the module needs to be
  installed with Composer.


How can I fix the "Deleted and replaced configuration entity" error during configuration import?

The error happens when entity you are trying to create already exists. Or the data changed while config import was in progress. See: ConfigImporter.php/checkOp().

  If the target already exists, use the entity storage to delete it again, if is a simple config, delete it directly.

Running import twice may help, but obviously not at the same time, otherwise, you probably need to remove that field manually and try again.

This could be a bug of the module, as normally modules should have the following condition in place, e.g.

 /**
  * Implements hook_ENTITY_TYPE_insert().
  */
 function hook_ENTITY_TYPE_insert(RoleInterface $role) {
   if (\Drupal::isConfigSyncing()) {
     // Do not change data while config import in progress.
     return;
   }
   // ...
 }

Related bug: The group_roles field gets created too early during configuration sync.

Few hints:

In case you don't need the particular import, you can use Config Ignore to ignore it.
Try exporting the config first, then import again.
Try importing config individually first, file by file by using Drupal Console, e.g.

drupal config:import:single --file=$PWD/config/sync/config_ignore.settings.yml


Create form for image selection from the content

Like most things in Drupal there are a couple of different ways you could do this. A quick look into the challenge, reveals the Webform View module. Basically, it allows you to pull in a viw (list of your nodes) as selectable items, for a webform. Webforms are good if all you want to do is store (and email of course) the submitted values of a form for manually processing later. Webforms are typically used for feedback, survey, contact forms.

If you need to do something a little more flexible with the submitted values, alternatively you could use the Views Bulk Operations (VBO) module (add-on for Views) which provides this kind of functionality plus a lot more if you need it for other purposes too.

Basically, you would create a view listing your content items with the fields you want to display, and then add a "Bulk operations: Content" field, and select the "Pass ids as arguments to a page", and then specify the path you want the arguments sent to. The path could then be defined in your custom drupal module, and you could use the $arguments = func_get_args(); to get all the arguments sent through. e.g. in a sandbox_test.module

function sandbox_test_menu() {
  $items = array();

  $items['test-submit'] = array(
    'title' => 'VBO Test Submission handler',
    'page callback' => 'sandbox_test_vbo_test',
    'access callback' => TRUE,
  );

  return $items;
}

function sandbox_test_vbo_test() {
  $output = '';

  $args = func_get_args();
  if (is_string($args[0])) {
    $items = explode(",", $args[0]);
    $output .= '<pre>' . print_r($items, true) . '</pre>';
  }
  else {
    $output .= 'None found';
  }

  return $output;
}


There is none.  To override it, copy modules/system/html.tpl.php into your Seven subtheme and change that.  Remember to clear cache to make your changes visible.

(Don't hack Seven directly, next core update will overwrite your changes.)


Cannot find out what is rendering a view block?

I have just found out that the Context module is installed which was rendering the block on those pages.

The "Themer Info" should have indicated that somehow.


Getting libraries to load with newer jQuery using jqmulti

If you have checked "load even if no libraries are assigned", jQuery 1.7 should load regardless of anything else you do. So in your HTML you should see Drupal's jQuery loading, and you should also see jQuery1.7 loading, and also a script called switch.js, which takes care of the noConflict() mode. If you don't see those loading, there is a problem that's not related to your hook. Check the jQuery Multi settings page, does it list the jQuery version it's using?


Views Filter by Field value (content type A) = Field value (content type B)

Install Equi Join.

  The Equi Join module allows you to create relationships between
  different entities based on an arbitrary field. This allows the use of
  relationships in Views without having to add Node References to a
  content type, which may not be an option when displaying data stored
  on a third-party database or data provided through custom Views
  handlers. That said, it works with nodes as well.

I must confess, I have never used this module before now, so my method of getting it to work was by trial and error. Here goes:

In your view, add a relationship Equi Join: Content, and configure both left field and right field to be on field 'ID' (I am assuming you re-used the ID field for both Employee A and Employee B. If not, adjust as appropriate). Make sure to provide a unique Identifier (will be used later to identify the relationship).

Add all the fields from Employee A and Employee B. For each of the fields of Employee B, make sure to add the relationship of the equi join.

Add Filter Criteria for each of the fields (AND). For all of them, Operator must be Is not empty (NOT NULL). For each of the Filter Criteria using fields on Employee B make sure to add the relationship of the equi join. If you have a required field on any of the Employee Types, then adding just that one required field would be sufficient for that Employee Type. If none of the fields are required, then you might end up filtering out a legitimate row with empty values. So best if each employee type has at least one required field on it.


How can I limit the maximum weight of an order?

Alright, I'm definetly not sure, if this is the intended way of doing things, but I did it now this way via a custom cart event subscriber:
modules/custom/my_checkout/my_checkout.services.yml:
services:
  my_checkout.cart_subscriber:
    class: Drupal\my_checkout\EventSubscriber\CartEventSubscriber
    arguments: ['@messenger', '@commerce_cart.cart_manager', '@string_translation']
    tags:
      - { name: event_subscriber }

modules/custom/my_checkout/src/EventSubscriber/CartEventSubscriber.php:
<?php

namespace Drupal\my_checkout\EventSubscriber;

use Drupal\commerce_cart\CartManagerInterface;
use Drupal\commerce_cart\Event\CartEntityAddEvent;
use Drupal\commerce_cart\Event\CartEvents;
use Drupal\commerce_cart\Event\CartOrderItemRemoveEvent;
use Drupal\commerce_cart\Event\CartOrderItemUpdateEvent;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\TypedData\Exception\MissingDataException;
use Drupal\physical\Calculator;
use Drupal\physical\Weight;
use Drupal\physical\WeightUnit;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CartEventSubscriber implements EventSubscriberInterface {

  use StringTranslationTrait;

  /**
   * The messenger.
   *
   * @var MessengerInterface
   */
  protected $messenger;

  /**
   * The cart manager.
   *
   * @var CartManagerInterface
   */
  protected $cartManager;

  /**
   * Constructs event subscriber.
   *
   * @param MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(MessengerInterface $messenger, CartManagerInterface $cart_manager, TranslationInterface $string_translation) {
    $this->messenger = $messenger;
    $this->cartManager = $cart_manager;
    $this->stringTranslation = $string_translation;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      CartEvents::CART_ENTITY_ADD => [['guardWeight', 100]],
      CartEvents::CART_ORDER_ITEM_UPDATE => [['guardWeight', 100]],
      CartEvents::CART_ORDER_ITEM_REMOVE => [['guardWeight', 100]]
    ];
  }

  /**
   * @param CartEntityAddEvent|CartOrderItemUpdateEvent|CartOrderItemRemoveEvent $event
   * @throws MissingDataException
   */
  public function guardWeight($event) {
    $cart = $event->getCart();

    // @todo - this should be configurable
    $maximumWeight = new Weight(40, WeightUnit::KILOGRAM);
    $orderWeight = new Weight(0, WeightUnit::KILOGRAM);

    foreach ($cart->getItems() as $order_item) {

      $purchased_entity = $order_item->getPurchasedEntity();
      // Calculate only items with a weight
      if (!$purchased_entity || !$purchased_entity->hasField('weight')) {
        continue;
      }

      $quantity = $order_item->getQuantity();
      if (Calculator::compare($order_item->getQuantity(), '0') == 0) {
        continue;
      }

      /** @var Weight $weight */
      $weight = $purchased_entity->get('weight')->first()->toMeasurement();

      $orderWeight = $orderWeight->add($weight->multiply($quantity));
    }

    if (!$orderWeight->lessThanOrEqual($maximumWeight)) {

      switch (get_class($event)) {
        case CartOrderItemUpdateEvent::class:
          $orderItem = $event->getOrderItem();
          $originalQuantity = $event->getOriginalOrderItem()->getQuantity();
          if (intval($orderItem->getQuantity()) > intval($originalQuantity)) {
            $orderItem->setQuantity($originalQuantity);
            $orderItem->save();
          }

          break;
        case CartEntityAddEvent::class:
          $orderItem = $event->getOrderItem();
          $cart->removeItem($orderItem);
          $orderItem->delete();
          break;
      }

      $this->messenger->addError($this->t('You would exceed the maximum order weight of @maxWeight, we could not update your cart.', [
        '@maxWeight' => implode('', $maximumWeight->toArray())
      ]));
    }
  }

}

It works well, but the "Your cart was updated" message is unfortunately still there. My guess is, it is still not the best location for this kind of logic.


Manually enter cck field data into database

I can't say I'd advise manually inserting data into the database (there are a lot of API functions for CCK that will help you to do this), but that's for another question.

To make sure the node is reloaded from the database after you've inserted your record(s) just run this code:

$node = node_load($node->nid, NULL, TRUE);

The third argument to the function is $reset, which if TRUE will force the node to be built again from the database, not from the static cache.


How to display jQuery UI dialog in submit button's onclick and prevent form submission?

when c.curCSS is not a function error occures ,just do the following
if any two js included check and remove .. after add this into script

jQuery.curCSS = jQuery.css;


Save and set an external link image programatically

Well, I think it is supported. I found an exact solution I need to be able to save and set an external image source inside Drupal according to Programmatically update node image field (using URI of the image) and get URL in twig.

I use this method system_retrieve_file.


How can i only allow published content to appear on the front page?

As far as I know scheduler module is not responsible for promoting or not nodes to the frontpage, so you have to go with a custom solution.
Try to implement hook_node_presave as follows:
/**
 * Implements hook_node_presave().
*/
function my_module_node_presave($node) {
  $was_published = !empty($node->original->unpublish_on);
  $now_is_unpublished = empty($node->unpublish_on);

  if (!$node->is_new && $was_published && $now_is_unpublished) {
    $node->promote = 0;
  }
}

Hope that helps!


Render all items of the main menu on one page

You can try with dhtml menu.

download dhtml module
http://drupal.org/project/dhtml_menu
Configure menu setting
admin/config/user-interface/dhtml_menu


How can I render an image_field from within hook_block_view?

I think a combination of field_get_items() and field_view_value() would do the trick:

$image_items = field_get_items('node', $node, 'field_image');
$image_view = field_view_value('node', $node, 'field_image', array_shift($image_items));

$block['content'] = render($image_view);


I need to unset terms from the drop down

I think I need more information.

In general, I believe you set the #default_value on your dependent form element to be the parent element, and also set the #ajax callback and wrapper on the parent. Check out the Ajax example and the form API reference.


Drupal 7. Replacing core links with their aliases in theme templates

Not sure if this is what you're after, but
in your tpl.php file you can change

Contact

to

<a href="<?php print url('node/1');?>">Contact


A view to display only nodes related from user field

In Views add a relationship to the "Entity Reference: Referenced Entity", then add a contextual filter for UID with a default value taken from the URL.

See also http://codekarate.com/daily-dose-of-drupal/using-views-entity-reference-module-drupal-7


Ajax Framework Using Dynamically Generated Links

you are probably missing the part to add behaviors to your new elements:

Drupal.attachBehaviors('.use-ajax');


As far as I'm aware, changing default.settings.php won't do anything. This file is only there to be copied into settings.php when the site is first installed - so if you change it after settings.php has been created it will do nothing at all.

You might try this module for proxy settings (though don't believe it when it claims to have a working version for D8)


The first step is using private files, because you can not control access to to public files as Drupal is not involved when they are delivered.

Private files in plain file fields (file and image, not media entity) automatically respect node access and will only be accessible if the user has access to at least one node that is using the file.

As you mention that users can bypass node access, I assume you have node access already implemented and it should then just work


Upgrading complex content types from D6 to D7

I had the same Problem, but when you follow cck upgrade procedure step by step, it works. I think you need additional Variable Check Module. After upgrade i had 2 corrupted vars. With Variable Check you can find corrupted vars and remove them.

My solution:

many cck fields are included in core
download and unpack missing modules in to sites/all/modules
download "cck 7.x version", "variable check" and unpack
after upgrading activate "Variable Check" and "CCK Content Migrate" modules
run upgrade.php
under admin/reports/variablecheck check the validity of settings in the variable table


Primary menu not showing when lanugage is changed?

Since Menu items are user created the Locale module cannot translate them all.. You have to manually create translation for each menu item for both the languages and it maps according to the language.


Replace the drop-down in Views with an image map

Strictly off the top of my head here...

You should be able to point the theming of an exposed filter to a custom theme function. Take a look at Better Exposed Filters for how to do so -- it's different between Views 2 and 3 and a little different between D6 and D7. The key will be to build the image map such that the URLs it redirects to are the same format that Views is expecting. Eg: test?field_animals_value[]=Dog

'Course you won't be able to use this solution with any filter on changing content without updating the image map....


How to place the page title and local tasks tab in a Panels region?

If you're just wanting to do that for a single variant, you may need a combination of panels configuration, e.g adding local tasks and page title to region as well as either hook_preprocess_page or perhaps hook_ctools_render_alter to remove the page title and tabs from default output based on path or other criteria.

For example:

template.php

/**
 * hook_preprocess_page
 * Alter variables for the page template
 */
function THEME_preprocess_page(&$vars){
  // If on a node page
  if ($node = menu_get_object('node')) {
    // Remove page title and menu tabs for this node type
    // as they're output in the panel variant instead
    if ($node->type == 'my_type') {
      $vars['title'] = FALSE;
      $vars['tabs'] = FALSE;
    }
  }

}


Since you're already loading the form, your switch statement won't do anything. If you want to skip the page, you'll need to implement hook_commerce_checkout_router() in your module so that you can control if it shows up or not.


How to get the product id on hook form alter

If You alter 'Add to card form', try this code

$form_state->getFormObject()->getEntity()->getPurchasedEntity()->product_id->getString();


How to prevent granting Userpoints again after a user already passed a Quiz?

You might use the Rules module to take away the role which has the permission to take the quiz once the quiz has been completed.


Filter view content by data in text field

targetUser is meant to collect the uid of a user that a current app
  user is sending a message to

IMO the better approach would be to make targetUser an entity reference field.

Download and install the Entity Reference module

In content type Message fields, add a new field with Entity Reference and a widget of Auto complete (tag style)

For example: I named mine lalala (click picture below to enlarge)

For Target Type, select User
Number of Values: Unlimited (as you could send a message to multiple users)

Then add or edit a message node and start typing user name, you will see the name in the drop down, select it and save.

Use a comma , to add other user account.

In your view

contextual filter of Logged in User id (uid)
add a relationship of lalala Referenced Entity

If not, try Referencing entity, but if my memory is correct it's Referenced

Result: you should get a view of all the nodes where the logged in user was referenced.

  The autocomplete only allows by username, and not uid. E.g. posting 47
  into this field isn't allowed?

Create a new USER view.

1) click on +Add

2) Select Entity Reference

3) Remove user:name and add user:uid

4) click on settings and checkmark uid (if you don't do this step, it won't let you save the view)

Go to your Content Type Messages manage fields and edit your entity reference field.

At the bottom check mark ✓ Render Views filters as select list
Change to mode to View and select your view.

  Also, "logged in user id (uid)" isn't an option? Just (author) User:
  Uid ?

You will need to create a CONTENT view and then add:

Relationship of Referenced User
Now since you have a relationship User: Uid becomes available as contextual filter


Why does Drupal use the database for the cached data?

The question that asked here is not whether the database cache can be replaced by something else, but why Drupal caches database information in the database. A reason that is not mentioned here is that although database information is again cached in the same database, it is not cached in the same format. The original data, such as node information or theme information, is stored in a kind of normalized form, which makes it easy to edit and query data. The cached values are stored in a way that reduces the amount of processing needed to display a page.

Let's say a page view consists of the following simplified steps:

Fetch information from database
Manipulate information to make it suitable for display
Display the result

Now Drupal stores the result of step 2 into the database, so on subsequent page views, steps 1 and 2 do not have to be executed. This saves time and processing power. When the original data changes, the cache needs to be cleared.


Maybe a combination of blog module and Subdomain module:

  Automatically creates subdomains and places content on them. There are
  4 modes:

  User: e.g. "Mary" and content at http://mary.example.com

  Taxonomy: e.g. "Seattle" and content at http://seattle.example.com

  Organic Group: e.g. "MyGroup" and content at
  http://mygroup.example.com

  Content type subdomains: e.g. "News" content at
  http://news.example.com


How do I consume REST data with an external service?

I actually have implemented a similar thing in my project.

I created a module structure like as follow.

 my_module [directory]
        products [directory]
          products.info.yml
          products.module
          products.routing.yml
          src[directory]
            Controller[directory]
              - ProductsController.php
          templates[directory]
              - products-list.html.twig
        my_module.info.yml
        my_module.module
        my_module.routing.yml

products.routing.yml

 products.list:
    path: '/products'
    defaults:
      _controller: '\Drupal\products\Controller\ProductsController::getList'
      _title: 'Get List'
    requirements:
      _permission: 'access content'

src/Controller/ProductsController.php

    /**
     * @file
     * Contains \Drupal\products\Controller\ProductsController.
     */
    namespace Drupal\products\Controller;

    use Drupal\Core\Controller\ControllerBase;

    /**
     * Controller routines for products routes.
     */
    class ProductsController extends ControllerBase {

      /**
       * Callback function to get the data from REST API
       */
      public function getList() {

        $data = array();
        $response = $data = $result = null;

        if (function_exists('my_module_reponse')) {
          $response = my_module_reponse('http://webservice.com/products/list', 'GET');
        }

        if ($response) {

          $result = json_decode($response);
          $data = array();

          // # add all the data in one multiple dim array
          $data['title'] = 'products to consume REST API';
          $data['users'] = $result;

          // display the content in the middle section of the page
          $build = array(
            '#theme' => 'products_list', // assign the theme [products-list.html.twig]
            '#title' => 'products to consume REST API', // assign the page title
            '#pagehtml' => 'data is coming from : products/list ', // assign the string message like this
            '#data' => $data
          ); // assign the array like this to access in twig file
        }
        return $build;
      }
    }

templates/products-list.html.twig

 {{ data.title }}

 {{ pagehtml }}

  {% for item in data.users %}

{{ item.yourproductnamekey}}

  {% endfor %}

my_module.module

      /**
       * @file
       * Test API module.
       */
      function my_module_reponse($url, $method = 'GET', $params = array()) {
        $methods = [
          'POST',
          'GET',
          'PUT',
          'DELETE'
        ];
        $result = array();

        try {
          if (empty($url)) {
            throw new Exception("Invalid url");
          }
          if (in_array(strtoupper($method), $methods) === FALSE) {
            throw new Exception("Invalid method");
          }
          else {
            // will need a request call for GET, POST, PUT
            switch (strtoupper($method)) {
              case 'GET':
              case 'POST':
              case 'PUT':
              case 'DELETE':
                if (function_exists('my_module_call_request')) {
                  $result = my_module_call_request($url, $method, $params);
                }
                break;
              default:
                throw new Exception("Invalid method");
                break;
            }
          }
        }
        catch (Exception $e) {
          echo $e->getMessage();
        }

        return $result;
      }

      function my_module_call_request($requesturl, $method, $params = array()) {

        // request url
        $url = $requesturl;

        try {

          // initialized curl
          $ch = curl_init();

          // set header for curl request
          $headers = array(
            "Cache-Control: no-cache",
            "Pragma: no-cache"
          );

          // set required setting with curl configuration
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
          curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);

          // pass the additional values
          curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));

          // close the curl connection
          $result = curl_exec($ch);
          curl_close($ch);

          return $result;
        }
        catch (Exception $e) {
          echo $e->getMessage();
        }
      }

products.module

    /**
     * implements hook_theme();
     * description: create the file as per below
     * eg : products-list.html.twig  for "products_list"
     */
    function example_theme($existing, $type, $theme, $path) {
      return array(
        'products_list' => array(
          'variables' => array(
            'pagehtml' => NULL,
            'data' => NULL
          )
        ),
      );
    }

Each submodule will contain the individual routing file and function related to each page. It will make easy for you to maintain the code as well.


How to avoid the error 'array expected string given' in db_query

You're using Drupal 6 syntax, you need to convert it to Drupal 7 syntax:

db_update('users')
  ->fields(array('name' => $name, 'mail' => $mail))
  ->condition('uid', $account->uid)
  ->execute();

See the Database API docs for more details.


How to get current language of node in twig?

A more elegant Drupal way without typing code:

Go to the Manage display of the content type of your node (/admin/structure/types/manage/YOUR_CONTENT_TYPE/display/full). Select your display mode (or use the default). You will notice the field 'Language', move it to the upper side so it gets out of 'Disabled'.
Once you have done that, the language of the node is available in Twig. You can access the id this way {{ node.langcode.langcode }}; or you can access the whole Object to get other data like the name {{ drupal_dump(node.langcode) }}


Delete hundreds of nodes by ID programmatically

You want to avoid deleting directly from the database. The node system distributes its data across a number of tables. Generally you always want to use the API. The method your after is node_delete() which takes the nid as its single argument. This will handle deleting all the associated data and firing off any hooks that are attached to the event.

An alternative approach:

Download and install the "Devel" module. This then gives you access to a page at /devel/php where you can run arbitrary PHP code within Drupal.
You could write custom code to load the text file and explode the nid's into an array. Something like this:

$nids = file_get_contents("/path/to/file");
$nids = explode(",", $nids); // This will depend on how your nids are delimited. Could be line break "\n"
foreach ($nids as $n) {
  node_delete($n);
}


Where can I save a CSV file that I construct dynamically to make it available for download?

The best practice is to use Drupal functions, not direct PHP functions, if there is Drupal API available. Particularly, here you may be interested in file_save_data and file_unmanaged_save_data.

If you want file available for short time, unmanaged file may be the way to go. But if you want periodic exports, archiving of prepared files, automatic clean-up etc, Managed is the way to go. If in doubt, try managed.

Examples for Developers offers a pretty good file_example.module, read it, play with it, and come back with more specific question.


Step 1) Install Date module.

Step 2) Enable the Date Popup module (comes with the Date module).

Step 3) Add code like the following:

  $form['date'] = [
    '#date_label' => 'above',
    '#type' => 'date_popup',
    '#date_format' => 'm/d/Y',
    '#datepicker_options' => [
      // limits date picker so no future date can be picked.
      // remove this section if you want to allow future dates.
      'maxDate' => "+0D",
    ],
    '#required' => TRUE,
    '#attributes' => [
      'autocomplete' => 'off',
    ],
  ];

Result:


I use this in my module to prepopulate the forms with data when hooking on FORM_ALTER:

$form['field_history_patient_id'][LANGUAGE_NONE][0]['value']['#default_value'] = "whatever";

But when defining the form it is enough to do :

$form['field_history_patient_id']['#default_value'] = "whatever";


Get a multiple value listing of related node IDs using Relation module and Views node ID field

A work around which could come in mind to an experienced Drupal site builder is to use Views module to get more flexibility in showing other fields of related entities listed instead of titles, by using the Views relationship advanced settings in connection with an existing field of related items like node ID.

Sadly the multiple value field handler of Views only appears on the Relation endpoint field itself, added directly in your Views view, but not in the node ID field by using the proper Views relationship to the relation <-> for this purpose.

The expected behavior is, that you are able to activate and modify multiple values of the related node ID field now in the node ID field settings like you did in the endpoints field before. But sadly that's not the case. You will always get the first related node ID or many duplicate records depending on how much related items you have with each related node ID per Views view row.


Attach an image gallery carousel to nodes

Check out Adding a jQuery Image Carousel to your Node View.

Though the above article is for Drupal 6, you can follow this like below:

As the gallery is referenced in the "Article" content type, you can modify the template file for that content type, and fetch the gallery images.
After that, you can display that in carousel.

The other way is using a theme preprocess function.

function YOURTHEME_preprocess_node(&$variables) {
  // Your code.
}


One possible reason could be the apparent failure to refer the your custom module in your project settings.js. This file resides in mobile/app/modules/custom/gsam/www/app. Edit the file and add the following code in the custom module section:

Drupal.modules.custom['gsam'] = {};

drupalgap.settings.front = 'hello_world';


How do I index custom fields with the search API using elasticsearch?

You seems to have provided link for creating custom fields using processor. Processor works smoothly for me.

Create custom fields using processor.
Make sure your name spaces are done correctly.
Enable your processor from the processor tab of Elasticsearch ui in Backend.
Go to "fields" section. You will see your added field there.
Finally Index item.


Those options are provided by the Pathauto module.

At time of writing, the Drupal 8 version of Pathauto is unfortunately not usable; you can follow progress here


Intending to select user role while creating the node to control the node visibility

try one of the following:

Node Access:

  The modules provide roles and user specific security permissions for
  menus, menu items, nodes, and security integration into the
  administration and help systems.

nodeaccess:

  Nodeaccess is a Drupal access control module which provides view, edit
  and delete access to nodes. Users with the 'grant node permissions'
  permission will have a grant tab on node pages which allows them to
  grant access to that node by user or role.

Content Access:

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.


You have at least 3 options:

If you're requiring all of the products to be bought together, you could use Commerce Bundle to create a Bundle Group product, and then add all of the individual bundle groups (e.g. a top, a bottom, and a pair of shoes) to it. This would then give you the ability to have all three products on a single page, but it'd require you to buy all 3 as a bundle.
You could create a node or a taxonomy page that simply references the node or products using entity or product reference fields. This would then give you multiple separate add to cart forms on a single page, (basically taking the three pages and combining them together).
Use Commerce Add to Cart Extras (or Commmerce's built-in views plugin) and build views which you could display on a node, panel, etc. Add to Cart Extras would allow you to build a form which would allow for bulk purchasing as well.


Custom Entity field of type long_text not storing values

After realising few minutes later, the column name should be supplemental not supplemental__value.

I was mapping content by looking into database columns which was wrong.


I ended up using the variable debug module, which was incredibly useful in helping me find out the expensive variables I had.


How do I enable Backlinks View and What Links Here?

Were you using Reverse Node Reference? Now in Drupal 7, you have reverse references available to you in views:

So you can use those relationships to go and load other content from one base content type (e.g. list blog posts or other products that reference this node or product).

Ideally, though, you might use EVA or or Views Field View to attach a view to an entity via a field. That view would use a base of whatever type of content or entity you were wanting to display, and then you'd just a contextual filter to limit it based on the field that references it.

Secondly, Commerce Kickstart doesn't use Solr out of the box, but it does use Search API. You can use Search API with Solr but faceted search and regular search do not require Solr. You can have Solr index entityreference fields and Views can use them, but all that does is change which checkbox you select in your Views config and not how you actually create the View.


How do I pre-configure default blocks for my drupal 7 theme

You can't control this from the theme at the time it's being enabled.

Drupal will try to assign each block enabled for the default theme to the same region in your theme, if available. If there's no region with a coincident name, it will drop the block to the default region, that is the first region defined in your theme's .info.

So there're two things you can do:

use more standard region names (sidebar_first, sidebar_second, footer)
in theme's .info, declare in the first place the more suitable region for orphaned blocks


How to show the author of Blocked users's Content as anonymous in Drupal 7?

You may use

function theme_username($variables)

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_username/7.x

$username = $variables['name'];

Check if user blocked

$variables['name'] = 'anonymous';


Trouble getting block to display after module enabled

your hook_block_view() is implemented in a wrong way,

first pass in argument delta as a parameter
you should put the contents of your block inside the $block['content'] variable.
return $block;

heres a very good tutorial
building a custom block


I don't think you need special modules or methods. Just copying the files and exporting/importing the database is enough. A module like Backup and Migrate can help you on that task but is not a must.

Anyway and as an extra information there are some optional but good practices (tools):

Drush: Apart that it can help you on some tasks (clearing cache, enabling modules, etc) it also can help you make a database dump using a command like drush sql-dump > file.sql, then you transfer the database to your server and you can import the database with a command like drush sql-cli < file.sql. If you are using Drupal 8.4.* just make sure to use drush 8.1.12 or higher. Drush can also help you syncronize the local dev site with the production site and even clone the site (more advanced).
Git repository: It will help you track custom files and even the configuration using a sync directory. The good thing about this is that you actually don't "transfer" the files, but commit/checkout, it can help you on your development workflow. Some people commit also the drupal or vendor files, other people (like me) just commit the custom files (modules and themes) and commit the composer files (see next).
Composer. The good thing about this is that you just transfer the composer.json and composer.lock file and then on the production server just run the command composer install --no-dev and it will download all the drupal/vendor files including contrib, modules, themes, libs, etc that you specified in the composer.json file (so you're actually not transfering the files). Specifically for commerce, the project base of drupal commerce can be a good starting point. Just customize it as you want.
Config Split module. It will helps on spliting your configuration so you can have modules that are enabled only locally on your dev environment but not enabled on the production server (like explained here), so in combination with composer you can have downloaded and enabled the devel module locally but not in the production server (as an example).

This answer is not intended to give you a how to on the tools mentioned, but to let you know some tools that exists and can help you in the process of developing drupal sites in general, if them sounds new to you and you are interested in any topics, please look their documentation sites and look around the internet as there are plenty of information, tutorials and videos that will help you consolidate your own workflow.


How do I get an array of all entitytypes of a specific entity?

Do you mean "How do I get an array of all entities of a specific entity type?"

$ids = \Drupal::entityQuery($entity_type_id)->execute();

Because an entity can only be of one type, to get the id of the entity type:

$entity_type_id = $entity->getEntityTypeId();

Answer to the edited question:

"How do I get an array of all bundle id's of a specific entity type?"

$bundles = \Drupal::entityManager()->getBundleInfo($entity_type_id);

Or all content types, which are bundles of the entity type node:

$content_types = \Drupal::entityManager()->getBundleInfo('node');

This function will be moved to it's own class before Drupal 9:

\Drupal\Core\Entity\EntityTypeBundleInfoInterface::getBundleInfo()

This is provided as a service:

$content_types = \Drupal::service('entity_type.bundle.info')->getBundleInfo('node');


Get the Devel module installed and use the dpm() function, e.g.

function display_my_users_loft_data_grids_info_alter(&$info) {
    dpm($info);
}

Then perform whatever action it would take to invoke that hook, and you'll see the $info variable exported to the messages area for easy browsing.


Change Entityqueue autocomplete to an entity widget

Finally i solved it using Entity API & Entity reference view widget.

Entityqueue is prefect but it suffers from lake of good UX.


Field API - defining a field, attaching it to privatemsg, and populating it "behind the scenes"

There is no need to define your own field type, just use a simple text field. You are storing a string after all, no need to re-invent the wheel.

The entity_type of privatemsg is privatemg_message. Note that you are not required to specify this property as the purpose of it is to limit the field for certain entity types. Leaving it empty means that instances of it can be attached to any entity.

To hide the field, you could use a module like Field permissions which gives you fine-tuned permission-based control over all fields. What that module actually does is provide a user interface for hook_field_access(), so you can alternatively implement that hook yourself and simply return FALSE for the field you created based on the field name.


Quote from Moshe Weitzman, main drush developer

  Database prefixing is no longer supported by Drush. Its a relic from a
  prior era.

March, 2017.


Adding a CSS, JS and HTML code to a block

The link and the script can be added through drupal_set_html_head() head

drupal_set_html_head('<link href="http://stg.odnoklassniki.ru/share/odkl_share.css" rel="stylesheet">');

On clicks are not good practice in drupal. Behaviors are used in stead.

So in your block you can output

  0

You can then set a couple of behaviors in your own script, which you can put in a file and add using drupal_add_js()

 Drupal.behaviors.my_module = function (context) {
   // This will load on page load
   ODKL.init();
   // This will attach a click handler to the links
   $('.odkl-klass-stat').click(function() {
   ODKL.Share(this);
   return false;
   });
 };


There is a module for that (tm):

http://drupal.org/project/elysia_cron

Have a look at http://2bits.com/drupal-performance/improving-performance-drupals-cron-using-elysia-cron-module.html for more information about it.


Displaying arbitrary HTML (or webgl) inside a Drupal frame (Drupal 7)

Depending on your needs, you may also not want to create your HTML page containing a WebGL canvas as content managed by Drupal. Instead, you can create a custom module providing a single page with your canvas and the additional JavaScript and CSS files.

function MODULE_menu() {
  return array(
    'path/to/canvas' => array(
      'title' => 'Awesome WebGL application',
      'page callback' => 'MODULE_canvas_page',
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
    ),
  );
}

function MODULE_canvas_page() {
  drupal_add_js(drupal_get_path('module', 'MODULE') . '/module.js');
  drupal_add_css(drupal_get_path('module', 'MODULE') . '/module.css');
  return theme('webgl_canvas');
}

function MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'webgl_canvas' => array()
  );
}

function theme_webgl_canvas() {
  return '<canvas id="glcanvas" width="640" height="480">Your browser doesn\'t appear to support the HTML5 <code>&lt;canvas&gt;</code> element.</canvas>';
}

The MODULE_menu() is an implementation of hook_menu(). It declares a page available at path/to/cancvs and handled by the MODULE_canvas_page() function. The handler function adds JavaScript and CSS files using the drupal_add_js() and drupal_add_css() which allow the files to be aggregated into single .js/.css files (if that feature is enabled for the site). It then return the markup for the WebGL canvas. The markup is produced by a theme hook function (theme_webgl_canvas()) declared in MODULE_theme which is an implementation of hook_theme(). This allow the theme or other modules to change the markup.

Because a WebGL page/application would likely use a lot of custom JavaScript, you may also want to check the Managing JavaScript in Drupal 7 guide.


Use taxonomy terms to set node access for a user

I don't think you can set this up with Context.

There is Access by Term where grants (view, update, delete) are based on the relationship between the user->term<-node.


How do I use render() for my custom content?

There is no magic framework involved (just magic array structures). You just need to build up your array (Or in your case, extend $node->content in hook_node_view() if you want to alter how a node is displayed).

Basically, a render array is a nested array with properties (always start with a #) and child-elements, which are assumed to be another render-array. drupal_render() will then dig itself through and convert it to HTML.

There are basically three things you can do, define a #type (types are defined in hook_element_info(), see system_element_info) including the necessary properties, define a #theme function and the necessary properties or just simply #markup, which is simply going to print whatever is in it (Note that #markup actually #type => markup, which is added automatically)

A basic example:

<?php
$render_array = array(
  '#type' => 'cointainer',
  '#attributes' => array('class' => array('your-class')),
  'child_element' => array(
    '#markup' => t('Some text'),
  ),
  'a_table' => array(
    '#theme' => 'table',
    '#rows' => $rows,
    '#header' => $header,
  ),
);
$node->content['your_module'] = $render_array;
?>

Assuming that the node template uses render($content), this will result in
Some text
...

You can also directly return such an array in a page callback function, see userpoints_list_transactions() for an example.

I have a feeling that you are however asking the wrong question: Note that is only for rendering, you can not store anything in this structure. To store that, you should first create the necessary fields on your content types and put your data in it, if you don't want it to be just text within the body. Also have a look at Display Suite, which gives you a lot of control on how to display your fields.


Go to /admin/reports/status and take a look at your unicode library. If you don't have multibyte support, install it: http://php.net/manual/en/mbstring.installation.php

I.e. for ubuntu like systems it's sudo apt-get install php7.0-mbstring for PHP7.

EDIT:

You could try 'auto' instead of 'sql_ascii', and btw., you can skip the count() call and can just write $converted_data[] = drupal_...

END EDIT


in private message: also match last names in auto-complete of To-field

There is an issue in the Privatemsg queue with an incomplete patch, privatemsg_realname: Permits to search inside realname field using "LIKE %...%".  You're welcome to help re-roll and test the patch.

The patch is for 6.x-2.x but it could fairly easily be re-written for 7.x-2.x.


Solve this by element pre render callback and ife module.

function _custom_bootstrap_pre_render_input($element) {
    $types = array(
        // Core.
        'password',
        'password_confirm',
        'select',
        'textarea',
        'textfield',
        // Elements module.
        'emailfield',
        'numberfield',
        'rangefield',
        'searchfield',
        'telfield',
        'urlfield',
    );
    if (empty($element['#type']) || !(in_array($element['#type'], $types) || ($element['#type'] === 'file' && empty($element['#managed_file']))) || !isset($element['#id'])) {
        return $element;
    }
    $error = ife_errors('get', $element['#id']);
    if (!empty($error)) {
        $element['#attributes']['class'][] = 'error-tooltip';
        $element['#attributes']['data-content'][] = $error;
    }
    return $element;
}


How can I create Folder like Structure with n Key Value Pairs?

If its just hierarchial text/numbers/whatever content you want under "folders" you could try the built-in Book module. And then re-theme its display to have "parent" pages appear as folders and child-pages be your value fields (or pages). The nice thing you get here is some pre-built templates for "folder" indexes at every depth of the folder-tree.

Also the built-in book module supports HTML export and is pluggable so you can write your own custom book_export_xml() function, see:
book.pages.inc book_export($type, $nid)

Be aware drupal (book) pages nest at most 8 levels deep I believe by default -- I think there are work-arounds for this in the DB to go deeper (perhaps unlimited).

Or, you allow each user to have their own Taxonomy in drupal and try to use like Field Collection to allow users to create many values under a single term in the vocabulary.

Taxonomy sounds like it might meet your needs -- but you would likely have to make custom code something to allow users to create X number of taxonomies only they can see and manipulate.

Just fyi -- there is always a "maximum" in any dataset you have hardware constraints (RAM and harddisk) and can only store so much and still be responsive for the enduser. So be realistic and set yourself a max value, say 999 values per Key ....

Drupal can probably do what you want but it will take a fair amount of research.


It looks like two content types: Show and Episode. You'll want to look into the Entity reference module to relate episodes to shows. This adds an Entity reference field type. And you'll be using Term reference fields for tagging.


After a long and confusing time experimenting with a lot of various hooks, I finally found hook_node_access.

I'm not sure if I had tried it previously but it seems to do the trick.

I used the following code to test when any node of any type is being viewed at which point I test for the presence of an particular taxonomy and value to determine if I want certain roles to view and read the page:

function mymodule_node_access($node, $op, $account){
    if($op == 'view'){
        if( isset($node->field_accessibility['und'][0]) ){
            ....
        }
    }
}

I hope that helps @longboardnode


Undefined index errors when running cron.php

You shouldn't run cron.php throught php cli. basically you should have a line like this in your crontab file:

0 * * * * wget -O - -q -t 1 http://www.example.com/cron.php

but you also need to append security token to the url.

by reading Configuring cron jobs using the cron command page you will get a better idea of how it works.


How can I disable all outgoing emails from a site all at once?

The Maillog module is for exactly this purpose, as

  Maillog provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the drupal core.


Add content type machine name as body class

The code sample from your question could be extended to look like that:

function marienschule_preprocess_html(&$variables) {

  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {

    // Add node ID body class.
    $variables['attributes']['class'][] = 'node-' . $node->id();

    // Add content type machine name body class.
    $variables['attributes']['class'][] = 'node-type-' . str_replace('_', '-', $node->bundle());
  }
}


Is there any integration of the Entity registration module with modal forms?

Few alternative way may helps you.

Entity popup module.

  This module allows you to show an entity in a popup. For flexibility,
  it doesn't provide any popup plugins itself, but it provides a menu
  callback that allows you to load the entity into any popup you desire.

NG Lightbox module:

  Lightbox any Drupal page such as the login page or comment reply.
      Works with forms out of the box, including webforms, node edit forms and more.
      Lightweight, only 1.2kbs in D7. D8 uses cores modal.
      Default responsive theme for the lightbox that can be customised.


How to send auto email for new unapproved comments?

using simple_comment_email_notification

and will send email notification to the site email configured at admin/config/system/site-information without any configuration

using rules

Rules module allows you  to
Add reaction rule by going to admin/config/workflow/rules/reactions/add

  React on event > After saving new comment

And add action

  system > send email

NOTE: rules is still in alpha stage at this time so some things might not work as expected if at all (above procedure has not been tested)


How to alter the user login response data

OK, I'd like to post one more answer approach, using the response event listener (with thanks to @Berdir). This is the one I'm using in the end as it avoids duplicating the login function logic. The previous answer may still be useful if you want to alter the actual login logic flow as well.

The event subscriber class

<?php

namespace Drupal\example\Listener;

use Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Serialization\Xml;
use Drupal\Component\Serialization\Json;

/**
 * Class ExampleLoginListener.
 *
 * @package Drupal\example
 */
class ExampleLoginListener implements EventSubscriberInterface
{

  /**
   * @var path.current service
   */
  private $currentPath;
  /**
   * @var jwt.authentication.jwt service
   */
  private $jwtAuth;

  /**
   * Constructor with dependency injection
   */
  public function __construct($currentPath, $JwtAuth) {
    $this->currentPath = $currentPath;
    $this->jwtAuth = $JwtAuth;
  }

  /**
   * Add JWT access token to user login API response
   */
  public function onHttpLoginResponse(FilterResponseEvent $event) {
    // Halt if not user login request
    if ($this->currentPath->getPath() !== '/user/login') {
      return;
    }
    // Get response
    $response = $event->getResponse();
    // Ensure not error response
    if ($response->getStatusCode() !== 200) {
      return;
    }
    // Get request
    $request = $event->getRequest();
    // Just handle JSON format for now
    if ($request->query->get('_format') !== 'json') {
      return;
    }
    // Decode and add JWT token
    if ($content = $response->getContent()) {
      if ($decoded = Json::decode($content)) {
        // Add JWT access_token
        $access_token = $this->jwtAuth->generateToken();
        $decoded['access_token'] = $access_token;
        // Set new response JSON
        $response->setContent(Json::encode($decoded));
        $event->setResponse($response);
      }
    }
  }

  /**
   * The subscribed events.
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[KernelEvents::RESPONSE][] = ['onHttpLoginResponse'];
    return $events;
  }

}

and the example.services.yml entry

services:
  example.login_response_listener:
    class: '\Drupal\example\Listener\ExampleLoginListener'
    arguments: ['@path.current', '@jwt.authentication.jwt']
    tags:
      - { name: event_subscriber }

In this way, we can add the JWT access_token to the /user/login?_format=json API response.


Drupal 7: What's the schema of the 'data' column in the 'users' table?

There isn't a 'schema' as such, the values can be absolutely anything (that's why a serialised array is used rather than having statically defined fields).

From the user_schema() docs:

  A serialized array of name value pairs that are related to the user. Any form values posted during user edit are stored and are loaded into the $user object during user_load(). Use of this field is discouraged and it will likely disappear in a future version of Drupal.


Just saw the your form callback, seems like you are missing argument $form. Small Change as following

From:

function forms_grade_factors_delete_factor($form_state, $node, $component) {

To:

function forms_grade_factors_delete_factor($form, &$form_state, $node, $component) {


You probably want to look on the db_select documentation. I strongly reccomend on this comment.


Views information not bolding used templates

I finally found out the issue. I was using Role theme switcher and i have selected a new theme to test it. It seems that this does not work well with my production theme, and this conflict between themes makes the views template bug.
I have disabled one of the themes and it works.
Thanks for your time


I'd rather say, added granularity is exactly what has been achieved by introducing entity form ID's specific to their entity type, bundle and operation.

You can now target the form for a specific entity type and bundle with a specific operation when using hook_form_FORM_ID_alter(). Before this you had to check the bundle yourself and also figure out whether the node already had an ID or not.

The form ID will be composed of entity type identifier, bundle, operation and the _form suffix. (Compare EntityForm::getFormID().)

If you require a more generic form alter for ALL node forms, you can use hook_form_BASE_FORM_ID_alter() which will be invoked with the base form ID that is ENTITYTYPE_form for entities, so node_form for content entities.

The invocation order along with a description of all three hooks is actually well documented in the description of hook_form_alter().


The routing system uses pattern matching. You can define a parameter in the path that will be used as a variable.

If we look at this snippet of node.routing.yml:

node.add:
  path: '/node/add/{node_type}'
  defaults:
    _controller: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
  requirements:
    _node_add_access: 'node:{node_type}'
  options:
    _node_operation_route: TRUE
    parameters:
      node_type:
        with_config_overrides: TRUE

You can see the {node_type} in the path. This variable will contain the node type as specified in the path. You can use that as part of the requirement as you can see above, and it will also be available to your functions. \Drupal\node\Controller\NodeController::add receives the node_type variable as well:

public function add(NodeTypeInterface $node_type) {
  $node = $this->entityManager()->getStorage('node')->create(array(
    'type' => $node_type->id(),
  ));

  $form = $this->entityFormBuilder()->getForm($node);

  return $form;
}

Read Parameters in routes for more information.

And for forms:

example.user_form
  path: 'example/form/{user}'
  defaults:
    _form: '\Drupal\example\Form\ExampleForm'
  requirements:
    _permission: 'access content'

You can use the buildForm function and place the additional parameters after $form and $form_state.

namespace Drupal\example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Session\AccountInterface;

class BasicForm extends FormBase {

 public function buildForm(array $form, FormStateInterface $form_state, AccountInterface $user = NULL) {
    // Do something with $user in the form
  }
}


Default customer profiles re-added on order edit, even without address field present

I think the typical issue is that because the address field value includes a country code by default, it's always assumed to have data ... so my guess is that whatever mechanism the Customer Profile Type UI is using to disable those sections of the order edit form isn't actually unsetting or otherwise removing them from the forms themselves. I don't have experience with the module in question, but if you have the ability, you'd likely be better off writing your own form alter to disable those portions of the edit form.


'Username' as a field is not available to webform as it is not stored in the webform submission.

You need to add a Relationship to the User using the UID and then the User Name will be available to you in the fields section.

See more about relationships in this video


Removing the "*" from the path does trigger the redirection to the right page.

It seems to me the "*" is just confusing global redirect (maybe some setting not configured correctly in the module?), because the redirection is definitely not happening, and that might be the reason why google is indexing that.

I'd suggest double-checking the globalredirect settings in place.


Pass additional variable into existing twig template (Book module)

Drupal offers preprocess functions where additional variables for templates can be set up.

The naming convention is THEMENAME_preprocess_THEMEHOOK(). In your case, you want to add a variable for book-tree.html.twig. The machine name for this is the first part of the template, with underscores replacing hyphens. In this case it would be book_tree. So your function would be THEMENAME_preprocess_book_tree().

Preprocessors receive a single argument, an array. The keys of this array become the variables available in your twig template.

THEMENAME_preprocess_book_tree(&$vars) {
  $vars['book_author'] = some_function_that_gets_the_author();
}

Now the variable book_author will be available to your template.


Custom form that will change the hyperlink inside the email for a chosen radiobutton

To send an email with Drupal, you should first use hook_mail to define the email and then drupal_mail to send it with any variables. There is extensive docs on this on the Drupal API site.


Where is the information in the node_info hook displayed in drupal

You should see it on the add content page. If you don't, either you need to clear cache, the module isn't enabled, or the module is coded incorrectly.


Count the number of content flagged by logged in user

This work for me in normal block (no in views):

<?php
global $user;
$uid = $user->uid; //Logged in user ID
$result = db_query("SELECT COUNT(*) FROM flagging WHERE uid=:uid and fid=2", array(':uid' => $uid))->fetchField(); //fid = ID your flag
print $result ." flagged items";
?>


Write the value of a field as a css class to another field

Here is some sample code to help you further which adds a class on a field (field_image) based on the value of another field (List field of type text) (field_alignment).

You will need to implement 2 preprocess hooks:

On node preprocess to retrieve the objects / values of the fields and add extra datamember which contains the class value
On field preprocess to retrieve the previously added extra datamember and merge it with the default classes_array part of a field

function YOURTHEME_preprocess_node(&$variables)
{
    if (!isset($variables['field_image']) || !isset($variables['field_alignment'])) {
        return false; // if 1 of both fields is not available, don't do anything
    }

    $alignment = reset($variables['field_alignment']); // retrieve first item of array
    $variables['content']['field_image']['#extra_classes'] = array($alignment['value']); // add an extra datamember containing an array with the value of the other field
}

function YOURTHEME_preprocess_field(&$variables)
{
    $field = $variables['element'];
    if ($field['#field_name'] !== 'field_image') {
        return false; // only manipulate the image field
    }

    if (!isset($field['#extra_classes'])) {
        return false; // don't do anything if the array with extra classes is not available
    }

    $variables['classes_array'] = array_merge(
        $variables['classes_array'], $field['#extra_classes']); // merge the default field classes with the new added class
}

Update - When assigning class to field_image which sits within a field collection (named field_collection)

function YOURTHEME_preprocess_node(&$variables)
{
    if (!isset($variables['field_collection']) || !isset($variables['field_classes'])) {
        return false;
    }

    if (!isset($variables['content']['field_collection'])) {
        return false;
    }

    $alignment = reset($variables['field_classes']);
    foreach (element_children($variables['content']['field_collection']) as $index) {
         foreach ($variables['content']['field_collection'][$index]['entity']['field_collection_item'] as &$field_collection_item) {
              if (!isset($field_collection_item['field_image'])) {
                  continue;
              }

              $field_collection_item['field_image']['#extra_classes'] = array($alignment['value']);
         }
    }
}


These modules may help: Custom Search, Search Configuration


I received the same request once .. and what I need is this module og_role_override

  This module provides Core permissions to act as particular OG roles in
  specific group types.

  In other words, it creates permissions of the form 'Act as ROLE in
  GROUP-TYPE' for each role and each OG group type. Granting this
  permission to a Core role gives it the same permissions as that OG
  role, in all groups of that type.

  For example, you might want users with your 'site editor' role to be
  able to act as a 'board member' in all OG groups, without having to
  add them to each group, and without having to replicate all the OG
  permissions as Core permissions.

Hope it helps ..


How can I let images uploaded via ckeditor show their full url in a json request via REST?

You can relatively easily fix the images on the client using jQuery by following Correct Img Src Path with Javascript and Jquery.


How to automatically create nodes from a bulk file upload

Using Bulk File Nodes you can create unlimited number of nodes at once .

  Bulk File Nodes allows a user to upload or import many files at once, and have many individual nodes created, one for each file . Where this module significantly differentiates from other modules like Bulk Media Upload is that after uploading/importing the file(s), the user is given the opportunity to edit all of the fields for each node in a single form.

This module creates a node for each file and you can edit the fields of each node after uploading.

Solution 1

You are right, Bulk File Nodes works only with images. since you need to create nodes programmatically and assign the files to the nodes you can use the following code to create a node without a file field

$uid = SOME_USER_UID
$values = array(
        'type' => 'THE_CONTENT_TYPE',
        'uid' => $uid,
        'status' => 0,
        'comment' => 0,
        'promote' => 0,
        'language'  => 'en'
);
$entity = entity_create ('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('THE_TITLE');

$ewrapper->save();

But from Attaching image files to nodes programmatically in Drupal 7
 you can use the following code to attach the file to the above node

$filepath = drupal_realpath('misc/druplicon.png');
 // Create managed File object and associate with Image field.
 $file = (object) array(
'uid' => 1,
'uri' => $filepath,
'filemime' => file_get_mimetype($filepath),
'status' => 1,
  );

// We save the file to the root of the files directory.
$file = file_copy($file, 'public://');

$ewrapper ->field_file[LANGUAGE_NONE][0] = (array)$file;

This code should be above $ewrapper->save(); line.

Solution 2

You can also create the nodes without file fields as described above. and for each node with $node variable Programmatically Attach Files to Node.

// We have complete file path.
$file_path = '/whatever/path/to/file/sample.pdf';

$file = new stdClass;
$file->uid = $node->uid;
$file->filename = pathinfo($file_path, PATHINFO_BASENAME);
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;

// Save file object to make it a 'managed file'.
file_save($file);

// We will save file under this location.
$destination = 'public://PDFs/';

// Make sure destination directory exists before moving files to that path.
// This will create directory if it does not exists.
file_prepare_directory($destination, FILE_CREATE_DIRECTORY);

// Now attach file to the file field.
$node->field_pdf[$node->language][0] = (array) $file;

// Default file type field comes with this extra properties.
$node->field_pdf[$node->language][0]['display'] = 1;
$node->field_pdf[$node->language][0]['description'] = 'Our special PDF';

// Save node to make the attachment effective.
node_save($node);


How do you upload images to content other than articles

Enter images into your content fields. On Add content type, go to "Manage fields," and under "Field type" select "Image." This will allow you to upload an image into that content type. If you want to add a referent to the image with <img src="image URL">, I suggest you switching from filtered HTML to full HTML as input format of the node body.


Can you make the hook_menu() item title different from the page title?

No there's no way to do it with hook_menu().

The simplest way is what you suggested, using drupal_set_title() and the most efficient is what dobeerman suggested above: use phptemplate_preprocess_page() and alter $vars accordingly.

Honestly though, I would just use drupal_set_title() even if there is that extra db call you mentioned (unconfirmed). This is a tiny optimization and if performance is important to you, you should have some caching mechanism in place (Varnish, Boost, etc) and this extra call won't make a difference!


It isn't clean but I'm able to do this with hook_cache_flush. It's called when a cache clear has been called, before the cache has been cleared.


Alternative to "Vote Up Down" module for?

Use the Fivestar module for rating. Or the Rate module. Some more details about these modules (quotes included are from their project pages):

Fivestar:

  ... adds a clean, attractive voting widget to nodes and comments and any entity. It features:

  jQuery rollover effects and AJAX no-reload voting
  Configurable star sets
  Graceful degradation to an HTML rating form when JavaScript is turned off
  Support for anonymous voters
  Spam protection to keep users from filling your DB with bogus votes
  Easy-to-use integration with Views module for lists sorted by rating, or filtered by min/max ratings
  A Fivestar CCK field for use in custom node types
  An easy-to-use Form API element type for use in other modules
  Compatible with all versions of jQuery (1.0 - 1.8)

Rate:

  ... provides flexible voting widgets for nodes and comments. "The cck model for voting with Drupal".


In Panels under Settings -> Basic for your page there is a checkbox with the label "Use this page in an admin overlay." that you can use for this.


I tried conditional fields module which is in dev version to make it works!

  Conditional fields module, define dependencies between fields based on their states and values.


Why does YAML parser strippes out underscore?

It's actually a native YAML issue. As Saltstack's YAML Inconsistencies page observes:

  If a definition only includes numbers and underscores, it is parsed by YAML as an integer and all underscores are stripped. To ensure the object becomes a string, it should be surrounded by quotes.

It's fairly common practice; Java does it too, for example

So wrap your ID in quotes and it should be fine.


Install the Devel module.
Use the dpm() function, it will print out $form_id for all forms on any page you visit.

function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_id);
}


Try to exclude the field you're grouping by from display:


How to get the parameter value from an ajax call in the page controller?

Why do you want to use fetch() when your code is based on jQuery? There a plenty of examples using $.ajax() for POST requests:
/core/modules/quickedit/js/quickedit.es6.js
  $.ajax({
    url: Drupal.url('quickedit/metadata'),
    type: 'POST',
    data: {
      'fields[]': fieldIDs,
      'entities[]': entityIDs,
    },
    dataType: 'json',
    success(results) {
      // Store the metadata.
      _.each(results, (fieldMetadata, fieldID) => {
        Drupal.quickedit.metadata.add(fieldID, fieldMetadata);
      });

      callback(fieldElementsWithoutMetadata);
    },
  });

/core/modules/quickedit/src/QuickEditController.php
  public function metadata(Request $request) {
    $fields = $request->request->get('fields');
    ...

To make PHP accept POST parameters you need to specify the correct request headers. Default in $.ajax() is the contentType application/x-www-form-urlencoded
So when using fetch() start with this:
fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },

To get on par with $.ajax() you might need to tweak fetch() a little more or wait until core decides to change the Ajax libraries from jQuery to pure Javascript.


Getting a translated country name from an address field

The country name in the country list is already a translatable markup object. It's not possible to add new options to it. So your idea to translate the country name again, this time with a specific langcode in options, is right. But you have to get the untranslated string if you want to translate it again

t($full_country_list[$country_code]->getUntranslatedString(), [], ['langcode' => 'de'])

because how you do it you get the translated string when running the code in a non english language context and translating from a non english language is not supported.

Edit: this answer is valid for the core country list

$full_country_list = \Drupal::service('country_manager')->getList();

there are probably other versions in contrib, see comment from @Berdir.


how to get previous step values in next step in drupal multi step form?

There are so many ways to send data from one from to other.

You can use session
You can also pass value in url

Example of pass by value

function register_form_submit($form, &$form_state){
$name = $form_state['values']['name'];
$age = $form_state['values']['age'];

$data = array(
    'query' => array(
         'name' => $name,
         'age' => $age,
        )
    );

$form_state['redirect'] = array('/success', $data);
}

here is a link you can refer for send data

https://www.drupal.org/node/2064545


How to automatically unpublish / move to archive an article or node?

I think you can easily archive your goal with a bunch of module.

I guess with Rules that gonna help you to make some actions when the article will be unpublished. Flag module will help you to set a flag 'Archived article' and finally Scheduler that let your user to choose when the article will be archived.


How may I add a tab item in an OG that shows a Content Type related to that group?

Hope this will help you,

In Drupal 7, you can achieve this using creating a new MENU item via programmatically OR by VIEWS.

Programmatically:

Create a menu item

function test_menu() {
  ....
  //menu for shows a Content Type related to that group
  $items['node/%/og-content-type'] = array(
  'title' => 'OG content type',
  'page callback' => 'get_og_content_type',
  'page arguments' => array(1),
  'access callback' => 'og_content_type_access',
  'access arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'weight' => 5,
  );
  ...
  return $items;
}

Now give access to the tab

function og_content_type_access($etid) {
  if (access) {//check your condition. Based on this condition the TAB will show.
    return TRUE;
  }
  else {
    return FALSE;
  }
}

Now its time to embed your view

function get_og_content_type($etid) {//Im passing ID in case you want in views.
  $html = '';
  $html = views_embed_view('VIEWNAME', 'display_id', $etid);//embed view
  return $html;
}

Reference : views_embed_view

Using Views:

Just create a new VIEW, with path as node/%/YOUR_PATH, Contextual filters and Permission. Refer the images below

Create a NEW menu TAB now

Add Contextual filters, based on this filter the VIEWS content changes.

Final result

To create a custom permission in VIEWS, you can use PHP filter.

Go to admin > modules and enable PHP filter
Go to your VIEW >> Page settings >> Access and select PHP filter and add this code without PHP TAGS.

  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $entity_type = 'node';
    $etid = arg(1);
    if ($group = og_get_group($entity_type, $etid)) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

NOTE :

You can create you own permission using hook_permission and you can use that permission in VIEWS >> Page settings >> Access


Don't use low level session_destroy(), use the session manager instead:

\Drupal::service('session_manager')->destroy();

This will remove all session data and the user is logged out, if that's what you want. You still get a warning if there is no session, so you might want to check this first.

A better solution might be to use the symfony Session object

$request = \Drupal::request();
$request->getSession()->clear();

if you have set the session data in the request object or

$_SESSION = [];

if you have used the deprecated $_SESSION superglobal.

Normally you don't destroy the session or clear all session data, because there might be other modules that also use session data. Simply remove session variables in the same place where you have set them.

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

// remove later when you don't need the value anymore
$session->remove('mymodule.value');

When all modules removed their values the session is destroyed by Drupal automatically (for anonymous users).


I have seen a solution of this problem. The idea is to use addTag() in query and implement hook_query_TAG_alter(), where you have good old SelectQuery object.


How to make Language Switcher Block work with unpublished nodes?

I was finally able to track this change down. The source lies within a security announcement which led to the i18n-7.x-1.11 update. In /sites/all/modules/i18n/i18n_node/i18n_node.module, l. 124 there's a new line reading

'access' => !$matches[2] ? $node_translation->status : NULL,

This line shall prevent unauthorized users from even seeing the path alias of nodes they do not have access to. However, there's no real check of permissions, this line just allows the access based on the node's status. So, even for User 1 (Superadmin) the link to the translated node is inactive if the translation is unpublished.

Whether this is only a temporary fix because of the SA or even supposed to be a permanent solution, I don't know. But that's the way it is right now and if you need to switch between unpublished translations often, you might want to comment that line.

There is already an issue at d.o for that.


"Codebase is assembled with Composer instead of Drush" (but it wasn't!) message

It comes from a command file like policy.drush.inc.


How to allow multiple parents (menu items) for a single node

The meny system can't do that

The Drupal menu system does not support what you want to do. Each entry has exactly one parent (which is id -1 if at the top).

The taxonomy module however, can

One could map the menu structure onto a vocabulary tree. The complex part here will be the node <=> term mapping, as I'm not aware of a module for that.

However, it's also worth noting that given that nodes and terms are very similar in D7, it's entirely possible to just migrate to using Terms for your main content, if the multiple parents hierachy generally makes sense for you. This could avoid a lot complexity.

Other options

One also make something completely custom or build the hierachy directly onto the entities with entity references, or separately as relations.

Node hierachy

If there is a module that solves your problem, you should probably be using it. Since Node hierachy is apparently one such option, it's worth your attention. If it really is buggy, you may want to consider helping out with that, if it helps to avoid a large custom effort.


how to render a node field of a referenced node on the node form

You can create using Views a view with "Entity Reference" where you can make the rendered content you wish to add to the node. Than add a new field of type "Entity Reference" to the node edit form of this node type and set up in section "Entity selection":

Mode -> 'Views: Filter by an entity reference view"
View used to select the entities -> choose the view machine name you have created for this purpose

Additionally, you can provide a comma separated list of arguments to pass to the view.

To avoid some status messages like 'Do something on load', you should uncheck "Test behavior" in "Additional behaviors" section.

Hope it helps


How do you add rules to specify zero rate VAT when a VAT number is supplied?

The rules for adding zero-rated VAT to other EU countries when a valid VAT Number is supplied are added when you enable the 'Commerce EU VAT Intra-community Supply' module in the 'COMMERCE EU VAT' module group.


I Assume you just want a row counter (1, 2, 3…). Just add the field "Global: View result counter".


Why Views is ignoring my field override, and printing fields regulary?

views renders fields with his own template. I imagine you're using a view which show "fields", right? On each field settings inside the view you can check the following option:

"Use field template"

If you select this option the view will use the field template instead of the view template.


You can use below code to redirect anonymous user to user login page.

if ($js) {
  // Required includes for ctools to work:
  ctools_include('modal');
  ctools_include('ajax');
}

if (user_is_logged_in()) {
  $title = 'hello';
  $output = 'more hellos';
  ctools_modal_render($title, $output);
} else {

  ctools_ajax_command_redirect('user/login');
  ctools_modal_command_dismiss();

}

Or, If you do not want to display popup to anonymous user, then you need to check user is anonymous or not before redering the ctools popup link.

<?php if (user_is_logged_in()): ?>
Link 1
<?php else: ?>
Login
<?php endif; ?>


To Connect to MYSQL - How to access database array in setting.php

If you want to access the Drupal database from a standalone script.

Firstly, consider if you can put the PHP code in a Drupal module instead.
Secondly, consider bootstrapping Drupal in your PHP script

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', '/var/www/drupal');

// Bootstrap to database level for db api
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

You can then use the Drupal database API to query content from the Drupal database.

Thirdly, if connecting to a different database is required, consider defining the other database in settings.php and switching to a target database using db_set_active

// Settings.php
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupal7',
  'username' => 'drupal_user',
  'password' => 'drupal_password',
  'host' => 'localhost',
  'prefix' => '',
);

$databases['other_database']['default'] = array(
  'driver' => 'mysql',
  'database' => 'other_database',
  'username' => 'other_database_user',
  'password' => 'other_database_password',
  'host' => 'localhost',
  'prefix' => '',
);

Then you can switch between databases with db_set_active

// Query other database
db_set_active('other_database');
// $query = db_select('my_table'); // e.g
// Return to default database
db_set_active();


As described in Support for automatic entity updates has been removed, when a module needs to update its own entity, and the update must change the database schema, the module needs to implement hook_post_update_NAME(). That is what the Taxonomy module does in taxonomy_post_update_make_taxonomy_term_revisionable() to make its entity revisionable.
The key code lines in that hook, which show how a new entity field is added, are the following ones.
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();
$last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');
$entity_type = $definition_update_manager->getEntityType('taxonomy_term');
$field_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions('taxonomy_term');
$field_storage_definitions['revision_id'] = BaseFieldDefinition::create('integer')
  ->setName('revision_id')
  ->setTargetEntityTypeId('taxonomy_term')
  ->setTargetBundle(NULL)
  ->setLabel(new TranslatableMarkup('Revision ID'))
  ->setReadOnly(TRUE)
  ->setSetting('unsigned', TRUE);
$field_storage_definitions['revision_default'] = BaseFieldDefinition::create('boolean')
  ->setName('revision_default')
  ->setTargetEntityTypeId('taxonomy_term')
  ->setTargetBundle(NULL)
  ->setLabel(new TranslatableMarkup('Default revision'))
  ->setDescription(new TranslatableMarkup('A flag indicating whether this was a default revision when it was saved.'))
  ->setStorageRequired(TRUE)
  ->setInternal(TRUE)
  ->setTranslatable(FALSE)
  ->setRevisionable(TRUE);
$definition_update_manager->updateFieldableEntityType($entity_type, $field_storage_definitions, $sandbox);

In your case, the code for hook_post_update_NAME() would be similar to the following one.
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();
$last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');
$entity_type = $definition_update_manager->getEntityType('entity_machine_name');
$field_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions('entity_machine_name');
$field_storage_definitions['meanvalue'] = BaseFieldDefinition::create('float')
  ->setLabel(t('meanvalue'));
$field_storage_definitions['cca_topic_id'] = BaseFieldDefinition::create('float')
  ->setLabel(t('cca_topic_id'));
$definition_update_manager->updateFieldableEntityType($entity_type, $field_storage_definitions, $sandbox);

Replace 'entity_machine_name' with the machine name of the entity.


Assuming your view uses Show: fields.

Add type as a field, check mark the hide from view box.

Click on your field, in REWRITE RESULTS, checkmark rewrite outlput of field

In there, put
[field_name]

Then in CSS

.all-links { display: none; }
.all-links.article { display: block !important; }

Another solution, is to use Views Conditional

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views.

Then just do a simple condition if type is x, then [field_name]


Manage config translations programmatically

The answer from @Smartsheet eng is correct if you want to load and read a specific translation as a config entity, see also How to progragrammatically get NodeType translated value in D8?.

However, changing them is different, because the config entity can't be saved like that, it doesn't understand what is a translation and what's not. It will just overwrite your default language with that data. See also https://www.drupal.org/project/drupal/issues/2910353.

To actually manage a translation of a config entity, you have to directly interact with the config system, you can see how in \Drupal\config_translation\Form\ConfigTranslationFormBase::submitForm():

$config_translation = \Drupal::languageManager()->getLanguageConfigOverride($langcode, $config_name);

// Write the keys you want to translate on the config object.
$config_translation->save();


Autosave nodes, when editing or creating new ones, in database

I'm unaware of any existing production/beta modules with this functionality.
There's an old blog post available from 2014 that discusses the use of GarlicJS to save the current working version of the Drupal node you're working on in browser local storage:
https://www.shooflydesign.org/buzz/lightweight-autosave-for-drupal-with-garlicjs
Quote:

Garlic uses HTML5 local storage, supported by all browsers these days, to cache what you're writing as you write it. I like this solution because, unlike WordPress, it doesn't create a bajillion post revisions. The values are stored by your browser until your submit the form, at which point they're cleared out.

If you're open to updating to Drupal8 (likely not, I realize), then there's a new module available called AutoSave_Form that claims to do something similar to what you're asking for:
https://www.drupal.org/project/autosave_form
Quote:

The autosave form module comes with a configuration form, which could be found under Admin->Configuration->Content->Autosave Form. There the interval could be easily adjusted and decide whether autosave is turned on for content or config entity forms or for both. By default it is active only on content entity forms and currently it is being tested only with content entity forms. If support for config entity forms is required please feel free to open an issue if you find some bugs regarding config entity forms.
At the moment the autosave works only for entity forms, but it will be extended to cover regular forms as well.


Cck date field save not working properly

Check that the granularity on the field isn't set to year only. You can edit this by going to admin/structure/types/manage/[CONTENT TYPE]/fields and selecting "edit" on the appropriate field.


What @clive has mentioned is great if you want to use /user for this, but from a number of angles, I really don't like using it at all for this kind of thing.  I would like to say mostly from a style perspective, but actually more from a linking perspective, eg, an email or post that includes check out my cool profile on mototribe:  www.mototribe.com/user bollixing things up.

So, when I've done stuff like this, I include php logic in my block view along the lines of:

$global $user;
$block=array();
$node=menu_get_object();

if ($node->type==THENODETYPEWEARELOOKINGFOR && $node->uid==$user->uid) {
  // generate the block here
} else {
  // don't generate anything (or put something else in it's place)
}

return $block;

so the block is only generated when the currently logged in user looks at a certain node type that s/he owns.  Obviously I've not fleshed out all the isset()s or empty()s needed in prime time for the above but I am sure you get the jist.

Of course, I could also be talking total smack here if D7 user profiles aren't nodes, but this works great in D6 with content profiles :)


How to sync a Drupal calendar with an iphone/ipad Calendar?

The Date iCal module can be used for syncing a Drupal calendar in both directions. Some more details about it (from its project page):

... your one-stop shop for iCal support in Drupal. It provides a plugin for Views to enable exporting your site's calendar as an iCal feed, and a plugin for Feeds to enable importing external iCal feeds into your site's calendar.
Any entity which contains a Date field can be utilized by Date iCal for import and export of iCal feeds.

So it provides:

a plugin for the Views module to enable exporting a Drupal calendar as an iCal feed.
a plugin for the Feeds module to enable importing external iCal feeds into a Drupal calendar.


Filebrowser thumbnails "can not create img for private://"

This is a workaround I used to solve the issue:

[https://www.drupal.org/project/private_files_download_permission]

I don't consider this 'magic' to be a fix. There is a lack of documentation and/or a bug in the filebrowser module.

How can one raise an issue with the developers?

PS: Also, now have another issue with the filebrowser module: sort order is not being honoured in Grid view!


You do not have any exposed filters. Under "Filter criteria" you need to define a filter which is exposed to the user. The block will then show up

EDIT
You already set the exposed filters to be shown in a block in your views administration on the right side. Now you find a block with the exposed filters in your block administration page. Here you can set the visibility of the block - maybe just show the block under the path of this view.


How to set a "must be greater than a value" condition in Rules

Check what kind of field you have.  If you have an Integer field, "is greater than" and "is less than" will be available for Data comparison.  Perhaps you mistakenly set it to text?  If so, you may need to delete the field and create it again.


Commerce doesn't handle Sagepay Form Integration return

Turns out that Firebug Lite script in html.tpl.php was causing the issue:

<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js"></script>

Swiftly removed.


Filtering out duplicate dates from different nodes in views

If there was a way to do this purely in views, I haven't discovered it.

What I was able to do though, was to use templates to remove the second item if it had a date that matched another item.


How to create node reference fields in Drupal 7?

The project that maintains the Drupal 7 versions of the "node reference" and "user reference" field types is References.

Part of the code of CCK has been ported in core code, but some code is still living in third-party modules. CCK itself has a version for Drupal 7, which contains the code to update from Drupal 6 to Drupal 7 (among other things).


Unable to add list items in item-list.html.twig

There is no such thing as #value, you want #markup instead, There are also better ways to create links, although I'm not 100% sure right now if you can provide #wrapper_attributes then, but you can call getRenderable() on the link, then you get a render array and should be able to it on that.:

\Drupal\Core\Link::fromTextAndUrl($value['name'], \Drupal\Core\Url::fromUri('http://test.com'))


how to add other component (html tag, js, and css) in form module

you should add a library like this :

$form['#attached']['library'][] = 'my_module/mylibrary';

Create mylibrary.libraries.yml file with the content :

mylibrary:
  version: 1.x
  css:
    theme:
      css/my-css.css: {}
  js:
    js/my-js.js: {}

more documentation: https://www.drupal.org/developing/api/8/assets


How do I stop the site content from being internally indexed?

Go to admin/settings/search and set "Number of items to index per cron run" to 0.


Programmatically printing from field_collection array

You can use Entity View Modes to solve the first part.

Install/enable the module, then configure some new view modes for field collections.

Then, goto the Field Collections config, and do the Manage Display for your collections.  Configure the new view mode(s).

Now, goto the Manage Display for your nodes.  Click the settings gear for the field collection field, and choose your view mode.

That should set you up for your second part, which is rendering out a field twice.  There are several ways to do this, like this and this.  You would just need to make sure your duplicated field uses your other view mode.


How to convert Json data directly into xml - standardized way?

The Serializer component is a tool in your Drupal toolbox that should be used when you need to serialize and deserialize data from and to Drupal data such as entities. Unfortunately you cannot deserialize into a \StdClass without implementing your own normalizer.

Inject the serializer service into your class, and use the serialize method to normalize the non-Drupal decoded JSON array into XML.

// Inject this instead of using \Drupal
$serializer = \Drupal::get('serializer');
// Use json_decode or @4k4's example above and use associative arrays instead of object.
$json = json_decode('[{"S":"a","D":"b"},{"S":"s1","D":"m1"},{"S":"2","D":"3"},{"S":"4","D":"5"}]', TRUE);
// Unfortunately it seems that for an array serializer xml_root_node_name won't work so wrap $json in the root name.
$data = ['US' => $json];
// Serialize into XML.
$xml = $serializer->serialize(
  $data,
  'xml',
  ['xml_root_node_name' => 'US']);


The directory should be named dev.sitename.com.fr not sitename.fr. Also, you may find it easier to create a sites.php file from example.sites.php. I recommend that over directory naming.


How can I migrate the Domain publishing settings for nodes via SQL?

OK, I figured it out... The domain_access table is the one I need to migrate the data from and to.

Key is to rebuild permissions after updating the domain_access table, so the node_access table is updated with the latest domain publishing options.

So I executed the following SQL to migrate the old domain_access records in to the new DB, then update with the new nid values from the migrate_d2d mapping table:-

delete from destinationdatabase.domain_access
    where nid in (select destid1 from destinationdatabase.migrate_map_blognodearticle);

CREATE TABLE IF NOT EXISTS destinationdatabase.domain_access_tmp LIKE destinationdatabase.domain_access;

INSERT INTO destinationdb.domain_access_tmp (nid, gid, realm)
SELECT nid, gid, realm
FROM sourcedatabase.domain_access
where sourcedatabase.domain_access.nid in (select sourceid1 from destinationdatabase.migrate_map_blognodearticle);

UPDATE destinationdatabase.domain_access_tmp AS ds, destinationdatabase.migrate_map_blognodearticle AS new
SET ds.nid=new.destid1
WHERE ds.nid=new.sourceid1
and ds.nid in (select sourceid1 from destinationdatabase.migrate_map_blognodearticle);

INSERT INTO destinationdatabase.domain_access (nid, gid, realm)
SELECT nid, gid, realm
FROM destinationdatabase.domain_access_tmp;

Then ran drush eval 'node_access_rebuild();


In the block configuration, you should be able to choose which menu it uses.