How to print the node body in a custom block?

$dest_node->get('body')->getValue();

this will return an array. So,$body is an array.
If you want the Body field values, then get it by accessing the proper index of the $body array. i.e $body[0]['value']

just replace print $body; with print $body[0]['value'];


How can I pull the latest published revision for a referenced node using the CCK node reference field?

Which module are you using to get forward-revisions? Revisioning?

This just seems like a bug in node reference field in that it makes the assumption that the latest revision is always published (which is true in core).

http://drupal.org/node/738116 has a patch which seems like it fixes node titles on auto-complete widgets and in the list of nodes. But it falls short of completely fixing the issue.


How to make table-responsive in drupal views

Consider the Views Responsive Grid module. Here is a quote about it (from its project page):

... provides a views plugin for displaying content in a responsive (mobile friendly) grid layout. Rather than trying to force the standard Views grid display to work for mobile this provides the same functionality, but in DIVs instead of tables. Provided is also the ability to specify a horizontal or vertical grid layout which will properly stack the content on a mobile display.
Features:

Horizontal or vertical grid layouts
Custom classes for use with responsive themes

Of course, this requires the use of a contributed module (which is something you want to avoid as per the edited version of your question).
Assuming that it's OK to use a contributed "theme", you may should consider using a responsive theme, such as (popular) Omega or Zen themes. There is also the Beep Edition "theme", which (quote from project page) "is designed from the ground up as a mobile-first responsive theme". However that has like 5 module dependencies ...
For a list of way more (less known) responsive themes, refer to 26 More of the Best Responsive Drupal Themes. Quote from that link:

All of these free Drupal themes have responsive layouts, and they include great features like Bootstrap frameworks, Google Fonts, sliders, Font Awesome icons, Facebook integration, social networking icons, and more.


I found simple solution with this module Simple Password Reset


I've not had much luck with the plus1 module.  The 7 version is wonky.  If you're just looking for a plus 1 or like function and your fixed on the voting api then vote up/down May work for you.  You can create multiple voting fields and they are tracked separately as a field.  The widget may cause some layout issues so may I suggest using flags instead.

Why?  It's easy to add a plus1 type feature and flags can be formatted using views or flag_create_link() so you can put it every where and wrap it in any CSS div or span.  You can have as many as you'd like and it's all in the db and available to views.  You can even use rules so the system can react on a flag.  I've moved away from voting api in favour of flags.


How to override text field widget form in Drupal 8

You can create you own widget for textfield you will use in your forms each time you need :

<?php

namespace Drupal\your_module\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextareaWidget;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'your_widget_widget' widget.
 *
 * @FieldWidget(
 *   id = "your_module",
 *   label = @Translation("Your widget name"),
 *   field_types = {
 *     "string"
 *   }
 * )
 */
class YourWidget extends StringTextfieldWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = $element + [
      '#type' => 'textfield',
      '#default_value' => $items[$delta]->value,
      '#placeholder' => $this->getSetting('placeholder'),
      '#maxlength' => $this->getFieldSetting('max_length'),
      '#attributes' => [
        'class' => ['js-text-full', 'text-full'],
      ],
    ];

    return $element;
  }

}

You probably have to override settingsForm() with your maxlength settings.
You can do this for each widget type (textarea...)

Note that you can generate skeleton with this drupal command :

$ drupal generate:plugin:fieldwidget
$ drupal gpfw


Your file needs to be named

custom-page.tpl.php

Note the .php extension. You might need to clear the caches to make that change show up

You also need either a variables or render element property as outlined in the docs


Webform 8.x-5.0-RC3 can't set custom settings

Finally, I found the answer. Webform implement ThirdPartySettingsInterface so I can edit my form_alter function to do the following :

// Because hidden by default.
$form["third_party_settings"]["#access"] = true;
$form['third_party_settings']['quizzes']['details_categories'] = [
    '#type' => 'details',
    '#title' => 'Catégories',
    '#open' => true,
    '#input' => false,
  ];

  $form['third_party_settings']['quizzes']['details_categories']['categories'] = [
    '#type' => 'checkboxes',
    '#options' => \Drupal\avantages\Services\PopulationsService::getPopulationList(),
    '#title' => t('Catégories'),
    '#default_value' => "",
    '#required' => false,
  ];

And to access my data, within the Webform entity :

$webform->getThirdPartySetting("quizzes", "categories");


Probably a little late to respond, but I came across this thread this morning whilst looking for a way to override the breadcrumb in Drupal 7, it helped a little so I thought I would add my solution.

This creates extra crumbs based on content types and adds the current page to the crumb. I'm using this to add a crumb to a filtering view seen before the given node.

function MYMODULE_menu_breadcrumb_alter(&$active_trail, $item) {

    //STORE THE LAST ITEM
    $end = end($active_trail);

    foreach ($active_trail as $key => $crumb){

        //CHECK AGAINST NODE TYPE
        if($crumb['map'][1]->type == 'NODE_MACHINE_NAME'){

            //INSERT THE REPLACEMENT CRUMB
            $active_trail[$key] = array(
                'title' => t("Title"),
                'href' => 'PATH',
                'link_path' => 'PATH',
                'localized_options' => array(),
                'type' => 0
            );
            //RECREATE ITEM
            $active_trail[] = $crumb;
        }

    }

    //SHOW CURRENT PAGE IN BREADCRUMB BY DUPLICATING THE LAST ARRAY ITEM IN ACTIVE_TRAIL

    if (!drupal_is_front_page()) {
        if ($item['href'] == $end['href']) {
            $active_trail[] = $end;
        }
    }

}


How to get drush to list ONLY parent folders on module list command?

You are looking for the pm-projectinfo command.  See: http://drushcommands.com/drush-8x/pm/pm-projectinfo/

In Drupal, "projects" contain "extensions". An "extension" can be either a module or a theme.  drush pm-list will show a list of modules and themes; drush pm-projectinfo shows a list of projects.

UPDATE: If you want to convert an existing site into a reproducible, buildable script, you might also be interested in using Composer.  See https://github.com/drupal-composer/drupal-project and https://www.drupal.org/project/composer_generate


How to post correctly fields in views-view-fields.tpl.php?

The correct way is:

<?php print $fields["field_name"]->content; ?>

Note: Using views-view-fields.tpl.php will affect all of your views, which you may not want.

To target a specific view you need to use:

views-view-fields--[view-name]--[machine-name].tpl.php


This will help you

(function ($) {

Drupal.behaviors.exampleModule = {
attach: function (context, settings) {
  $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples

}

};
})(jQuery);

Read this https://drupal.org/node/756722 It will definitely help you.


Why does the same form/field appear diffently depending on the browser?

The primary confusion around this is that the widgets (the code responsible for field input) for datetime, datetime range, and timestamp fields use HTML5 date/time input elements (except when using the select list version).  One for the date portion, and one for the time portion.

The browser, not Drupal, renders out HTML5 date/time input elements.  So, the actual UI will vary from browser to browser, and OS-to-OS.  In addition, not all browsers support these inputs.

When a browser encounters an input element type it doesn't recognize, it defaults back to plain text entry.  In this case, Drupal provides a polyfill for the date portion based on the jQuery UI component.  There is an issue for the time element, but it currently languishing in the queue.

It looks like from your screenshots, Safari is using the polyfill and the rest are using the browser versions of the inputs.

The "yyyy-mm-dd" format for Safari, is a side effect of the fallback.  The HTML5 input elements require dates in that format, so that is how the widget gets configured and rendered out.  The native elements are using a localized version of the inputs, and handling the conversion behind the scenes so that Drupal gets the right format.


Change label of an exposed filter button in Views

This question is regarding D6. However just fyi, in Drupal 7 you can change the label much more easily by going to "Advanced" in your view edit page, then in the exposed form settings you can change the button label as well as other look and feed settings.


Permissions on example payment method- Drupal commerce

You have to go admin/commerce/config/payment-methods
And edit the example payment. In there you can set a condition that is on user. Data type of current user is admin and that will only allow admins to process the test payments.


Reference start date and end date for date field

If that is a node field, then the values you are trying to use are accessible using the following code.

$items = field_get_items('node', $node, 'field_time');

$from = $items[0]['value'];
$to = $items[0]['value2'];


Changing the key/value pair of a field list in Drupal 7 once content has been added to the site

In future use taxonomy for the list. That way you can add/edit to the list without any problems. Lists should be used for things that are constant, like the seasons of the year etc.

Use MySQL Workbench (assuming you are using MySQL). Open the table 'field_config' and do a select on it.

Look for your field in question. It's data is a blob. Right click on the blob and select 'Open Value in editor'. Select text.

You will see something like this:

  a:7:{s:12:"translatable";s:1:"0";s:12:"entity_types";a:0:{}s:8:"settings";a:2:{s:14:"allowed_values";a:2:{i:1;s:3:"one";i:2;s:3:"two";}s:23:"allowed_values_function";s:0:"";}s:7:"storage";a:5:{s:4:"type";s:17:"field_sql_storage";s:8:"settings";a:0:{}s:6:"module";s:17:"field_sql_storage";s:6:"active";s:1:"1";s:7:"details";a:1:{s:3:"sql";a:2:{s:18:"FIELD_LOAD_CURRENT";a:1:{s:21:"field_data_field_list";a:1:{s:5:"value";s:16:"field_list_value";}}s:19:"FIELD_LOAD_REVISION";a:1:{s:25:"field_revision_field_list";a:1:{s:5:"value";s:16:"field_list_value";}}}}}s:12:"foreign
  keys";a:0:{}s:7:"indexes";a:1:{s:5:"value";a:1:{i:0;s:5:"value";}}s:2:"id";s:1:"6";}

You can see under allowed values I have two list entries:

1 => one

2 => two

To add 3 => three I change this bit:

"allowed_values";a:2:{i:1;s:3:"one";i:2;s:3:"two";}

To this:

"allowed_values";a:3:{i:1;s:3:"one";i:2;s:3:"two";i:3;s:5:"three";}

a:2 changed to a:3 as it is the count of values in the list

i:3 indicates the new key

s:5 is the string length of the word three

Then hit apply in the edit box, and hit apply in the SQL window and you are done.

So you don't want to add a new value, but edit an existing one. Use same process as above, but just edit the allowed_values, then run an SQL update on your two tables for the field : 'field_data_XXX', 'field_revision_XX' to update old key to new key.


What is the mechanism behind class comments?

The class comments are Annotations :
What is Annotation mean ?

In general according to techopedia.com

  Annotation is a term used in computer programming to refer to documentation and comments that may be found on code logic. Annotation is typically ignored once the code is executed or compiled.

In Drupal According to Annotations doc page:

  Annotations for class discovery and metadata description.
  The Drupal plugin system has a set of reusable components that developers can use, override, and extend in their modules. Most of the plugins use annotations, which let classes register themselves as plugins and describe their metadata. (Annotations can also be used for other purposes, though at the moment, Drupal only uses them for the plugin system.)

A lot of frameworks use annotations too like symfony use it in many contexts like creating routes using annotations here.

For the annotation example you put in your question is for QueueWorker plugin:

cron = {"time" = 60}

the definition of cron property QueueWorker::$cron according to QueueWorker::$cron it mean:

  time: (optional) How much time Drupal cron should spend on calling this worker in seconds. Defaults to 15.


The solution I used was to copy the scripts/autocomplete.js folder from Googles' GSS module into a custom module, include the autocomplete.js in mymodule.info and imitate the few lines of code in GSS.module which implements the autocomplete functionality.

If you ask me, Google left the CSE unfinished.


Pass an argument to a Rules Action using VBO

Explaining how to create Rule that accept arguments (user can enter any value) and adding VBO field in Views: The Power of Rules with Views Bulk Operations (and Commerce)

From Joren comment:

 function modulename_form_views_form_test_view_page_alter(&$form, $form_state, $form_id) {
    $form['#submit'][] = 'modulename_vbo_submit';
    $form['select']['arg'] = array( '#type' => 'textfield', '#title' => t('Whatever') );
 }
 function modulename_vbo_submit(&$form, $form_state) {
   $nids = $form_state['selection'];
   foreach ($nids as $nid) {
     $node = node_load($nid);
     rules_invoke_component('rules_test', $node, $form_state['values']['arg']);
     drupal_goto('test-view');
   }
 }


How can I add this image plugin, on a new clean/new texteditor?

This can be achieved by activating the image plugin for CKEditor.

Drag the following icon from the available icons to the active toolbar:


Invalidate Internal Page Cache at certain times in a day for anonymous users

You have to add a cache context as well. See both answers in this topic:

How do I create a cache context in Drupal 8 that varies on user/node field data?

You add a variation to the CID of the Internal Page Cache and a custom cache context to the node, so that it can bubble up to all elements which are dynamically cached. The difference is, CIDs can't bubble up, contexts can, and so vary all render elements no matter how deep they are nested.


Theming Views problem to print view fields

1- clear cache
2- take the views-view-field.tpl.php source as a starting point for doing what you need also have a look at documentation at the top of the file


You can try this code

<?php
use Drupal\node\Entity\Node;

$node = Node::load($nid);
//set value for field
$node->body->value = 'body';
$node->body->format = 'full_html';
//field tag
$node->field_tags = [1];
//field image
$field_image = array(
    'target_id' => $fileID,
    'alt' => "My 'alt'",
    'title' => "My 'title'",
);
$node->field_image = $field_image;

//save to update node
$node->save();


Provide User with list field of images to select

I previously used IMCE for FileField module:

it opens a simple file browser and let you select files from configured path of server.


It seems there is not any module that provides this functionality directly. But certainly you can achieve it using other contributed modules.

Profile2
This module allows you to create user profile for the users. You can create profile for the two users like free_registered user and admin_approved users, and can add any number of fields on the user profiles.

Profile2 Registration Path
This module allows you to set the unique registration path for each profile2 user profile.
So after installation you will have two registration forms for each profile2 user profiles. You can access this form from the path specified in Profile2 Registration Path module configuration.

Let me know if any issue occurs. :)


Entity Reference Filter: Filter users by role

As far I understood you want to see only "Managers" in Entity Reference widget on user add/edit page.

Entity reference widget can filter values by using "Views" module.

You can just create an "Entity reference view" and get all users with role "Manager" there.

Here is instruction for widget settings: https://drupal.stackexchange.com/a/38917/6309


It sounds like you aren't very clear on what that permission does vs. how products are displayed. I'm guessing here that you're using Drupal 7. If so, it seems your problem is you're trying to expose the admin paths to products to customers, but those paths aren't intended to be viewed by them. Instead, you're supposed to create either a View that renders product entities directly or a node type with a product reference field on it that functions as what we called a product display. When you attach a product reference field to a node type, it supports embedding product fields into that node while rendering the field itself as an Add to Cart form.

There are a variety of tutorials / guides to understanding and implementing this on the project website: https://drupalcommerce.org

When you need to grant that permission and / or disable SQL rewriting is when you have a View that creates a relationship between your node type (or order line items) to product entities. In that case, though, the View should have additional filters on it to apply appropriate access control so customers only have access to view in that context the products or line items they should.


How do I delete custom entity instances?

Drush 9 supports deleting custom entities
drush entity:delete my_custom_entity


How to SUM/add the values of two fields in a View?

There's a module for that: Views Calc allows you to SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns in Views.


Try

theme_node_add_list

Parameters

$variables: An associative array containing:

content: An array of content types.

function theme_node_add_list($variables) {
  $content = $variables['content'];
  $output = '';

  if ($content) {
    $output = '
';
    foreach ($content as $item) {
      $output .= '
' . l($item['title'], $item['href'], $item['localized_options']) . '
';
      $output .= '
' . filter_xss_admin($item['description']) . '
';
    }
    $output .= '
';
  }
  else {
    $output = '
' . t('You have not created any content types yet. Go to the content type creation page to add a new content type.', array('@create-content' => url('admin/structure/types/add'))) . '
';
  }
  return $output;
}

See here


How do I hide translation vertical tab programmatically?

I think I found it.

In core\modules\content_translatio\src\ContentTranslationHandler.php, there is an entityFormAlter() method, which adds this vertical tab. It seems that this method is executed after your code. I would try changing the weight of your module (so your code will run later).

(I found this looking for the If you made a significant change string in core; doing so, I found where the translation tab was coming from.)


how to set cron correctly on a shared server

Looks like perhaps you settings.php file has some extra characters outside of the


Showing a block in specific content types and URLs

If you want to check all children of specified term below code can help you

first load all children of it ,then check its term ids one by one

$tids=array_keys(taxonomy_get_children(8));
foreach($tids as $tid)
 if (strpos($url, "taxonomy/term/".$tid)) {
    $match = TRUE;
    break;
  }


Change the order of product variations on the "add to cart" form

Similar to Drupal 7, Drupal Commerce for Drupal 8 respects the ordering of attribute fields on the product variation form when rendering them into the Add to Cart form. To find these options, you'll need to navigate to Administration >  Commerce > Configuration > Product variation types and select the Manage form display option from the Operations dropdown for the variation type in question. Reorder the fields there, and they'll appear in the new order on the Add to Cart form.


The meaning of update.php pending updates

It's part of menu_update_7003(). The comments in that function say it all really:

Make sure all custom menus are present in the active menus variable so that their items may appear in the active trail.

Usually just searching Google for the exact message in quotes (e.g. "Add missing custom menus to active menus list") will bring up the page that explains why it's been done (that's what I did to find this out). You can most likely do the same for the other two updates and find out exactly what they're doing.


How to sync configuration between multiple developers' environments

Don't push to the develop branch directly. You should have a branch and merge strategy. If using GitHub or GitLab or similar, you would do a pull request of your branch to develop.

A common strategy (or one of) is the Git Flow workflow. Some links to explain Git Flow:

https://nvie.com/posts/a-successful-git-branching-model/
https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow

There are a handful of strategies, use whatever will fit for your team.

One of the few circumstances I ran into with merge conflicts was if someone was working on something touching the same configuration areas as another person.. we avoided this by just coordinating the work well.


There are several things to check for when troubleshooting migrate/migrate plus.

Based on "not registering" make sure you set id: my_migration instead of id: beer_term or it won't show up when you run drush ms. That's the easy one, hopefully it's that. If not...

Failures resulting from errors in your migration configs will be silent most of the time. When they're not silent, they tend to send you on a wild goose chase for something pretty unrelated to what failed. This can make it frustrating to pinpoint what went wrong. Quadruple check your .yml syntax.

Secondly, make sure your config (.yml) files are named correctly. They should be named and placed exactly like /drupal/modules/custom/my_module/config/install/migrate_plus.migration.my_migration.yml The config files should NOT be named my_module.migration.my_migration.yml. As @mike ryan points out, resist the temptation to do so.

If you've done all of the above after uninstalling and reinstalling your module, your migration should show up when you do a migrate status check.


Automatically close webform after submission

You need to use hook_form_alter() and on submit of the form you need to set action like this

$form["#submit"][] = "ajax_modal_form_submit";

and add function

function ajax_modal_form_submit($form,&$form_state) {
    ctools_include('ajax');
    ctools_include('modal');
    $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
    $form_state['ajax_commands'][] = ctools_ajax_command_reload();
    drupal_set_message(t("You detail submitted successfully!"));
  }


You can turn off caching by going to Configuration > Performance, and uncheck "Cache pages for anonymous users."  That will turn off page caching for the whole site.

If you only want to keep specific pages from being cached you can use Cache Exclude.

You can also (but it is not recommended; see the comments) enter this PHP snippet into the page's template, for example node--123.tpl.php.

// Keep the page from being cached
$GLOBALS['conf']['cache'] = FALSE;


Drupal Commerce: How to manage different payments (a total amount can be pay in different shares and the user can choose in how many shares)

There is Commerce Installments

  Commerce Installments allows you to create installment payments for
  products in a Drupal Commerce store.

Make sure you read Issues for Commerce Installments


Specify destination folders outside of Drupal root using Drush Make

I've noticed how I can get part of the way there without moving the downloaded files around

From my main directory I can run

drush make --no-core --contrib-destination=modules test.make sites

to yield

project_name
  - sites
    - modules
    - themes

then use a standard

drush dl

to get core and then use custom scripts to symlink core/sites/all -> project_name/sites or something like that.

There doesn't seem to be an option for --no-contrib or anything like that (probably because there isn't much point)


I now understand how this works:

If you want a user to be able to edit all content types, regardless, you are supposed to use "Bypass Content Access Types".

"Administer Content" allows people without "Bypass Content Access Types" access to the Author and Promotion panels on the rhside of the node edit screen. i.e. they can change the Author (UID) and the creation date/time, and can either promote the content to the homepage or make it sticky.

"Administer Content" also gives access to the Revisions tab for all content types - but those permissions are duplicated - a user may already have them if type-specific revision permissions have been set, e.g:

Basic page: Delete revisions
Basic page: Revert revisions

(Note: Administer Content used to be called Administer Nodes and the latter name is still used internally.)


Error when running database update: "DatabaseSchemaObjectExistsException: Cannot add field redirect.status: field already exists."

Most probably you are on Redirect 7.x-1.0-rc3 which was released back on 8 July 2015. It has been fixed on https://www.drupal.org/project/redirect/issues/2541304, so just update your Redirect module to 7.x-1.x-dev.


Disabling Wysyig profile profile for particular content type

I was having a similar issue and did it using Better Formats module.

I created a new Input Format (for example "my input format")
Disabled WYSIWYG in that format
In the Content type settings, under "Input format settings", select that new profile as default


Can I add a "edit node" link as field in a node?

You could also check to see if the user has access before printing the edit link.
<?php
  if (node_access('update', $entity)) {
    print l(t('Edit'), 'node/' . $entity->nid . '/edit');
  }
?>


How to get term name using PHP code in views? Drupal 6!

If you want to get the term name of current node in views you can make use of Content: All taxonomy terms field. There is no need for diving into PHP code.


Support composer_manager AND drupal-composer/drupal-project with contrib module

Here are the conclusions I will follow for the CFR module package.

I am writing this as guidelines for module maintainers.

The steps may look different for other module packages with a different structure.

Start a new major version.

If the existing version of the contrib module requires composer_manager to work, supporting an alternative method might come with backwards-compatibility-breaking side effects. If this is the case, a new major version should be introduced.

Use the 'alternatives' module.

The alternatives module allows to replace one dependency with another.

In the *.info file:

dependencies[] = composer_autoloader
alternatives[composer_autoloader][] = composer_manager

This means: If 'alternatives' and 'composer_manager' are enabled, then the module in question can be enabled without enabling 'composer_autoloader'.

Depend on composer_autoloader

Let your modules, or one of them, depend on composer_autoloader, but add the alternatives[composer_autoloader][] = composer_manager as mentioned above.

Doing this in a subdirectory module causes the metapackage to require drupal/composer_autoloader.

Additional composer.json file at the top level

Why?

Composer manager will look at composer.json files per (sub)module. If the root dir of the module package contains a composer.json, but no module exists in the root dir of the module package, this composer.json will be ignored by composer_manager.

On the other hand, the project_composer module responsible for packages.drupal.org will extract metapackage information from the *.info file in a subdirectory module, but ignore composer.json files for modules in subdirectories.

Unlike composer_manager, it does look at the main composer.json in the package root dir, even if there is no module in this place.

How?

Put one composer.json at the top level directory of the module package. This has to require the 3rd party libraries from every submodule contained in the module package.

Keep the submodule composerjson files in place.

Replacement composer_manager for the transition.

Goal: Transition from composer_manager to composer_autoloader + drupal-composer.

Problem

If the modules were previously installed with composer_manager and now we want to use composer_autoloader, we are in a bit of a pickle:

At least one of the two dependencies must be enabled at any given time, to allow the dependee module to remain enabled and the 3rd party libraries to be autoloaded.
Downloading both with drupal-composer is not possible, because composer_autoloader declares a conflict with composer_manager in its composer.json.
Assuming we would find a way to download both composer_autoloader and composer_manager at the same time, having both enabled would be possible but would perhaps cause weird behavior due to duplicate vendor directory and duplicate autoload.
Updating code and database at the same time is not possible. We need to call drush en and drush dis, or do the switch via hook_update_N(), in the new codebase.

Solution

Let the site builder create a dummy / placeholder version of composer_manager in sites/all/modules/custom/composer_manager.

The only thing this would do:
- a hook_boot(), which would check if composer_autoloader exists, and if not, it replicate the behavior from composer_autoloader.
- a hook_uninstall() to replicate uninstalling the regular composer_manager.

Then use a hook_update_N() to enable composer_autoloader and disable + uninstall the placeholder composer_manager module.

Perhaps such a placeholder module could be provided on packagist, with an obfuscated name to prevent the conflict with composer_autoloader.


VBO Pass Argument to Custom Action Function

Awhile back I did come up with a work around for this. Basically you can create a custom submission handler for the VBO form, then have that custom handler perform the code you need.

/**
* Implements hook_views_bulk_operations_form_alter().
*
* This is the function that alters our VBO form
*
* @param $form
* @param $form_state
* @param $vbo
*/
function mymodule_views_bulk_operations_form_alter(&$form, &$form_state, $vbo){

  // Here I added a date popup to the form
  $form['vbo_set_close_date'] = array (
        '#type' => 'date_popup',
        '#title' => t ('Set Close Date'),
        '#date_format' => 'm/d/Y',
        '#date_label_position' => 'within',
        '#weight' => -10000,
  );

  // Here is where I added the custom submission handler. This calls the "mymodule_set_close_dates" method
  $form['select']['submit']['#submit'][] = "mymodule_set_close_dates";

}

/**
 * Callback function for VBO form
 *
 * @param $form
 * @param $form_state
 */
function mymodule_set_close_dates($form, &$form_state){

  $date = $form_state['values']['vbo_set_close_date'];
  $action = $form_state['operation']->operationId;
  if(!is_null($date) && $action == 'action::mymodule_close_job'){ // <------- custom action
      $value = strtotime($date);
      $relations = $form_state['build_info']['args'][0]->result;
      foreach ($relations as $relation){
        $rid = $relation->rid;
        $wrapper = entity_metadata_wrapper('relation', $rid);
        $wrapper->field_ended->set($value);
        $wrapper->save();
    }
}


You don't define the 'page callback' for the MENU_DEFAULT_LOCAL_TASK since it is taken care of by the 'root' page, plus without any additional tabs it won't show up anyway.  If you add another MENU_LOCAL_TASK it should show up.  You can think of the default local task as the page itself, there would be no reason for a VIEW tab there without anything else like EDIT UNPUBLISH etc.


use-ajax class for ajax link not working in dynamic content load

Did you use Drupal.behaviors?
Javascript event listeners that are attached to DOM objects at the jQuery(document).ready event won't be attached to ajax-loaded stuff. Drupal.behaviors sort that out for you.


How to make a custom block visible if and only if there are no other blocks active in given region

There is a function that returns the list of the blocks available in a region, but it cannot be invoked from the PHP code used to establish the visibility of a block as it would probably cause a recursive call.

Looking at the code of block_list(), you can write the visibility code for your block. What you need to change is the query that obtains the list of all the blocks to exclude the block for which you are writing the visibility code.

The actual query executed by the function is the following:

$result = db_query(db_rewrite_sql("SELECT DISTINCT b.* FROM {blocks} b LEFT JOIN {blocks_roles} r ON b.module = r.module AND b.delta = r.delta WHERE b.theme = '%s' AND b.status = 1 AND (r.rid IN (" . db_placeholders($rids) . ") OR r.rid IS NULL) ORDER BY b.region, b.weight, b.module", 'b', 'bid'), array_merge(array($theme_key), $rids));

The function code requires you know the region in which the block is visible; if you move the block in a different region, then you need to change the code used to test the block visibility accordingly.

In Drupal 7, a module can implement hook_block_list_alter() to alter the list of visible blocks.

  Act on blocks prior to rendering.

  This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.

  You can also set $block->content here, which will override the content of the block and prevent hook_block_view() from running.


Preprocess function for node.tpl.php file

To create a variable for any type of node you should use yourtheme_preprocess_node() function, and in this fuction you should specify a type of node.

Example:

/**
 * Override or insert variables into the node templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */

function YOURTHEME_preprocess_node(&$variables, $hook) {

  //$variables['sample_variable'] = t('Lorem ipsum.');
  // Optionally, run node-type-specific preprocess functions, like
  // YOURTHEME_preprocess_node_page() or YOURTHEME_preprocess_node_story().
  //$function = __FUNCTION__ . '_' . $variables['node']->type;
  //if (function_exists($function)) {
  //  $function($variables, $hook);
  //}

  // define $node object, so it's be easier to use it
  $node = $variables['node'];

  // add variables to node--nameofnodetype.tpl.php file
  if ($node->type == 'nameofnodetype'){

      // $variables: an array with variables
      // you need to add one, so just define it
      $variables['my_variable'] = 'whatever';

      // also you can rewrite those variables which already exists
      // for example variable: $title
      $variables['title'] = t('The new title');
  }
}

In your node--nameofnodetype.tpl.php file:

// check if your new variable exist
print $my_variable;

 * Don't forget replace 'YOURTHEME' to your theme name


What is the rule on licensing and third party code?

My gut tells me it is likely not good practice to bundle it up into your module.

You shouldn't. That page starts out with:

This is the policy for 3rd party code libraries in Drupal's contribution repositories.

In general 3rd party libraries and content are forbidden, so do not commit any. Instead, document for your users how to find and install the library/content themselves.

The other way is exceptions and they're clearly defined and you need to request approval.


get rid of decimal scale of stock field in commerce

That bug has been fixed a long time ago; update from 7.x-2.0-alpha4 to 7.x-2.0-rc1. https://drupal.org/project/commerce_stock and that will fix it, along with a lot of other issues.


Issue in converting a HTML Link to Drupal Link using l() function

$current_path = check_url(drupal_get_path_alias($_GET['q']));
$onclick = 'loadQtiPlayer(' . $targetPath . ',' . $targetWindowHeight . ',' . $targetWindowWidth . ')';
print l('Start QTI Quiz', $current_path, array('fragment' => ' ', 'attributes' => array('onclick' => $onclick)));


Here is how you could do it.

function mymodule_testes($form, $form_state) {
// your form definition goes here
  $form = array();
  $form['upload'] = array( // note the key
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#weight' => -10,
  );

  $form['upload2'] = array(
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#weight' => -10,
  );

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

  return $form;
}

function mymodule_testes_validate($form, $form_state) {
  dpm($form_state);
  // pass proper args to file_save_upload .. see documentation
  $file1 = file_save_upload('upload' , array()); // remember the key
  $file2 = file_save_upload('upload2' , array());
  // you dont have to do it verbosly
  // Do all your  validations  if(!$file1 || !$file2) form_set_error ...

  // save it onto form_State
  $form_state['files_storage'][0] = $file1
  $form_state['files_storage'][1] = $file1
  dpm($file1);
  dpm($file2);

}

function mymodule_testes_submit($form, $form_state) {
 // using devel so you could see how it is stored
 dpm($form_state);

  foreach ($form_state['files_storage'] as $key => $file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
  }
}

Hope this helps


In the display settings of your field, you can choose to display the "Rendered Content" (what you actually have) or only the URL of the file ("URL to file"). This should only give you the file URL.


How to add query parameters to a CacheableJsonResponse's cache?

Add a cache context for the query parameter to the response:

$cache_metadata = (new CacheableMetadata())->addCacheContexts(['url.query_args:lang']);
$response->addCacheableDependency($cache_metadata);

About the second question, when this issue is resolved you can use core REST to deliver translated entities: https://www.drupal.org/node/2135829


How to send email to multiple recipients using drupal_mail?

The to-parameter to drupal_mail is a string, not an array.  But you can have as many receipent as you like in the the e-mails "to" string, provided they're separated by commas.

So to send the same mail to multiple recipients, do the following:

$to  = 'one@email.com,two@email.com,three@email.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

Se also API documentation for drupal_mail


How to add comments per picture in a photo album?

Would build this by creating a single content type with only one picture per node with the comments turned on just as you did.  Then build a view for your gallery with the comment as a link included.


How do I remove outer/container divs from a view?

You should override the views-view.tpl.php, not the views-view-unformatted.tpl.php.

The two divs you mention are originating from sites/all/modules/views/theme/views-view.tpl.php, check out lines 30 and 55.

If you copy this over to your theme's templates folder, and rename to be specific to your page/block display, you can remove that part of the template's code and you should get what you need.

  cp sites/all/modules/views/theme/views-view.tpl.php
  sites/all/themes/your_theme/templates/views/views-view--your-ul-page.tpl.php

N.B.: This is exactly what the other post's accepted answer is doing in the first part, before going into Semantic Views configuration, you can ignore that part. Here is a modified/simpler version of the code snippet from that answer, for quick reference:

<div class="<?php print $classes; ?>">     // 30: delete this line
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
[...]
<?php if ($rows): ?>

  // 55: delete this line,
      <?php print $rows; ?>

                      // 57: delete this line
  <?php elseif ($empty): ?>
[...]

<?php /* class view */ ?> // 90: delete the div from this line

Good luck!


Creating a very specific custom Views argument handler

Well this is what I ended up with, it's not entirely pretty - and I've never really grasped how the Views structure works, but it works.

/**
 * Implementation of hook_views_data().
 */
function msc_cc_vc_views_data() {
  return array('msc_cc_vc' => array(
    'table' => array(
      'group' => t('MSC Version Control'),
      'base' => array(
        'title' => t('MSC Version Control'),
      ),
      'join' => array(
        'node' => array(
          // links directly to node via vid
          'table' => 'node',
          'left_table' => 'node',
          'left_field' => 'vid',
          'field' => 'vid',
        ),
      ),
    ),
    'users_version_tid' => array(
      'title' => t('User\'s Version Term ID'),
      'help' => t('The taxonomy term ID (from the Version vocabulary) of the supplied user UID.'),
      'argument' => array(
        'field' => 'uid',
        'handler' => 'msc_cc_vc_views_handler_argument_users_version',
        'numeric' => TRUE,
      ),
    ),
  ));
}

/**
 * Implementation of hook_views_handlers().
 */
function msc_cc_vc_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'msc_cc_vc') . '/views',
    ),
    'handlers' => array(
      // argument handlers
      'msc_cc_vc_views_handler_argument_users_version' => array(
        'parent' => 'views_handler_argument_many_to_one',
      ),
      // field handlers
      // filter handlers
      // relationship handlers
      // sort handlers
    ),
  );
}

And then the handler itself. Here I have hard-coded the Taxonomy VID because for this application it doesn't matter. You could steal the code for selecting vocabularies from other handlers, you might also want to allow multiple TIDs.

class msc_cc_vc_views_handler_argument_users_version extends views_handler_argument_many_to_one {

  /**
   * Called to implement a relationship in a query.
   */
  function query() {
    $this->ensure_my_table();

    // This is the supplied UID
    $uid = $this->value[0];

    // Not great Drupal but let's do some easy processing:
    $profile = content_profile_load('profile', $uid);
    $terms = taxonomy_node_get_terms_by_vocabulary($profile, 8);
    $version  = reset($terms);
    if (empty($version)) {
      drupal_set_message(t('The selected user does not have curriculum version.'), 'warning');
      return;
    }

    $def = $this->definition;

    // Rebuild the definition to create a unique relationship
    // that forces all results to have the selected version TID.

    $def['table'] = 'term_data';
    $def['type'] = 'INNER';
    $def['left_table'] = $this->table_alias;
    $def['left_field'] = 'vid';
    $def['field'] = 'revision';

    $def['table formula'] = "(SELECT td.*, tn.vid AS revision FROM {term_data} td INNER JOIN {term_node} tn ON tn.tid = td.tid WHERE td.tid={$version->tid})";

    $join = new views_join();

    $join->definition = $def;
    $join->construct();
    $join->adjusted = TRUE;

    // use a short alias for this:
    $alias = $def['table'] . '_' . $this->table;

    $this->alias = $this->query->add_relationship($alias, $join, 'term_data', $this->relationship);
  }
}

Enjoy.


How to get custom role ID from Drupal UI?

Not what I was looking for, but if you inspect the Roles Drop Drop on the People Page then the array has the ID in it.


How to add Title attribute to Menu links?

Just enter text in the description field and it will be rendered as the link title.


Is there any way to clone a content type

No need to clone content type. I had the same issue but I handled it this way, create all of the common fields and then create one more extra field of type list and you can call it Field Type, this field is a list of content types. When you are entering content, you only need to select an item from list to distinct among content types.


How to prevent drupalSettings to sort settings object

It's not Drupal that sorts the drupalSettings array, but it's console.log() that sorts the properties of drupalSettings.options before outputting it. See Show original order of object properties in console.log where the answer explains this.

If you really want to avoid console.log() sorts the object properties, you could call console.log() using code similar to the following one.

console.log(JSON.stringify(obj, drupalSettings.options, null, 2));

I would rather use this code if it's really important to see the object properties in the order they are set.


node_save is not same as saving a node manually

Try one of this options:

Explicit field deletion:

$node = node_load($nid, NULL, FALSE); // Force to load
if (!empty($node->nid)) {
  $node->field_taxonomy_term = NULL; // Reset the field
  node_save($node);
}

Submit the node form programmatically:

$node = node_load($nid, NULL, FALSE); // Force to load
if (!empty($node->nid)) {
  $form_state['node'] = $node;
  $form_state['values']['op'] = t('Save');
  drupal_form_submit($node->type . '_node_form', $form_state, $node);
}

Edit all nodes on bulk with views bulk operations:

Install https://drupal.org/project/views_bulk_operations
Add a new view page of content (node) and set fields as display.
Add field "Bulk operations: Content"
Configure the fields: SELECTED BULK OPERATIONS: "Save content" (check)
Save the view and go to the views path.
Select all items and the "Save" operation and execute it!
Done!


Why does deleting a node ALSO invoke hook_node_update?

Thanks for your answers, much appreciated!

I finally managed to find the cause. The "problem" is caused by the module https://www.drupal.org/project/field_collection. My node has a field that is a field_collection, and apparently, when deleting a node, the field_collection items are first deleted from the node, which is then saved (which causes the update hook to fire), and only then the node itself is actually deleted.

It's pretty easy to workaround this issue once you actually KNOW what is causing it, in my case I modified the update hook to check for field_collection items in the node, if there were none it means the node is about to be deleted...


Hitting a download link and displaying text in the same menu item page callback (7)

A particularly low-tech solution using meta refresh (which should work cross-browser):

function download_icon_page_callback() {
  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'http-equiv' => 'refresh',
      'content' => '5', // Timeout in seconds
      'url' => '/path/to/my/file.zip'
    ),
  );

  drupal_add_html_head($element, 'download_icon_refresh');

  return array(
    'instructions' => array(
      '#markup' => t('Some instructions')
    ),
    'backup_link' => array(
      '#markup' => l('Click here if the file download does not automatically start.', 'path/to/my/file.zip'),
      '#prefix' => '<p>',
      '#suffix' => '</p>'
    )
  );
}

Although returning a string from a page callback function works fine (the return is run through render() which accepts a string or render array), returning a render array is preferred as it gives other parts of the system the chance to alter the output while it's still in a structured manner. The documentation for render arrays is a great place to start if you haven't used them before.


Panels Pane Content Added - Stacked, need Inline

You could use custom panel layouts (use the builder option) and create the regions you want with the size and position you want.


I guess one obvious improvement would be to use a different cache backend.

If you have a single server and enough memory, you could use an APC backend (D6: http://drupal.org/project/cacherouter, D7: http://drupal.org/project/apc) to have various of the often used caches directly in shared memory. That is probably the fastest cache solution you can get.

Another alternative is Memcached, which is especially interesting if you have multiples servers that should share a cache.

Note that you can't move the cache_form because that contains information about currently displayed forms and is not really a cache since it contains unique information, not just aggregated things like the others, which can always be cleared. Also, some other caches, especially cache_update, you might want to keep in the database, because that shouldn't be cleared like the rest as it contains information about update information of your used modules, something that doesn't change that often and can be very slow to re-fetch if you have many of them.

You can also move the sessions information out of the database, for example can you place it in MongoDB, and there are probably others too.


How do I change the node title when saving it?

To do this without writing code, the module you want for Drupal 9 is Automatic Entity Label.  Nodes are entities, so you can use this to set the label (title).


How to prevent term URL in webform email template (Webform References Module)?

When returning field value Webform References Module, add link to field output using theme function (theme_webform_display_term_reference_field()), which you can override in your theme's template.php and then clear Site Cache. Check sample code below, which you can write in your theme's template.php:

/**
 * Format the output of data for this component.
 */
function [THEME_NAME]_webform_display_term_reference_field($variables) {
  $values = (array) $variables['element']['#value'];
  $items = array();
  foreach (array_filter($values) as $value) {
    $tid = check_plain($value);
    if ($tid) {
      // Do not pass 2nd argument, keep it default i.e. FALSE.
      $items[] = _webform_references_get_term_name($tid);
    }
  }
  $output = count($items) > 1 ? theme('item_list', array('items' => $items)) : (isset($items[0]) ? $items[0] : '');
  return $output;
}

NOTE : This will also remove the Term field link on view submission page.


Auto resize iframe from different domain?

I'd hate to say it, specially as the author of easyXDM, but http://consumer.easyxdm.net/current/example/resize_iframe.html is kinda the way to do it if you need cross-browser (and especially IE6) support. If you're fine with only supporting more modern browsers, then using postMessage directly is not that hard.


Change Created Date to date from field_post_date

I had 'create' not 'created' - Doh!
Now it works...


Custom theme block position is not importing

The solution was to disable and un-install my custom theme and then re-enable.

Here are the steps (Where vcs is our directory for default config defined in settings.php and my_custom_theme is our theme name).

After running drush si, lets import our config.

drush cim vcs --partial -y

At this point although our config has been imported our custom blocks are not appearing in the regions as set in the config .yml files.

Enable a core theme so we are free to uninstall our custom theme.

drush cset system.theme default seven

Rebuild the cache now.

drush cr

Uninstall our custom theme.

drush pm-uninstall my_custom_theme -y

Enable our custom theme.

drush en my_custom_theme -y

Set our Custom theme as default theme.

drush cset system.theme default rrre_theme -y

Import our default config.

drush cim vcs

Run Server.

drush rs

:)


How to programmatically render a webform to display specific Elements

To hide custom field in webfrom you need to use the hook_form_FORM_ID_alter.

function CUSTOM_MODULE_form_webform_submission_request_form_add_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $elements = &Drupal\webform\Utility\WebformFormHelper::flattenElements($form['elements']);

  $elements['flexbox_layout']['confirmation_id']['#access'] = FALSE;
}

To get specific form elements you can use getSubmissionForm() method:

public function buildForm(array $form, FormStateInterface $form_state, $sid = NULL) {
  $my_webform_machinename = 'request_form';
  $my_form = \Drupal\webform\Entity\Webform::load($my_webform_machinename);

  $webform = $my_form->getSubmissionForm();

  $form['my_field'] = $webform['elements']['flexbox_layout']['confirmation_id'];

  return parent::buildForm($form, $form_state);
}


Drupal 6 to Drupal 7 content type migration using feature module?

This is already included in the core. You don't need to install Features in order to migrate all that.

Here's what you need to do in a nutshell: disable all contrib modules, make backups of everything, plug D7 into the D6 database and update the site. Drupal will take care of all basics, such as content types and fields.

Refer to the documentation for more information.


Problem with submitting ajax form with autocomplete

I think you need to do this:

$form['actions']['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'userpasswords2_callback',
      'wrapper' => 'box',
      'event' => 'click'
    ),
    '#value' => t('Submit'),
  );

just add 'event' => 'click' you your submit ajax element in the form. This must be done for all forms you want to be submitted through #ajax.


How can I edit the string "Send this user a private message" in Privatemsg

Have you tried String Overrides module? Here is a quote about it (from the module's project page):

... a quick and easy way to replace any text on the site.
Features:

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


How to display the weekly view in manage availability in rooms_availability?

I'm not aware of a way to display a weekly view. But as per your "... is there another change in the code ...", it seems like it should be pretty forward to transform the 3 months view to a single month view via rooms_three_month_calendar.tpl.php.

To actually do so, remove line 2 (with class="month1") and line 4 (with class="month3") from this part of that tpl file:

After doing so, it should look like so:

Still not exactly a weekly view, but at least you already got rid of 2/3 of the days you don't want to see, right? And hence leaves 3 times as much space for the current month view.

Note: By not removing the backward / current / forward links in that tpl file, you should still be able to easily navigate to another month.


What are the "Files" that Metatag module allows adding Metadata to?

They are all the files managed by Drupal through attachments, images & file fields. In D7, these managed files are entities. As such, the metatag module supports it.

This isn't useful with the metatag module alone, but if you had a configuration where files had their own display page (e.g. the file entity & media module), it could be utilized.


Drupal 7 localhost is shortening css strings

same issue, to me helps:

visit: admin/config/development/performance

turn on "CACHING" for:
 Cache pages for anonymous users

turn off all "BANDWIDTH OPTIMIZATION"
 Compress cached pages.
 Aggregate and compress CSS files.
 Aggregate JavaScript files.

Then Clear all cahces

That fix my issue with css ;)


How do you create a variable from hook_preprocess_page() that will be available to a node template?

You cannot.
The parameter passed to hook_preprocess_page() (what you define as &$vars) is not the same parameter passed to hook_preprocess_node(), which means that if you set $vars['social'] in the first, it is not passed to the latter. If you need to pass a value to the node template file, you need to set it in hook_preprocess_node(), or hook_process_node().


2015: What am I missing to get a simple hit counter block by page?

I couldn't figure out how to do it with contextual filters, so I guess I still don't understand things on that front. However, a custom block with just a couple lines of PHP did the trick. All directions from:

How to get visitors count of a page created using views

As per that post, custom code was:

<?php
$path = $_GET['q'];
drupal_set_message($path);
$visits = db_query("SELECT count(*) FROM {accesslog} where path = :path", array(':path' => $path))->fetchField();
echo "Views: " . $visits;
?>


Where to programmatically enable a Feature module

A feature module is just another module. And you can enable it programmatically using the linked code from another enabled module's hook_update_N placed in this another enabled module's *.install file. This even can be another feature module. Then have this hook fired via drush updb on the command line or by visiting your site's /update.php.

You also could do that from a form submit handler. Or even from a menu callback providing some custom endpoint you can access with cURL for example.

It's safe to use other feature modules' *.install files. Since Features never touches *.module and *.install files during regeneration. So you are free to use them to your needs.


as arpitr says, you need to include the field so that it becomes visible to Views. You can exclude it from view in the field settings if you don't want it to show - then try, borrowed from (adjust appropriately for your setup) here:

  It's not super-obvious how to do this, but it is pretty easy.

  The downloaded filename has nothing to do with the "path" in the "data
  export settings" - that is simply the path that is used to trigger the
  generation of the file.

  To set the actual filename, click "settings" next to "CSV file" in the
  View's "format" section. Then, check the "provide as file" box and
  then set the filename (including token) there.


How to add html tags to account setting emails?

Have a look at Mail Headers project.
As says doc, it allows you to control and modify any (almost any) mail header.


How can I convert first page of a pdf as its thumbnail?

Some people have started a Drupal 7 version, but it's nowhere near ready yet. If you can program for Drupal 7 and want to get involved, you could check out their Git repository and help them out.

If you're not ready to start porting D6 modules to D7, you could try one of these options to build those thumbnails, then write a little snippet of code to attach them to your nodes in your imagefields:

Stack Overflow: How do I convert a PDF document to a preview image in PHP?
Webvamp: How-to create PDF preview images in PHP


how to correctly use curl command line with Services module?

You need to send only username and password. Mail is not required.. Please check the documentation here...

$base_url = 'http://localhost/test_endpoint';
$data = array(
  'username' => 'admin',
  'password' => 'password',
);
$data = http_build_query($data, '', '&');
$headers = array();
$options = array(
  'headers' => array(
    'Accept' => 'application/json',
  ),
  'method' => 'POST',
  'data' => $data
);
$response = drupal_http_request($base_url . '/user/login', $options);
$data = json_decode($response->data);
// Check if login was successful
if ($response->code == 200) {
  // Now recycle the login cookie we recieved in the first request
  $options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
  // Get info about a user
  $data = array();
  $options['data'] = http_build_query($data, '', '&');
  $options['method'] = 'GET';
  $response = drupal_http_request($base_url . '/user/32', $options);
}

Below one worked for me

curl -H 'Content-type: application/json'  -d '{"username":"admin", "password": "admin"}' http://localhost/d7/testendpoint/user/login

In your case it should be

curl -H 'Content-type: application/json'  -d '{"username":"u10", "password": "123"}' http://localhost/test/api/user/login


Alternative to Google Adsense content injector module

It might not be quite as versatile, but the Block Inject module will allow you to embed adsense blocks within the node body.


Use this module http://drupal.org/project/uc_node_checkout

You can assign a node/content type to a product in uber cart, so once a visitor has selected a product in the cart they can create an og group node.

for my needs I then just used rules to make the group unpublished until the visitor had a fully paid for the role in the ubercrt


However if there is a simple(er) solution I prefer that.

Sorry, maybe I going too deep, but the most simpler solution that you can use just for display is a CSS solution.

Based in your example:

input[name='elementName'] {
  text-transform: uppercase;
}

That's it, any char will be uppercase in your textfield. If need store in uppercase, just change case before save.


Content Moderation: Remove transition from select list programmatically

Thanks @No Sssweat. You put me on the right track.

Since this is the node form, I opted to use hook_form_BASE_FORM_ID_alter().

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 */
function MY_MODULE_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $roles = \Drupal::currentUser()->getRoles();
  if (array_intersect(['role_1', 'role_2', 'role_3'], $roles)) {
    $options = isset($form['moderation_state']['widget']) ? $form['moderation_state']['widget'][0]['state']['#options'] : [];
    $options = array_diff_key($options, [
      'request_publish' => 'Request Publish',
      'request_unpublish' => 'Request unpublish',
      'request_delete' => 'Request Delete'
    ]);
    $form['moderation_state']['widget'][0]['state']['#options'] = $options;
  }
}


Install module that has an external php script and a couple of other files

You should use the Libraries module - it allows integration with external libraries and scripts.
This is the correct way of adding libraries and using third party scripts in Drupal. This way several modules can use the same library and same sources, which is better from maintenance and organization perspective.

You can define a dependency in your custom module using the hook_libraries_info() and then include the library when you need it with libraries_load()`.

As an example, take a look at Colorbox to see how the hook is implemented there.

Check out also the Print module.

In your particular case, you will probably use TCPDF for generating PDFs, so you should define a library dependency like so:

/**
 * Implements hook_libraries_info().
 */
function YOUR_MODULE_libraries_info() {
  $libraries['tcpdf'] = array(
    'name' => 'TCPDF',
    'vendor' => 'http://www.tcpdf.org/',
    'download url' => 'http://sourceforge.net/projects/tcpdf/files/',
    'version callback' => 'YOUR_MODULE_tcpdf_version',
    'files' => array(
      'php' => array(
        'tcpdf.php',
      ),
    ),
  );

  return $libraries;
}

And when you need it, just call libraries_load():

libraries_load('tcpdf');

Last thing - don't forget to add dependency for libraries in your module .info file.


This should work... Context allows contexts to be fired based on the presence of other contexts. So in your "global" context, you can add the condition 'Context(all)' and then add ~[taxonomy_context_id]. Where taxonomy_context_id is the id of the taxonomy context. Make sure that "Require all conditions" is checked. And save.

Now the "global" context should only show when the the other isn't available.

Recommendation: If you are looking to switch logos based on taxonomy term, you can use template_preprocess_page() to switch out the path of the logo based on the current menu_object that is loading. This allows for you to have a global context that persists and doesn't duplicate the work/blocks and provides an override to the page.tpl.php variables instead of multiple possibly conflicting context.


Where and how does drupal store the node body in drupal 7?

If you emptied out the field_data_body (and revision) table and you are still getting data that can only mean three things:

you emptied the wrong table (wrong database or the right database with the wrong prefix)
it's still cached (there's a clear cache button on the admin/config/development/performance page).
You are not using SQL to store your fields. Do you have mongodb_field_storage enabled? Something even more exotic?

As for how it gets stored, node_save calls field_attach_insert (and node_load calls field_attach_load) which, in turn, calls the field storage module which I presume is field_sql_storage and so field_sql_storage_field_storage_write writes your database records and field_sql_storage_field_storage_load loads them.

Also note that array_shift(array_keys()) is wrong (E_STRICT error: Only variables should be passed by reference because array_shift takes a reference and array_keys is not returning by reference. Finally, you should feed your EntityFieldQuery code to the coder module to fix the coding standards: at least the code inside the if is indented wrong and the string concat operator (the dot) needs spaces on both sides. It hurts my eyes :)


There's not enough here to tell what's wrong, but there are a couple of things you can do to isolate the problem. Start with drush @uat sql-conf and drush @dev sql-conf; this is what Drush will use to look up the database records for the two sites.  If one of these fails to print the right information, that could cause sql-sync to fail.  Next, try drush sa --with-db @uat and again for @dev, and see if the database record matches what you saw with sql-conf.  If, for example, you copied a database record into your @dev alias and specified the wrong database (one different than the one specified in settings.php), then sql-sync might be successfully copying your production database to some other db on the dev machine.

If neither of these things work, you can try adding first -v (verbose output) and then -d (debug mode -- really a lot of output) and see if there is anything there that might help you find the problem.

Update: Did you make a typo in your update?  drush sql-sync @dev @uat pushes dev to uat, which seems like the opposite operation.  If drush sql-sync @uat @dev works on dev and not on uat, I would recommend carefully comparing your alias files on the two machines and see if there are any differences.  Especially check your 'databases' record in your alias definition, if you have any, and run the diagnostic tests I recommend above.  As a workaround, from uat you could run drush @dev sql-sync @uat @dev, which would remotely run drush sql-sync @uat @dev on the dev machine.


translate(localize) specific title of web form use preprocess func

The code doesn't work because the function receives only a parameter, and that is not $node. The correct code should eventually be the following one.

function mymodule_preprocess_page(&$variables) {
  if(!empty($variables['node']) && $variables['node']->nid == 6) {
    $variables['title'] = t($variables['title']);
  }
}

I am assuming you want to change the title when the node ID is equal to 6.


Language switcher to non-source language not working

This looks really similar to what is described in Language switcher (content) does not work, which is an issue on D.O that is not yet resolved (status = active).


The main module to accomplish this is the Form Builder module, which integrates with Webform.  Acquia also uses a similar-but-different module for Drupal Gardens.


Drupal Webform is sending emails but there are no values

In the Webform configuration under advanced settings to configure the general Webform settings go to admin/config/content/webform

Advanced settings : Check off Allow tokens to be used in Webforms


Display a Block for mobile only without creating new theme

Take a look at the Browscap Block module. Here is a quote about it (from the module's project page):

... adds visibility options to block configuration settings to allow you hide or show blocks in mobile devices.
If you are looking for the same thing for Panel panes check out Browscap CTools.


How do I execute code when a module is installed or uninstalled?

Needs to go inside of mymodule.install file

<?php

/*
 * Implements hook_install()
 */
function mymodule_install() {

  // code that creates terms

}

/*
 * Implements hook_uninstall()
 */
function mymodule_uninstall() {

  // code that deletes terms

}


Both Drupal and CKEditor are licensed under GPL2+.
See https://github.com/ckeditor/ckeditor5/issues/991 and https://www.drupal.org/about/licensing.
CKEditor is not the only open source project offering commercial licensing. See the FAQ.


Override menu item weight (bring it to same level as 'user' link) that has user/% path and has to be in user-menu

pff got it

had to

hook_menu_link_alter

and changes this link's plid like:

/**
* Implements hook_menu_link_alter().
*/
function YOURMODULE_menu_link_alter(&$item) {
  if ($item['link_path'] == 'user/some-path') {
    $item['plid'] = '0'; // instead of '2' (My Account menu item)
 }
}

drupal is a pain sometimes... but we love it anyway


There are probably many ways doing this. I'm still new as well, so go easy on me.

I would suggest you to create a taxonomy quiz. Each list item of quiz would be your question. Then for the content type answer, have a field named question and select term reference, choose select list as the widget type. That way, when a user create a new content answer and refer to one of the question from taxonomy quiz, you can just click on the question and it will give you a list of answer.

Other ways would be using Node Reference, but I couldn't get my mind around how to refer back to the question itself, maybe Relation would do the trick.

But try my first suggestion first.


How to render inside a paragraph template a specific view mode for that paragragh

You could try using Twig Tweak module

{{ drupal_entity('paragraph', NUMERIC_ID, VIEWMODE_MACHINE_NAME) }}

Also see the cheat sheet  for Twig tweak, it really is a great module for frontend work!


How to change search index for a view in the Views

I also had this problem after realizing switching indexes also requires changing the view's index. So to accomplish that quickest way I could think of was to change these values from the ‘export’ of the original index being used.

Main lines of original view:

    $view = new view();
    $view->name = 'es_connector';
    $view->description = 'Search box based on elasticsearch (connector)';
    $view->tag = 'default';
    $view->base_table = 'search_api_index_es_connector_index';
    $view->human_name = 'ES Connector';

New search view:

    $view = new view();
    $view->name = 'es_connector_rebuild’; // changed arbitrarily to my new view name
    $view->description = 'Search box based on elasticsearch (connector)';
    $view->tag = 'default';
    $view->base_table = 'search_api_index_es_connector_rebuild’; // changed to work - see below as to how determined
    $view->human_name = 'ES Connector Rebuild’; // changed arbitrarily

To find the name of base table click name of your new index (admin/config/search/search_api/index/) and append search_api_index_ with the machine name. Find and replace any occurance of your new view name.

Then paste all of the export into an import script. This will leave you with a new view based on the new index (with the original search view still available). Then just swap out the new search block for the old one. You also probably need to change the path under page settings of the  view.


How to create a node from an other node template?

Use Form Block

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks

Select your content type for the form. Place block in region and for visibility select the other content type.

If you rather render the block using a template file, ex: node--movie.html.twig you can use Twig Tweak and print it out using {{ drupal_block('block_id') }}


Context Module - not triggering menu active

The patch is here: https://www.drupal.org/files/issues/context-fix-menu-reaction-2374445-16.patch

It will fix the issue for the main menu set as a block.


Question about adding a field value to a view programmatically

So the issues was that Krumo pulled that information of its own accord, and the $order object did not have those details. I had to call $product->nid first, query the DB for the field values i needed, and insert them. I ended up with this code, in case it can help anyone!

    foreach ($order->products as $product_id => $product) {
    $pid = $product->nid;
    $ps = db_query('SELECT field_size_value FROM field_data_field_size WHERE entity_id = :pid', array(':pid'=>$pid))->fetchField();
    $pp = db_query('SELECT field_pack_value FROM field_data_field_pack WHERE entity_id = :pid', array(':pid'=>$pid))->fetchField();
    $form['assigned'][$key][$product_id]['attribute'] = array(
      '#type' => 'item',
      '#title' => t($product->title),
      '#markup' => isset($product->data['attributes']['What would you like']) ? $product->data['attributes']['What would you like'][0] : '',
    );
    if(!empty($ps)){
        $form['assigned'][$key][$product_id]['size'] = array(
      '#type' => 'item',
      '#title' => t('Size:'),
      '#markup' => $ps,
    );
    }
    if(!empty($pp)){
      $form['assigned'][$key][$product_id]['pack'] = array(
        '#type' => 'item',
        '#title' => t('Pack:'),
        '#markup' => $pp,
      );
    }
  }


It was my problem: I took the original dimensions wrong, then Drupal resized the original image to fit the max dimensions.


How to add checkbox to existing administration page

To alter a form implemented by another module, you just implement hook_form_alter(). You probably need to change the #weight property of the form element you are adding, to avoid it is rendered in the wrong place.

function mymodule_form_system_performance_settings_alter(&$form, &$form_state) {
 // Add the checkbox to $form.
}


How to create a custom Twig Template for Menu Block

Ok, I think I found the answer.  Kristian Kaa answers it on his blog here:
http://kristiankaa.dk/article/drupal8-region-specific-menu-theme-hook-suggestion

Basically you use 2 preprocess functions like so:

/**
 * Implements hook_preprocess_block().
 */
function mymodule_preprocess_block(&$variables) {
  $variables['content']['#attributes']['block'] =    $variables['attributes']['id'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mymodule_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  // Remove the block and replace dashes with underscores in the block ID to
  // use for the hook name.
  if (isset($variables['attributes']['block'])) {
    $hook = str_replace(array('block-', '-'), array('', '_'),    $variables['attributes']['block']);
    $suggestions[] = $variables['theme_hook_original'] . '__' . $hook;
  }
}

This will add the block ID as a new theme hook suggestion.  Many thanks to Kristian.


You likely don't need to change anything at all. Just move the folder and clear caches. Maybe you need to change the path in settings.php but only if you hardcoded it there before.

The instructions you found are for Drupal 6 and changing the path is no longer necessary unless you manually changed it to something else than the default location before.


Commons: can each non-admin user create groups?

The answer is yes. Straight out of the box, each Commons user can create groups.


How can I use pathauto to generate URLs for deeply nested vocabularies?

Try something like this as your vocabulary pattern:

[term:parent:parent:parent:name]/[term:parent:parent:name]/[term:parent:name]/[term:name]

And your last question should go away.

Just be sure to repeat the parent: part at least as many times as max term depth expected in your vocabulary. Pathauto will smartly skip overhead items.

I know it's not super-scalable, but it works for me.


Migrate user passwords salted and hashed with md5

I don't like this solution because it decreases security of the site and throws away whole D7 password hashing code.

How does this decrease security? The D7 hashing function is pluggable, you can migrate the fields without (re)hashing them by setting $this->md5Password = FALSE and then using your own hash function from the legacy system, as commented on in the issue you posted:

https://www.drupal.org/node/1326450#comment-5192996

You're still using the Drupal API to perform authentication and more than likely the legacy hashing technique while not stellar is probably not brain dead.

Now, if you don't like side-stepping the default Drupal7 password semantics -- then don't. Or do it for a temporary amount of time as you mentioned and inform your users of a pending system-wide password reset. This happens alot all over the net even recently on Drupal.org.

You may force all site users todo a password reset and setup strict password enforcement using the Password Policy module:

  A password policy can be defined with a set of constraints which must
  be met before a user password change will be accepted. Each constraint
  has a parameter allowing for the minimum number of valid conditions
  which must be met before the constraint is satisfied.

  Example: an uppercase constraint (with a parameter of 2) and a digit
  constraint (with a parameter of 4) means that a user password must
  have at least 2 uppercase letters and at least 4 digits for it to be
  accepted.


Go to Manage form display of a content type and click on settings cog on right corner of Language field. There you will see a checkbox Include locked languages such as Not specified and Not applicable uncheck it to remove options like Not specified and Not applicable.


No, Node ids are unique.

But yes you can avoid this kind of issues in feature by using url alias in drupal as you can generate same URL for different node id if current node is deleted accidentally.

Documentation for URL alias https://www.drupal.org/node/120631


For anyone else looking for help with this in the future, here's how I did it:

I used the default pages that are generated for each term - I didnt realse that all terms generate a page that displays all of the content associated with them.

I then enabled and used the default Taxonomy view to edit the output of the term pages.

I also used the Taxonomy Menu module to create a menu of each taxonomy,


Have you already tried the Commerce Product Add-On module? That sounds like exactly what you're describing.


Trying AJAX autocheckboxes example; getting Notice: Undefined index: #ajax in ajax_form_callback()

Reinstall XAMPP! if that doesn't fix it, try a different stack:

Bitnami
Acquia
MAMP

So installing the Bitnami Drupal stack and testing successfully there indicated a problem with my XAMPP install. Also wanted to try the Acquia stack, was ok, ended up going back to XAMPP.


How to duplicate a line item in shopping cart programmatically

You can clone a line item and save it without any problems:

$cloned_line_item = clone($line_item);

But if what you want is to add it back to the order, you'll probably want to call commerce_cart_product_add to add your line item back to your order:

commerce_cart_product_add($uid, $line_item, FALSE);

Be careful with setting the combine options correctly if you don't want your line items to be aggregated.

$line_item->data['context']['add_to_cart_combine']

Update: Adding more details on the combine part.

In case you don't want to combine any line items for that product type:

Be aware that the combine options are at formatter level for the add to cart button, so you need to set them everywhere you're using this formatter, in manage display settings for all your view modes, in views... the configuration is not shared. This is very important as there might be hidden places you forgot to configure (if I had a penny every time I forget to configure this in "Teaser", i.e....)

In case you want to combine some times and others not:

The function commerce_cart_product_add above has a combine parameter to make Drupal Commerce try to combine or not and add a new element to the cart or just increase the quantity of an existing one.
On top of that, there's something called comparison properties, by default these are all the fields that the line item has:

foreach (field_info_instances('commerce_line_item', $line_item->type) as $info) {
  if (!empty($info['commerce_cart_settings']['field_access'])) {
    $comparison_properties[] = $info['field_name'];
  }
}

So one way you've got to hook into this process is hook_commerce_cart_product_comparison_properties_alter to define more comparison properties.


Yes, possible and very easy.

Short version

You can use this render array.

This will render the Cart form if your product can be added to cart - if it has available variations bascially.

$combine = TRUE;
$langcode = 'en';
$view_mode = 'cart';

$build['add_to_cart_form'] = [
  '#lazy_builder' => [
    'commerce_product.lazy_builders:addToCartForm', [
      $product_id,
      $view_mode,
      $combine,
      $langcode
    ],
  ],
  '#create_placeholder' => TRUE,
];

Full example with a Controller

You can use a custom Controller to render your own Add To Cart form.

First, prepare the route in mymodule.routing.yml:

# Custom route to render Add to cart form.
mymodule.add_to_cart:
  path: '/mymodule/add_to_cart/{product_id}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CartController::addToCart'
    _title: 'Add to cart'
  requirements:
    _access: 'TRUE'
    product_id: \d+

Second, create your Controller:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for cart routes.
 */
class CartController extends ControllerBase {

  function addToCart(int $product_id) {
    $build = [];

    if (!$product_id) {
      $build['error'] = [
        '#type' => 'item',
        '#markup' => $this->t('Wrong product ID'),
      ];
      return $build;
    }

    $build['add_to_cart_form'] = [
      '#lazy_builder' => [
        'commerce_product.lazy_builders:addToCartForm', [
          $product_id,
          'cart',
          TRUE,
          'fr'
        ],
      ],
      '#create_placeholder' => TRUE,
    ];

    return $build;
  }

}

Finally, add a link to open a modal on front end, as follow:

Add product to cart

Clear cache

You should be good to go! :)


Load a Module versus JavaScript embedded in Theme

You can do pretty much anything you want with custom code, including this.
The question is should you use custom code or an existing module that provides the functionality you're after.

The answer depends on your specific situation.

For example if you have limited time/budget it may be better to go with something that's already available, like views slideshow, and keep as much of your budget as possible for other tasks.
However there might be some reason that option isn't ideal, like maybe the modules have lots of functionality you don't need and you want to code something more specific to your requirements.

Another possible issue might be that the existing module doesn't do something exactly the way you need it to, so then you have to decide whether you write a patch to modify that module or if you want to write custom code.

This question deals with pros and cons of using custom code instead of existing modules.


Running 'composer update' replaces module folders

Is this normal behavior for composer?

Yes

  Is there some way to specify that I only want to replace what's going into the vendor directory?

Sure, remove the reference to the module(s) from composer.json. Obviously at that point you’ll need to manage any updates for them yourself.

A better resolution would be to install Composer patches, and patch the modules automatically as they’re being installed/updated.


What's your trick to document (in the UI?) variables overridden in settings.php?

You could implement a hook_help that displays a message on the page where you would set the variable. Would still need to do it manually per variable though.


Drupal 7 comes with a Testing module, and for Drupal 6 you can download http://drupal.org/project/simpletest.

It doesn't do anything automatically (how could it..) but it allows you to write automated tests that test the functionality of your custom modules.

I wrote a blog post about this a while ago: Writing automated tests for Drupal 7. Even though the title says Drupal 7, most of it applies to Drupal 6 too. See Simpletest documentation on drupal.org for more information.


how to do mapping user to user in drupal

So you have 4 user roles and 2 different content types. The first 2 user roles work with content type 1 and the other 2 user roles with content type 2.

I believe you'll find the answer to your question on this page as it explains:

How to configure Workbench Moderation states
How to configure and check Workbench Moderation transitions for each role

So you can set additional States according to your needs but the three default States of "Draft", "Needs Review" & "Published" seem to do the job for your case. You can also set what transitions between which states should generally be available and then configure the transition permissions for every role according to your needs.

Applying those guidelines, a Contributor1 user would create a node of content type 1 (in "Draft" state), given that they have the proper content creation permission. After that, Contributor1 would not be able to do the transition to other states for that content type. On the other hand, Validator1 should be given permissions to do the transition from "Needs Review" to "Published" for content type 1.


Dynamic Persistent Menu problem / module alternatives

Yes, as you mention, their is a conflict between the Dynamic Persistent Menu and Special Menu Items modules.

Dynamic Persistent Menu adds a CSS class (.dynamic-persistent-menu-menu-item) to all <li> elements of a menu that is overridden by Special Menu Items.

This bug comes from the special_menu_items.module file, line 64. You can remove the following code:

$element['#attributes']['class'][] = 'nolink';
$element['#attributes']['class'][] = 'separator';

EDIT: The main bugs come from Dynamic Persistent Menu. As you know, the class attribute passed to theme_menu_link() should be an array, but in Dynamic Persistent Menu a string is passed.

So your WSOD (blank page) comes from theme_dynamic_persistent_menu_menu_item() in Dynamic Persistent Menu, where a string is passed instead of array.

When Special Menu Items tries to override it, a fatal error is presented.


My Custom drupal 8 module does not shown in modules list

Remove the spaces between the identifiers and colons:

name: Drupal Center Custom Migrate
description: This module provides custom migration configuration and plugins to migrate my custom site from drupal 6.
type: module
core: 8.x

package: Custom migrate
dependencies:
  - migrate
  - migrate_plus
  - migrate_tools
  - migrate_upgrade
  - migrate_drupal

Then it'll work.

See the YAML rules for more info.


Is there an OOP alternative to hook_entity_operations_alter() in Drupal 8

The operations originally come from UserListBuilder. You can extend this class and alter User entity info to point list builder property to your class. The problem is that you need to implement hook_entity_type_alter wich is not in OOP land :-).

I suggest you keep this hook until Drupal become a true OOP application.

This article contains a quck comarision of hooks vs OOP events.


How to authenticate a user which exists in an external site?

Based off of your comments, it sounds like you have the basic procedure down: hook_form_alter the user_login form, and use your own validation.

If you take a look at user_login_default_validators, I think your problem is that you need to swap out user_login_authenticate_validate with your own, but still get the form back into the same state.

I think your best bet is to do your RESTful authentication in a validator, and then set $form_state['uid'] to a valid user in the system.

My suggestion is to create a single user that you map all of your REST logins to, and use this as $form_state['uid'].  This way, you still can use the permission system across your site.  To get them logged in, you can just do a user_load with the $uid of your special user.

I am not positive, though, if having all of these users will cause any problems with sessions.  I have only done something similar with Drupal 6 and each remote user got their own account in Drupal.


Node PHP function causing CRON not to run properly

Try debug_cron module to debug the cron issue.Also I am not sure if the mentioned code is even executing on cron run.
This module provides debugging of

 fail due to programming or runtime errors
 time out (PHP, server, database)
 are very slow

  Cron Debug will also allow you to test run specific cron functions
  while not running others. This can be nice for developing cron
  functions where you don't want to run a full cron.php with all
  maintenance, alerts and other tasks every time you test your own
  function.

Also why not you putting the complete code inside the first if conditions like'

if ($node = menu_get_object()) {
  $nid = $node->nid;
  $staticPath = file_create_url($node->field_static_ad['und'][0]['uri']);
  $flashPath = field_get_items('node', $node, 'field_flash_ad');
  if ($flashPath) {
    $flashPath = file_create_url($node->field_flash_ad['und'][0]['uri']);
  } else {
      $flashPath = file_create_url($node->field_static_ad['und'][0]['uri']);
   }
}


How to read file submitted through file field in block configure form

You want to use the #type 'managed_file' instead of just file: http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#managed_file.

That will then automatically save the file and create a row in {file_managed}, You just need to set it as permament, as explained in the link above and then save the fid, for example with variable_set().

You can also set the #default_value for the fid, and it will display the field again.


How to show titles as plain text on rendered entity reference

If you have display suite. You will need to do this no in the rendered part, you have to do this in the view mode of the content type that you are rendering for instance. I have installed display suite and that helps me to have more control over the layout

profile product --> rendering entity from news product displayed as teaser
news product --> In news product in the teaser view mode or full mode in your case, in manage display choose the title and select no link.

You need to have applyed a column layout in display suite to see it.


Views 3.8 hook_views_default_views() stopped working

See the API documentation: The correct way to declare the version is by the major number only (i.e. an integer) not the entire version as a string.

// code included in my_module.module
function my_module_views_api() {
  return array('api' => 3);
}


Conditionally unpublish a nodes more than latest 20

You need an entity query to get the nodes filtered by the content type, sorted by the changed or created date and starting with the 21th node:

  $query = \Drupal::entityQuery('node');
  $nids = $query
    ->condition('type', $type)
    ->sort('changed', 'DESC')
    ->range(20, PHP_INT_MAX)
    ->execute();
  $nodes = Node::loadMultiple($nids);

You could also add a condition for published nodes, so that you don't load nodes that don't need to be unpublished:

    ->condition('status', NodeInterface::PUBLISHED)


hook_form_alter selecting a default value in a node reference select list

CCK requires a little voodoo to alter values with a hook_form_alter(). You need to implement a special type: after_build, so put this code in a custom.module:

//Declare the callback for after_build for page node form
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'page_node_form) {
    $form['#after_build'][] = 'custom_after_build';
  }
}

function custom_after_build($form, &$form_state) {
  //Set my node ref to 5
  $form['field_node']['nid']['nid']['#value'][0] = 5;
  //you can set more than one using
  $form['field_node']['nid']['nid']['#value'][2] = 6;
  //have a look at the form after after_build
  dsm($form);
  return $form;
}

I adapted a previous answer of mine, but I have to admin that node reference is even more confusing ;)


You can find it in the last page of the releases for drush on drupal.org (right at the bottom, unsurprisingly).

As Greg mentions in the comments, Drush 1.x is a module so it needs to be put in the modules folder and enabled.


How to pass data between operations of a single Batch?

Thanks David for your answer. But unfortunately $context['sandbox'] values were not retained through operations - they were retained through iterations of the same operation but not between operations.

Interestingly though, I found that $context['results'] values were retained between each operation.
I did a simple test using the following module:

<?php
function mytest_menu() {
  $items = array();
  $items['admin/content/mytest'] = array(
    'title' => 'mytest',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mytest_form'),
    'access arguments' => array('administer content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function mytest_form() {
  $form = array();

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

function mytest_form_submit($form, $form_state) {
  $batch = array(
    'title' => t('Working ...'),
    'operations' => array(),
    'finished' => 'mytest_batch_finished',
    'init_message' => t('Starting ...'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'progressive' => FALSE
  );
  $batch['operations'][] = array('mytest_initialize', array('test data'));
  $batch['operations'][] = array('mytest_perform', array('different data'));
  $batch['operations'][] = array('mytest_perform', array('different data'));
  $batch['operations'][] = array('mytest_perform', array('different data'));
  batch_set($batch);
  batch_process('admin/content/mytest');
}

function mytest_initialize($d, &$context) {
  dsm($d);
  $context['results']['test'] = 'inti val';
  $context['test']['test'] = 'init val';
}

function mytest_perform ($d, &$context) {
  dsm($context);
  $context['results']['test'] = uniqid();
  $context['test']['test'] = $context['results']['test'];
}

function mytest_batch_finished($success, $results, $operations) {
  dsm($results);
}

After the batch finished, I could see the dsm()'d messages. voilà: values were retained.

http://i.stack.imgur.com/tkAXx.png

It seems like only $context['results'] was given to the next operation. Arbitrary keys ($context['my own key'] for example) didn't work.

Hope someone will find this useful :)

PS: *previous not previos (screenshot).


Assign file to entity image field (Programmatically)

You add an image to the field by assigning the file id to target_id:

$entity->field_someimage[] = [
  'target_id' => $file->id(),
  'alt' => 'Alt text',
  'title' => 'Title',
];
$entity-save();

You can add other properties at the same time. An image usually needs a title and an alt text.


Building a full featured gallery with voting system

1 vote per image, per node, per user, and users are able to vote on
  any image in the node

I don't fully understand the use case here; it might be easier to visualise the scenario with a fuller explanation?

At a guess, the issue might revolve around the use of field collection module here? I'm not a wizard at the internals of that, but personally in this situation I usually manage this with a container/item setup:

Gallery (node/entity)

Image (node/entity)
Image

Gallery

Image
Image

I then relate these either with entity_reference or I guess you could use inline entity form, depends. I don't know if there is anything that precludes you from doing it this way, but I think you're more likely to have better data from votingapi et al like this? Probably using two content types is going to give more joy than entities for that reason.

This is all from a site builder perspective, where using this kind of setup generally means I have to write as near to zero code as possible!


You need to implement hook_mail too and define some_mail_key in your hook_mail :

/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  if ($key == 'some_mail_key') {
    $message['subject'] = $params['subject'];
    $message['body'][] = $params['body'];
  }
}

Then you can use drupal_mail function like :

drupal_mail('mymodule', 'some_mail_key', $to, language_default(), $params, $from, TRUE);

Change mymodule with your module's name.


For reference there are a couple answers depending on the situation. The order of the field display can be controlled by going to store->configuration->order settings->Manage Display which I believe would solve the OP question.

If you are looking to setup a custom .tpl.php file I wasn't able to successfully use the template suggestions which are:

commerce_order
commerce_order__commerce_order
commerce_order__commerce_order__customer
commerce_order__OID (where OID is the order ID)

I found these in template_preprocess_entity in $variables['theme_hook_suggestions']

However, since an order is an entity I was able to use http://drupal.org/node/1238606 (tutorial on theming custom entities) and use a template of my own choosing.

template.php

/**
* Process variables for MYTEMPLATE--order.tpl.php.
*/
function MYTHEME_preprocess_MYTEMPLATE(&$variables) {
  // This is the generic entity preprocessor
  template_preprocess_entity($variables);
}

/**
 * Implements hook_entity_view_alter to alter the entity theme used by
 * commerce_order.
 */
function MYTHEME_entity_view_alter(&$build, $type) {
  if('commerce_order' == $type){
    $build['#theme'] = 'MYTEMPLATE';
  }
}

From there you can use: sites/all/modules/entity/entity.tpl.php as a template for your template.

Hope this helps someone.

Cheers,

Rob