You can use hook_field_formatter_settings_form to add formatting of the field as shown in example below:

function example_field_formatter_info() {
  $info = array();
  $info['default_formatter'] = array(
    'label' => t('Show as link'),
    'field types' => array('example_field_type'),
     'settings' => array('target' => '_blank'), // <--- THIS
  );
  return $info;
}

function example_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();
  if ($display['type'] == 'default_formatter') {
    $element['target'] = array(
      '#type' => 'select',
      '#title' => t('HREF target'),
      '#options' => array('_blank' => 'New window', '_self' => 'Same window'),
      '#default_value' => $settings['target'],
      '#description' => t('Control where the link opens (i.e. set the TARGET attribute of the A element).'),
    );
  }
  return $element;
}

function example_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings']; // Key needs to be defined in info array (who knew?)
  $element = array();
  if ($display['type'] == 'default_formatter') {
    $target = $settings['target'];
    foreach ($items as $delta => $item) {
      $element[$delta]['#markup'] = "{$item['label']}
";
    }
  }
  return $element;
}

Update #1:

/**
 * Implements hook_field_formatter_settings_summary().
 */
function example_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = t('Show as link'); // we use t() for translation and placeholders to guard against attacks
  return $summary;
}


creating nodes with many to many relationship type with some fields?

You are looking for the capabilities in the Relation module. With it you can relate a seller to a book, and attach a price field to the relationship.

  Relation is an API module and storage model for both simple and the
  most complex relations between entities. The module can handle both
  directional and symmetrical relations very well.

  Relations are entities and can therefore have fields. This makes
  Relation the most flexible and powerful relation model out there.
  (Still, using Relation with anything but the default SQL storage will
  not work in most cases.)


You need i18n module. It gives you a possibility to display a language switcher block on the front end.

Also check Localization update module for automatic update of translations.


Well you can always use form altering to provide you own submit function


How can I get uploaded files sent to webforms to be attached to an email?

The steps to get uploaded files to be sent as attachments to be included in emails from Webforms go as follows:

Install SwiftMailer and Mail System Modules
In Mail System Module Configuration, add Webform Module and set Handler and Mailer to Swift Mailer
In Swift Mailer Configuration, Messages tab, set to HTML (may not be necessary, but it worked for me.
In Structure..Webforms..[your webform name]..Settings..Email/Handler..Edit..Advanced Tab set the check box for include files as attachments

The body of the email still has a broken image, but the files are attached.
I believe I can modify the body of the email to just include the fields that I want by expliciting naming each one, however, if you uncheck the fields that are "broken" in Included Email Values (hoping to continue to use [webform_submission:values] in the body template) the email does not show the broken connection but it also no longer includes the attached file(s)


The module http://drupal.org/project/google_image_sitemap has a d6 version but it was released after the d7 version :)


It is made available as a view template.

Goto admin/structure/views/add-template and create a new calendar view based on the Date Field that you want to use.


If you are not in control of the initial building of the content then hook_block_view_alter() can alter the content of any block before it is rendered.

From the API page:

Perform alterations to the content of a block.

This hook allows you to modify any data returned by hook_block_view().

To target a specific block...

In hook_block_info(), each block your module provides is given a unique identifier referred to as "delta" (the array key in the return value). Delta values only need to be unique within your module.

The variable $block is passed into hook_block_view_alter(). This variable is defined as:

$block: The block object, as loaded from the database, having the main properties:

module: The name of the module that defined the block.
delta: The unique identifier for the block within that module, as defined in hook_block_info().

So you can check what the module and delta of the block to target specific blocks.


Drupal form does not save the user input value in the $form_state array

File input fields work differently than other input fields. This is a restriction of HTML. The file path is not transmitted to the server, because it is considered sensitive information. Only the file data and the name of the file is transmitted to the server.

Use file_save_upload() to save the file. To find out what to pass as the $source argument, print out both $form_state[values] as well as the $_FILES array.


Does a template override require a subtheme?

The correct answer is no since you can also override templates in a module (example). It doesn't sound like you want to do that, though.

At minimum you would have to create an *.info file that includes the dependency:

name = My Theme
description = Just a basic theme
core = 7.x
base theme = base_theme_name


Help with Drupal.behaviors and AJAX refresh

Well it seems I have found a solution :-)

I needed to add 'context' to the function of border adding itself

so this

 $(".moviescreenss").each(function () {

becomes this

 $(".moviescreenss",context).each(function () {

and now it seems to work fine :-)

Still need to see if I can make the whole code more efficient, I'll go to stackoverflow with this and update here if I get anything better


How to create a view showing the products from a user's company?

To achieve it with the current content architecture:

Create view of users.
Add a relationship Entity Reference: Referenced Entity. Mark it as required. This will make a connection between the user and the company.
Add another relationship Entity Reference: Referencing entity. Before saving add the value of the Relationship select list and select the relationship created in step #2. Mark this relationship as required too. This will make the connection between user company and the product.
You should now get the fields of products you could add to the view using the relationship you have built at step #3


Possible to pull the validate hook on forms not in form api

The validate handlers for forms aren't hooks as such, they're just functions that use a naming convention provided by the FAPI (small point, but worth mentioning).

Technically speaking, you might get away with putting said function in PHP in the body of a node. If you have a form called MYMODULE_form_test, and declare a function called MYMODULE_form_test_validate in the body of a node, the processor might well pick it up in time, and Drupal might call it during form validation. But you'd probably get some strange, incorrect results when you turn caching on.

Either way, I wouldn't rely on it working forever more; it's certainly not an advisable workflow, and keeping code in the node body is considered very bad practice.

Creating a module only takes a couple of minutes, and this sort of functionality is exactly what they're designed to contain.


Multistep information collection with reference to price addition or substraction

If you dont want the shopping aspect of the site then I would do the following.

Create the content types called the product.
Add a field with a drop down with the different steps (Processor, RAM etc)
Add a field to add the price.

Create a custom module with formAPI to call these values and do the needful.

Multistep forms would be the way to go. With Ajax to give it some flare.

You can download the example module to see how the form APIs work. The examples you would want to check would be the form example and ajax example


How do I add a span class to form item title in register form?

You can use the following code:

'#title' => '' . t('I have read and agree to the terms of service', array('@terms' => url('terms'))) . '',


Image gallery as a field, not a content type?

Make a View for your gallery and put that view in a block. Then activate that block for the desired content type; putting that block in the region you want it to appear.


Contrib Module JavaScript interfering with Node

That seems to be a common issue with the sharebar module.  The 7.x-2.x-dev version moves the sharebar into a block so that you can place it anywhere with either the block ui or the context ui.

The 7.x-2.x version is still in dev so you may need to do a little testing before enabling it on production, however, the module maintainer is suggesting that people upgrade to this version anyway.


So you'll need two tampers for that field. From the manual:

Find replace REGEX
Find and replace a user-specified string using REGEX with an option to limit the number of replacements. See the PHP Manual on PCRE Pattern Syntax for a complete reference, or RegexPal for a quick tester.
Convert to boolean
Convert a user-specified string to boolean, with the option of specifying what to do in the case of no match.

Here is a regular expression that will find SSR and replace the entire string with it.

https://regex101.com/r/aO0uG3/2

/\b(SSR)\b/\1/

Then match SSR in the Convert to boolean tamper. (Note: The regex in the screen shot is now out of date. Use /\b/(SSR)\b/ instead)


Only show menu level 2 from active trail (with option Show as expanded)

I also discovered that if "Show as expanded" is checked, the menu is displayed at sublevels where it should not appear. This patch fix this behavior:

https://www.drupal.org/node/2631468#comment-10792980


An entity handler class is instantiated via EntityHandlerInterface::createInstance static method, which takes the container as the first argument and the EntityTypeInterface as the second argument.

So you would not need the service and have to use the injected container to instantiate your class.

class MyCommentStorage extends CommentStorage implements EntityHandlerInterface {

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeInterface $entity_info, Connection $database, EntityManagerInterface $entity_manager, AccountInterface $current_user, CacheBackendInterface $cache, LanguageManagerInterface $language_manager) {
    parent::__construct($entity_info, $database, $entity_manager, $current_user, $cache, $language_manager);
  }

  static public function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $entity_type,
      $container->get('database'),
      // etc...
    );
  }

}


You can customise your search-results.tpl.php by copying this file from the core search module and putting it into your theme directory. You can add your menu in where you like using code:

<div id="menu">
  <?php print theme('links__system_main_menu', array('links' => $main_menu)); ?>
</div>

Also remember to clear your cache after making changes!


Attachment added through hook_mail_alter() is making no effect

If you're not already using it, I think you need MIME Mail or something similar to handle attachments, and when you do, your attachment needs to be added as an array of arrays rather than an array.
This is what the README file says.

You can use the following optional parameters to build the e-mail:

'plain': Boolean, whether to send messages in plaintext-only (optional, default is FALSE).
'plaintext': Plaintext portion of a multipart e-mail (optional).
'attachments': Array of arrays with the path or content, name and MIME type of the file (optional).
'headers': A keyed array with headers (optional).


Error messages appear in background page, not in dialog

To help those implement @Clive's suggestion you can do the following:

(function ($) {
  $(document).ready(function () {
    $("#dialog").dialog({
        autoOpen: false,
        modal: true,
        width: 400,
        open: function() {
            $('.messages').prependTo('#dialog');
        }
    });
  });
})(jQuery);

Substitute #dialog with the name of the div containing your dialog's components.


New e-commerce site: stuck with D6 Ubercart for now?

I would agree. I have too researched this and have come to the same conclusion. We are still starting all Drupal ecommerce projects on Ubercart and D6 (Looking forward to Drupal Commerce though)


Can I update from 7.34 to 7.41 directly? What is the safest way to do so?

Yes, Drupal Core is self-contained in that any forward version of Drupal contains all the updates of intermediary versions of Drupal you are missing. So, you don't have to install and update Drupal manually through every single version of Drupal that is released.

The recommended way is to simply overwrite your drupal site files as per the distributed documentation with Drupal. Put your site in Maintenance Mode and run the update script.

Alternatively, you can upgrade Drupal via Patches:
https://fuerstnet.de/en/drupal-upgrade-easy-way


Entity query respects access by default. Add the ->accessCheck(FALSE) method to prevent access checking. Be careful, removing access checks may expose restricted data. It may be better to configure view permissions or whatever access system you're using to allow anonymous users to access content instead of removing the check.


Bootstrap progress bar missing style option

#markup filters the style option because of the xss filter.

Use an inline template instead:

$form['pr_bar'] = [
  '#type' => 'inline_template',
  '#template' => '

        {{ complete }}% Complete (success)

',
  '#context' => [
    'complete' => '40',
  ],
];

You can pass the percentage value as twig variable.


Modifying CSS class of Menu Block links?

You would need to copy the whole function. There is a good example on the theme_menu_link() page.

You could also check out the Menu attributes module which allows you to add classes to individual menu items.


'path' in array with special characters using imagecache

I would use a hyphen "-" instead of plus "+" as it is URL safe and the standard MO on Drupal


$form array in views-exposed-form.tpl.php has #printed set to true?

#printed is set by drupal_render, so if the actual form element is rendering into a string the $form has #printed, try it out on any other drupal form theming.


Based on your comments and the fact you will be writing some custom code for the video player in your site. You can easily include the Drupal user id into flash variables.

In order to do this, you will load the Drupal user object of the currently logged in user. This is quite easy to do.

<?php

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

?>


You've got definitely a Drupal upgrade problem, drupal_get_hash_salt used to be in common.inc and was moved to bootstrap.inc in Drupal 7.23 version as you can see in https://www.drupal.org/node/1739986.

Something went wrong with your core update, I'd suggest you to backup your data and upgrade your files to the latest version, then run update.php and check everything is OK.


Instead of inspecting the request object directly, the current_route_match service is the preferred object to consult for request parameters. It provides both the raw and upcast values of parameters. Additionally, using \Drupal\Core\Routing\StackedRouteMatchInterface you can retrieve values from the master request.

The reason you are having trouble with /comment/{comment} is because that route is special: it performs a subrequest to view the entity the comment belongs to. This explains why you only have the node entity available when viewing a comment on a node.

To work around this, consult the master request:

$comment = \Drupal::routeMatch()->getMasterRouteMatch()->getParameter('comment');


How do I alter the form submission handler?

$form['#submit'] stores an array of form submit handlers. With the code you provided you're overwriting it by adding only your own. To get the result you want you should add your submit handler as the first element in the array like this:

array_unshift($form['#submit'], 'mymodule_custom_submission');

Getting the right values in the right forms and replacing some characters is probably a bigger issue in itself. You may want to narrow down the forms/fields you need to change to make sure you don't break anything.


I finally figured out the answer. Only took me a week.

Under the view settings there is a "Format" option, and beneath that there is a "Settings" link. Upon clicking there are options to make your new fields sort-able or not to the user. Adding 'click sortable' => TRUE just exposes that radio button!

Good grief that was causing me some headaches! I was beating myself up on the code when it was a UI setting withing Drupal.

Something else to consider is the actual sorting. There are many different handlers for sorting fields. This particular field is a date. In order for this to work, the date needs to be stored as a UNIX time epoch. There are flags that I did not pass that can allow you to choose the granularity of the sort, (seconds, minutes, days, months, years).

This is what my code ended up looking like to make the date sort actually work as expected. When I stored the date as a UNIX time epoch.

/**
 * Implements hook_views_data().
 */
function uc_order_views_data() {
  $data['uc_orders']['data'] = array(
    'group' => t('Order:data'),
    'title' => t('Ship Date'),
    'help' => t('The date to ship the order.'),
    'field' => array(
      'handler' =>'uc_order_handler_field_ship_date',
      'click sortable' => TRUE,
     ),
     'sort' => array(
       'handler' => 'views_handler_sort_date',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter_date',
     ),
  );
}

Now, lets take a look at the uc_order_handler_field_ship_date handler. You want to be sure that if you are not using the standard sort handler, that you extend the proper handler. If this date was not buried within some serialized data, I wouldn't even need this class and the default views handler would be sufficient.

class uc_order_handler_field_ship_date extends views_handler_field_date {
  /**
   * Overrides views_handler_field_date::render().
   */
  function render($values) {
    $data = unserialize($values->uc_orders_data);
    if (isset($data['fedex_calendar_ship_date'])) {
      $date = $data['fedex_calendar_ship_date'];
    }
    else {
      $date = "-";
    }
    return date('n/j/Y',$date);
  }
}

For more information on all of the sort handlers available see:
http://api.drupal.org/api/views/handlers%21views_handler_sort.inc/class/views_handler_sort/7


Set entity reference field to 'autocreate' directly in the entity field definitions

I finally found a way to get it to work after digging through the code for the EntityReferenceAutocompleteWidget. To enable automatic creation, I needed to edit the handler settings. Here's my code:

$fields['client'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Client'))
  ->setSettings(array(
    'target_type'      => 'client',
    'handler'          => 'default',
    'handler_settings' => array(            // Added
      'auto_create'    => TRUE              // Added
    )
  ))
  ->setDisplayOptions('form', array(
    'type'     => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size'           => 60,
      'placeholder'    => ''
    ),
    'weight'   => 0
  ))
  ->setRequired(TRUE);


How to create a chart for tracking Product stock over some period of time using Ubercart?

You should try views charts for creating graph

  About the Project

  Provides a "charts" style output for Views module so you can render
  result-set not just as text (list, tabular) but as pie-chart,
  bar-chart, scatter-plot etc.

  DC DrupalCon '09 Presentation

  http://vimeo.com/5306364

  Dependencies

  Views Charts and Graphs Suggested modules

  For Drupal 6 you will need the Views GroupBy: if you want to chart
  anything actually useful. Views 3 for Drupal 7 has grouping built in.
  Documentation

  Views Charts has basic usage instructions available as Advanced Help
  pages. Please install and enable it to see the available help.


I don't think this is possible without modification to Drupal core's routing. When you specify a Views page as the frontpage (e.g. /frontpage when you override the default Frontpage view), you're telling Drupal to route all www.example.com requests to that path (e.g. www.example.com/frontpage).

If you mandate that a required contextual filter (e.g. /frontpage/%), that path component isn't "copied over" (e.g. www.example.com/cookies doesn't route to www.example.com/fronpage/cookies). Nor can you add a views page with the root path /. If this was possible, you'd then have to deal with the problem of overlapping paths (e.g. should /admin be handled by system_admin_menu_block_page() or by your view?).

Instead of trying to fight Drupal's routing system, you'd be better off trying to hook into the alias system. For example, a module invocating hook_taxonomy_term_insert()/hook_taxonomy_term_update() could add a new alias for each term item you wish to shortcut to your view (e.g. aliasing /cookies to /frontpage/cookies).


Set value to Field collection item link field

I managed to solve it by using an array in setValue.

$field_collection_item2->field_url->setValue(array('uri'=>$base_url . '/form/email-project-completion-survey', 'title' => 'Survey'));


How do I set the HTML5 date "min" attribute?

In Drupal 8, the datetime fields are HTML5 inputs, so the popup is provided by the browser itself, or from a polyfill library for browsers that don't support these inputs (eg, Firefox).

If you want to provide a default value, you can do it from the settings for the field.  You can use the Current Date or a Relative Date as the default.  Despite the name and the docs on Relative Date, you can use this to set an actual date/time.

If you need to pull the default value from somewhere else (like config), you would hook_form_alter() the node form, and then check the field value.  If it is empty, you would set the value there.


How can I redirect users on login with PHP?

$edit['redirect'] = $redirect; doesn't stop other operations being executed I think.. The only thing I can think is to stop them with drupal_goto, but you should check you won't break anything else or not:

function MYMODULE_user_login(&$edit, $account) {
  // Allow users to reset their passwords
  if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
    // Under 18
    if (in_array('administrator', $account->roles)) {
      $redirect = 'admin/hud';
    }

    drupal_goto($redirect);
  }
}


Paragraph of text in webform generated email is split into multiple lines rather than presurving single line of text

The issue seems to be with the plain text format of the mail.If you want to send mail content with designed structure then you must use  Mime mail module.Once you enable the module you can use a HTML formatter for the textarea that is used to structure the mail. Let me know if you face any issues.


Use print_pdf in the background on node save?

The function used from that module to output PDF is print_pdf_generate_html(), which gets a filename as last parameter.

To understand what to pass as first argument, see print_pdf_generate_path(), which is the function calling print_pdf_generate_html(). In particular, see the following code.

$print = print_controller($path, $cid, PRINT_PDF_FORMAT);
if ($print === FALSE) {
  return;
}


Services 3.5 q=system/connect.json 404 (Not Found)

what version of drupal did you use?Can you try to remove the q?= and try it again?Also i notice on OPTIONS http://{localhost}:8888/drupal2/?q=system/connect.json 404,it doesn't contain your endpoint.


AFAIK, this cannot be achieved using the block title field, however using the Token Filter module, you can just drop the token in the body area of the block and wrap it in an H2 tag and it will appear as if it was the block title. (Just set the block title to <none>)


Permanent Cookie Contains Sensitive Session Information

Your app scanner is alerting you that cookie session data is being sent over an insecure channel (http://site-name/user/login?ModPagespeed=noscript) and is susceptible session hijacking.

One way to resolve this is to force your website to use HTTPS only, thus preventing anyone from sniffing out session data.


Show comment author e-mail in comment.html.twig

If you have a fresh Drupal 8 standard install, go to: 'People >
  Permissions' and Allow anonymous users to 'Post comments' and 'Skip
  comment approval'. Then go to: 'Structure > Content Types > Article >
  Manage Fields' and edit the 'Comments' field. Go to 'Anonymous
  commenting' and select 'Anonymous posters may leave their contact
  information'. Click 'Save settings'. Now when you go post a comment as
  an anonymous user you can leave your e-mail.

You can print that e-mail value in plain text like this:

{{ content.comment_body['#object'].getAuthorEmail() }}

Now, this will print the e-mails of logged in users as well. If you don't want that, then you will need to add a conditional to check if their User ID is 0, which means they are anonymous.

{% if attributes.toArray()['data-comment-user-id'] == 0 %}

    {{ content.comment_body['#object'].getAuthorEmail() }}

{% endif %}


Please see the Apache Solr Views module for combining Solr and Views together.

If you are looking for a Views-only approach, you should watch this screencast on Exposed Filters.


How to add additional tab in the User Profile page using views

somethingelse/<uid> is a path alias for user/<uid>. When you set the path for a view, you need not to use path aliases.


How to set only one save button for a page with Editable Fields by Views?

You can use Editable views module. It uses one save button for all fields in a view.
Editable Views:

Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.
Currently, the following Views fields can be edited:

All FieldAPI fields
Node title


Invalidate node cache so hook_node_view() runs on each node view

For new content added to $build you have also add the cache metadata.

Example if you add data from a file entity do this:

$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($build, $file);

This adds the cache tag for the file and whenever this file is changed, the cache item of the node which contains information from the file gets invalidated.

If  the added $content is already a render array with cache metadata drupal will merge this. You can check, which cache tags are missing in $content and add them in the class that generates this data.

Reference: https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays

If what the comment in the code suggests you have a list of files, you can add the tag 'file_list'. All entities invalidate the tag [entity-type]_list when creating, changing or deleting an entity.

Edit:

If you use the standard tools, that is building single entity displays with the view() method and list of entities with Views, then you don't need to take care of cache dependencies, because the render arrays these tools produce contain all necessary cache metadata.


If you can, look instead at serving the image as a public file, so that your webserver can return it directly without loading Drupal at all for that request. Instead of seeing system/files in the path, you'd see a path to the actual image file on your server - eg sites/default/files/.

Review whether it's necessary to serve images using the Private download method, which introduces a Drupal bootstrap and access controls on all static file requests. The default for this is configurable at admin/config/media/file-system.

It may be you're seeing a delay across all requests handled by Drupal, and have noticed it because you'd expect serving a static file to be quicker than that? Note that requests for static files (eg your logo) are not similarly affected, but for me I see ~6s response time checking the more basic pages on your site (eg curl --head against your donate page).

Is your server overloaded, or do you have modules enabled which might be performing time-consuming operations (eg network activity, DNS lookup, ...) for every request?

A patch in d.o#2089789 gives you a means to remove the itok token if you do need to serve that image after checking Drupal's access controls.

The reasons for introducing itok are discussed in the Drupal 7.20 release notes.


Drupal sends emails to Hotmail but not to other accounts

Likely the problem is not in drupal, but in server environment. You could use Drupal SMTP Support module to bypass this.


Variations price adjust based on previous variation

http://www.drupalcommerce.org/user-guide/product-attributes-variations - here you can read about product variations, don't forget to enable field as an attribute field that can change the Add to Cart form

After that you need to create products for all variations with right prices. You can use http://drupal.org/project/commerce_bpc


How to send 2 mails simultaneously with drupal_mail()

You can use CC to send a copy to admin/yourself

$message['headers']['CC'] = "foo@gmail.com"


How can I edit the 'Title' field label of a Node content type within a module?

This is stored as a field override configuration. It's a separate config entity with the name core.base_field_override.node.your_node_type.title.


How should I structure a node migration that has three locations?

I used the following code to join to the location tables for each lid field in the d6 content.  Whee!

$address_arguments = array(
        'administrative_area' => array('source_field' => 'hq_province'),
        'locality' => array('source_field' => 'hq_city'),
        'thoroughfare' => array('source_field' => 'hq_street'),
        'premise' => array('source_field' => 'hq_additional'),
        'postal_code' => array('source_field' => 'hq_postal_code'),
);
$this->addFieldMapping('field_company_address','hq_country')
->arguments($address_arguments);

$address_arguments = array(
        'administrative_area' => array('source_field' => 'leg_province'),
        'locality' => array('source_field' => 'leg_city'),
        'thoroughfare' => array('source_field' => 'leg_street'),
        'premise' => array('source_field' => 'leg_additional'),
        'postal_code' => array('source_field' => 'leg_postal_code'),
);
$this->addFieldMapping('field_company_legal_contact','leg_country')
->arguments($address_arguments);

$address_arguments = array(
        'administrative_area' => array('source_field' => 'inc_province'),
        'locality' => array('source_field' => 'inc_city'),
        'thoroughfare' => array('source_field' => 'inc_street'),
        'premise' => array('source_field' => 'inc_additional'),
        'postal_code' => array('source_field' => 'inc_postal_code'),
);
$this->addFieldMapping('field_company_inc_state','inc_country')
->arguments($address_arguments);

$this->addUnmigratedSources(array('field_company_twitter:title','field_company_twitter:attributes','field_company_linkedin:title','field_company_linkedin:attributes','field_website:title','field_website:attributes'));

}
protected function query() {
$query = parent::query();
$query->leftJoin('location_instance', 'hq_i', 'hq_i.lid = f.field_hqaddress_lid AND hq_i.vid = n.vid');
$query->leftJoin('location', 'hq_l', 'hq_l.lid = hq_i.lid');
$query->addField('hq_l','street','hq_street');
$query->addField('hq_l','additional', 'hq_additional');
$query->addField('hq_l','city', 'hq_city');
$query->addField('hq_l','province' ,'hq_province');
$query->addField('hq_l','postal_code', 'hq_postal_code');
$query->addField('hq_l','country' ,'hq_country');

$query->leftJoin('location_instance', 'leg_i', 'leg_i.lid = f.field_legal_contact_address_lid AND leg_i.vid = n.vid');
$query->leftJoin('location', 'leg_l', 'leg_l.lid = leg_i.lid');
$query->addField('leg_l','street','leg_street');
$query->addField('leg_l','additional', 'leg_additional');
$query->addField('leg_l','city', 'leg_city');
$query->addField('leg_l','province' ,'leg_province');
$query->addField('leg_l','postal_code', 'leg_postal_code');
$query->addField('leg_l','country' ,'leg_country');

$query->leftJoin('location_instance', 'inc_i', 'inc_i.lid = f.field_incorporation_state_lid AND inc_i.vid = n.vid');
$query->leftJoin('location', 'inc_l', 'inc_l.lid = inc_i.lid');
$query->addField('inc_l','street','inc_street');
$query->addField('inc_l','additional', 'inc_additional');
$query->addField('inc_l','city', 'inc_city');
$query->addField('inc_l','province' ,'inc_province');
$query->addField('inc_l','postal_code', 'inc_postal_code');
$query->addField('inc_l','country' ,'inc_country');

return $query;
}


Scalable way to add custom css/js to a page

I had a theme, called bikeswitzerland. There I had a file template.php, where I added the following code:

function bikeswitzerland_preprocess_page($vars)
{
       $nid = array_keys($vars["page"]["content"]["system_main"]["nodes"]);
       $nid = $nid[0];

       $alias = drupal_get_path_alias("node/" . $nid);
       $theme_path = drupal_get_path('theme', 'bikeswitzerland');

       switch($alias)
       {
       case 'ask-us':
              drupal_add_css($theme_path . "/css/ask_us.css");
              break;
       };
}

Use preprocess_page hook in your theme. Upload your css files into a dir and create a table in the database, that stores the mapping between the page aliases/urls and appropriate css files.

Then inside the function check, what is the current page url and attach the appropriate css, like I did. And you'll solve your problem.


You can work with panels as suggested in the above comment.

Without panels nor any contrib module you can show blocks limited to roles on the specified error node. Review the blocks settings.

Maybe you need multiblock to place blocks several times.


How do I set the page title from view result (same as the view result)

Inside a views template, you could call drupal_set_title() with whatever you want out of the $view->result array.  You can put a drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>'); or its equivalent in there to see what you have to work with.

In Style Settings, just click on Theme Information, and choose one, I'd suggest modifying the Style Output one because you could also change $title in there as well.

ADDITIONS DUE TO COMMENTS:

No, views will not set this for you, I thought that's what you were asking.

In your views template for the view in question, you need to dig into your row result to get the value you want and then call drupal_set_title() with that.  Calling it with a null value only returns the existing title, if any.

For example, if you put the print_r() of your result in there, you will see what values you have to work with, and then you use them with this to set the title.

Let's say you have something like this:

[0] => stdClass Object
    (
        [node_title] => Sirens
        [nid] => 240
        [_random] => 0.000554758124570137
    )

which is the view result from a view I just put together that randomly returns node titles, you would do something like this in your template:

$title=check_plain($view->result[0]->node_title);
drupal_set_title($title);

You could also put this in a pre_render() hook like so:

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name==NAMEOFYOURVIEW) { // && $view->current_display == 'page' if needed
    $title=check_plain($view->result[0]->node_title);
    drupal_set_title($title);
  }

}

But either way, since I don't know exactly what your view row looks like, I can't tell you precisely what $view->result[0]......  you need.

Also, all of this is assuming your theme behaves nicely with the $head_title variable as well.


Hiding a tab on a user profile based on the user role

Just under Display content of "No results found" I see Display "Access denied" you need to use that one.
Denied users won't see the tab anymore.
If the display of your view is a page you can even manage the access directly into the "page's parameters" block and restrict the access by user role without using a contextual filter (unless the view really needs one).


How to assign a link or path to a button in drupalgap?

Try this in your hook_block_view():

var content = '
';
content += theme('item_list', {
  items: [
    l('Home', '', { attributes: { 'data-icon': 'home' } }),
    l('Saved', 'node/1029', { attributes: { 'data-icon': 'action' } }),
    l('Sponsors', 'node/969', { attributes: { 'data-icon': 'star' } }),
    l('Setup', 'node/1021', { attributes: { 'data-icon': 'gear' } })
  ]
});
content += '
';
return content;

Whenever linking in DrupalGap, the key is to use the l() or bl() functions which will properly assemble a link or button link for you. Here's the docs page with more info: http://docs.drupalgap.org/7/Pages/Navigating_Pages


You can use this module:

Block Visibility Groups

Here you can configure a visibility group which hides blocks for a specific content type.

The visibility groups not only provide more options for block visibility, they are also reusable, that means you can apply the same settings on multiple blocks.

Ctools also provides the functionality to hide blocks for content types, but there was an issue, I don't know if this is resolved.


Image Files Uploaded via REST got Temporary status - Cannot be refereced by Media Image

The solution I found so far is to fix a Drupal module code:
modules\contrib\file_entity\src\Normalizer\FileEntityNormalizer.php
on line 48 add:
$entity->setPermanent();

See:

Which Drupal 8.1.x Rest API property in the JSON request controls
Drupal's File status (Temporary and Permanent) logic?

Files created with REST API are only temporary


Clearing the caching tables did the trick! Thanks CodeNext!

However I could not use Drush, so I cleared them manually in PHPmyAdmin using this post


I don't know what you're aiming to build.

Because I think it's not good to use your javascript in hook_form_alter() , that way, any form you try to see will invoke that javascript code.

However... Back to your issue,

I think the hook_form_alter() function should be used in the module_name.module file under the root of your module folder: modules/custom/module_name/module_name.module along side the routing, info, etc.

After building the .module file, you need to build the module_name.libraries.yml file (if it's not already built), and there, you write your routing requirements, example:

<route_name>:
  version: 1.x
  js:
    js/<your_javascript_file>.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

Backto the .module file, you implement the hook_form_alter, so your code goes like this:

/**
 * Implements hook_form_alter().
 */

function <module_name>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

    $form['#attached']['library'][] = '<module_name>/<route_name>';
    $form['#attached']['drupalSettings']['<module_name>']['<route_name>'] ['variable'] = 'value';

    return $form;

}

To make sure, console.log your PHP variable in your_javascript_file to see it, example:

(function($){
    console.log(drupalSettings.<module_name>.<route_name>.variable); // value
})(jQuery);

Hope this help!


I have run into an issue where dpm() and some other messages were eaten up by a 404 request in the background.

Explanation:

If dpm() or drupal_set_message() is called before the messages are printed out with theme_status_messages(), then you get to see them on the same page.

If dpm() or drupal_set_message() is called after theme_status_messages(), then those messages are delayed in $_SESSION until the next request that does theme_status_messages().

Some types of requests do NOT trigger theme_status_messages(). E.g. a form submit will only do the form processing, and then do a redirect, so the messages remain in the $_SESSION.

Also, it will only trigger on requests by the same visitor/client (this is why it is saved in session, which is client specific).

However, some requests that happen in the background do trigger theme_status_messages(), and can eat up your messages.

In my case this were requests to missing images, which resulted in full-blown html 404 pages WITH messages (and I did not get to see any of this, obviously).

Solution:

The solution was to activate the "fast 404" feature.

Change notice 1296384 explaining this newly introduced feature.
Drupal 7 default.settings.php you might want to copy some code from here.


How do I automatically assign a node to a term?

If it was me, I would add a term reference field to user, then when the user becomes "writer" and the related term was created I just added that term to user,

Then using rules, when the user creates a story, I would need to attach term to node, likely I have the term Id attached to user so it could be simply attached to node.

in this way no php code is needed.


As usual, there is a module for that! :) Check out Multi-Language Link and Redirect (MultiLink). It was a bit buggy when I was testing it 5 months ago so I didn't include it in my Drupal 7 Multilingual Sites book (well, it's referred to in the appendix, page 112), but it should be working by now. Have fun!


Update a field on a node after hitting save

Depending on your exact usage, you'd want to use either

1) hook_node_presave - Called on any node being saved (inserted or updated). see here

2) Attach a submit handler to the form: Allows to change the form's values before the submit is completed.


How to create a theme function for overriding Address Field theming?

Download & enable the Addressfield Tokens module (https://www.drupal.org/project/addressfield_tokens). This will provide additional tokens and theme functions for Addressfield.
Set the field in question to display using the "Address components" format.
Select all the fields you wish to display. Note that the separator does not matter, unless you choose to use it in your theme function.
Create a theme function named THEMENAME_addressfield_formatter__components, where THEMENAME is the name of your theme. Here is an example I created in my template.php to add microdata for XHTML+RDFa: https://gist.github.com/evandonovan/d47a3874e26151c4c07f6c20b7edc204. It is designed especially with the United States in mind, so may not work as well on other countries.
Clear the theme registry for your theme function to take effect. If you have Drush, you can use drush cc theme-registry. Otherwise, see https://www.drupal.org/node/173880#theme-registry for other means to clear.


Views & colorbox trigger, make the colorbox image adapt to screen size

The colorbox-trigger is normally only required when you want to display HTML in your colorbox. You are then required to set height and width as colorbox is not able to determine the dimensions of the HTML content before it is loaded.

If you want to display an image in a colorbox, there's no need to use the colorbox-trigger but instead just add the image field and use colorbox as image style. Within the field formatter settings of colorbox you can then define the image styles to be used for preview and inside the colorbox. If the colorbox image style exceeds the screen, colorbox will automatically resize the image to fit the screen/window.

In your case, you want to have the image displayed along with custom HTML captions. Thus, you need to define the colorbox content and then set height and width to 100%. The colorbox will then use up maximum available space. However, your image is still not diplayed at 100% width. To achieve that, you would need a quite large image to be displayed in the colorbox, eventually add a wrapper div to it and set a CSS rule like

div.wrapper img { max-width: 100%; }


Yes, as you guested unprocessed show the number of items that this module detected but couldn't import .


Theme takes different css file from /default/files/css when uploaded to remote server from local

The location "default/files/css" is used to store aggregated CSS files, created by Drupal Core. CSS/JS file aggregation can be enabled/disabled by navigating to Drupal Performance settings page, using "Admin => Configure => Development => Performance" and enabling checkbox "Aggregate CSS files". You can also delete the .css files from "default/files/css" directory and Drupal will automatically create new one whenever site is visited first time after that. Check the screenshot below:

It is not advisable on production, but if you want to use original files from Theme's CSS directory directly, then uncheck "Aggregate CSS files" setting checkbox and Try clearing cache.


This is not a straight-forward flag trim. Trim works on all content in the set of a content type, and I don't see how you can do it on a subset.

This answer uses Views bulk Operations, so please install that. I also assume the flag is global (or if not then only one user flags)

We will create a view that will get the list of images to unflag. Then we will create a rule component that will unflag the images, and lastly we will create a rule that will initiate all of this when an image is flagged.

Create a view that will fetch the images that belong to a certain gallery and that have been flagged.

To do that, create a view (master display only) on content (node), and filter on content type (image). Add three relationships:

Relationship 1: Add a relationship 'Flags: Node flag', include only flagged content, set the flag to the desired flag, and set it to 'Any User'. This will ensure that only flagged images show up.

Relationship 2: 'A bridge to the Content entity that is referenced via field_gallery'. This will bring in the referenced 'gallery'.

Relationship 3: This one may seem weird, but bear with me. Add 'A bridge to the Content entity that is referencing Content via field_gallery', and set its relationship to the previous one, ie 'Content entity referenced from field_gallery'. This links back to the image type. The reason for this will become apparent in the next step.

Add a contextual filter of 'Content nid' and set its relationship to the third relationship you added above, ie 'Content referencing Content from field_gallery'. We will pass in an image nid, get the associated gallery, and then get all the associated images belonging to that gallery that are flagged. So now we have our list that we will use in rules.

The last step is to add a new field (the only field we need). Add a field 'Bulk operations: Content'. Do not use a relationship. This will allow us to use the view with rules.

Finally, remove the pager as it is not needed.

Now we need to add a rule component and a rule.

Create a rule component.
Add a new rule component called 'Unflag Image'. It is of plugin type 'Rule'. Add two variables.

First variable: Data type -> node, Label -> previously flagged image, Machine name -> prev_image

Second variable: Data type -> node, Label -> newly flagged image, Machine name -> new_image

Now add a condition: Data comparison. Compare 'prev-image:nid' equal 'new-image:nid' and tick 'Negate'. This will check that the previously flagged image does not equal the newly flagged image.

Add an action: Unlag a node, and set the node to flag as 'prev-image'. Set user on whose behalf to flag as 'site:current-user', and select skip permission check: false.

Create a Rule.
Add a rule that has event: 'A node has been flagged' and select your flag.

There is no condition.

Add an action to the rule: Load a list of entity objects from a VBO View. For its value select the view that you added previously. For the argument select the flagged-node:nid. Leave the provide variables as is.

Add a loop, and select 'entity list' (the provided variable from previous step), and leave defaults for current list item.

Inside the loop, add an action: Component: Rule: Unflag image. This is the component we added earlier. For previously added image, select 'list-item' (provided variable of previous step), and for newly flagged image, select 'flagged node'.

And that is it. You should now debug it as I have not checked it, but the logic is more or less there and you can take it further.


Difference between field_data and field_revision tables?

That is correct: Working with Field SQL Storage.

  Database tables:

  {field_data_[field_name]} Standard data storage for a field.
  {field_revision_[field_name]} Standard revision storage for a field.


Print the main menu in overridden node page

If you want to render the menu for sitemap purpose, better to use the "Sitemap" module

Configuration page from this link

admin/config/search/sitemap

You can see the below screen on configuration page,

Just check the menu, which you want to display in sitemap.

After this you can access your page with /sitemap url and you can see your menu there on that page.


How to filter content in views based on user id

You can do it by using these modules:

If you want to give permissions to node then you can use this module

Node Access

  Nodeaccess is a Drupal access control module which provides view, edit
  and delete access to nodes. Users with the 'grant node permissions'
  permission will have a grant tab on node pages which allows them to
  grant access to that node by user or role. Administrators can set
  default access controls per content type, and also define which roles
  are available to grant permissions to on the node grants tab.

If you want to "assign" node to some user, you can use user reference field and then in view add filter for that field and make it filter by current user.

For user reference use this field

References

  There were a couple changes in the way 'References' views are handled
  ("referenceable nodes/users defined by a view"), which might require
  double-checking those existing on your site:

  The 'label' (node title or user name) is no longer automatically    added if not included in the view. If some of your 'References' views
  currently do not include it, you might want to add it explicitly,
  else it will no longer appear in the widgets.
  The HTML generated by the view is no longer stripped out before being    handed to "checkboxes / radios" widgets, thus allowing
  advanced    formatting. You might want to check for Reference views
  having fields    configured to display "as links", since the (probably
  unwanted)     tags generated by Views are not removed anymore.


Sure; these are called 'megamenus' or 'meganavs' and there is a module directly for this: the Megamenu module.

  Mega menus are a type of drop-down, which seeks to overcome some of the usability drawbacks to traditional style drop-downs. Primarily, mega menus have two advantages:

  The information architecture of your navigation is made clearer and is visible all at once
  The amount of clicking, searching, and navigating is reduced

  This module allows you to build mega menus by leveraging jQuery and the existing Drupal menu system. Megamenu takes a Drupal menu that is 3 levels deep, and converts it into a categorized 3-level mega menu, which is placed into your site as a block.

The 7.2-x branch allows "embeded blocks within mega menus"


How to embed plugin configuration form elements into another form?

I have solved this by making sure my forn had a unique element names to avoid collision with the Action's configuration. I have added a 'x_' prefix to names of all my elements. Since my form did not use #tree globally I have put the Action's configuration under a 'configruation' key and in form validation and submit callbacks I have provided this array as $form['configuration'] to the validation and submit handlers of the Action plugin instead of the whole $form array. So far it works withotu any issues.


Dump-dir specified in aliases.drushrc.php; not seen by drush?

FWIW, I finally resolved the error by including the --source-dump option in the command line. I specified the same directory I had listed in my aliases file, and it created the dump file there flawlessly. So perhaps dump-dir is not being read in 6.0-rc2...


What have i missed in my security constraints?

I looks like you're running an outdated version of Drupal (ver. 7.17) with many severe security issues including the one known as "Drupageddon" (fixed in ver. 7.32).

First, you must start reading up on the Drupal Security advisories, in particular SA-CORE-2014-005 - Drupal core - SQL injection, PSA-2014-003 and FAQ on SA-CORE-2014-005 - they will tell you what you've missed regarding Drupageddon. This flowchart is a great resource.

To get back the control over your site, you should simply delete it, and start recreating it from scratch on a different server, since the attacker may have a root kit on your present server.  Change the password of the db-user that Drupal uses, and the passwords of all privileged accounts. If you want to keep your content, roll it back from a backup created before Oct. 15 (you have backups, don't you?).

If you don't have backups, there are some tools (including a Drush command named Drupalgeddon) that may be use for forensics and part clean-up of an compromised site.  I do not recommend that you use these tools, as there is no guarantee that they'll able to find all infected areas on your site and web server. But they're the last resort, if scrapping the site and starting over is not an option.

You should also start reading up an all Drupal SAs.  Or even better, subscribe to them: Log in on Drupal.org, go to your user profile page and subscribe to the Drupal security newsletter on the Edit » My newsletters tab.

Contributed modules frequently have security flaws.  These are eventually fixed, but the fix also tells all the bad guys how to exploit unfixed sites.  That means that to keep your site secure, you must make sure you install security updates in a timely manner.  That's why subscribing to the security newsletter is so important.

Custom modules made by inexperienced programmers is a huge risk.  If you use custom modules, make sure you have their code reviewed by someone experienced in security.


How do you swap position of Order Total Components in Checkout Pane?

Do it in a custom module implementing hook_commerce_price_formatted_components_alter(). See commerce_price.api.php for parameter information.


Mini pager on View in a block does not work

If you want pagination to work as being a block display, you will have to set Use AJAX to Yes under Basic settings in your view edit page.

In the page display Pager work as it receives parameter as query string variable ?page=1.


Views listing of nodes and node title as exposed filter

Finally found a solution with Views Selective Filters. :)

By added a "Regions" field in my content type I've been able to get only the regions with results exposed as a filter in my views.


Redirect basic page to external url when visiting page

this is a cache problem. You need to set correctly the cache tags and context for the entity and it will work.
You need to do something like this to skip the cache:

  '#cache' => ['max-age' => 0],

you can find more info here: https://www.drupal.org/developing/api/8/cache/tags

Notes:

This needs to be put on hook_entity_view_alter() on the entity in your case the node, or if you want in just one field for which you want to set it. This is a work around for your redirect issue!
Try to add it to the $entity, if it doesn't work you need to replace the default '#cache' or you can add it to the $build array, this is case dependent.


is Form api ajax attribute good in performance ? does it require an entire bootsrap?

Whether or not the request method is AJAX has no bearing on whether a full bootstrap is performed - that's completely down to the behaviour of the path that's being requested. If your AJAX call requests '/js/my-page.js', and that menu path is somehow configured not to bootstrap fully, then you won't incur a bootstrap penalty.
To that end, I would highly recommend installing the High-performance JavaScript callback handler module.

JavaScript callback handler is an interim solution for high-performance server requests including (but not limited to) AHAH, AJAX, JSON, XML, etc.
This project targets module developers and provides a "bare bone" callback handler which is intended to be addressed by modules wanting to improve response times for specialized tasks.

It will allow you to define router items for which a full bootstrap will not run; in fact you can pick exactly which modules should be loaded, and which other files should be included, for your callback's requirements.
I've used it before with great success, and have seen very noticeable improvements when converting custom (and even core) AJAX callbacks to use this method. It's blindingly fast.
It also has integration with a bunch of other modules (SHS for example).
As to whether Drupal will be able to handle your project - that's not for us to say; have a look at the various options available (including this one), do some benchmarking and stress testing per your project/client-established requirements, and it'll become apparent whether or not Drupal will meet your needs.


I managed to do this in the following way:

function theme_get_page_children($nid) {
         $parentPath = 'node/'.$nid;
          $parentId = db_query("SELECT mlid FROM {menu_links} WHERE link_path ='".$parentPath."'");

      foreach($parentId as $pid){
         $finalID = $pid->mlid;
      }

        $getChildren = db_query("SELECT link_path FROM {menu_links} WHERE plid='".$finalID."' ORDER BY weight");

      foreach($getChildren as $child){
          $nodeID = str_replace('node/', '', $child->link_path);
          $children[]= $nodeID;
      }

        if(isset($children)){
             foreach($children as $nid){
                 $node = node_load($nid);
                 if($node->status ==1){ //check node is published
                      print render(node_view($node, $view_mode = 'teaser'));
                 }
            }
        }
    }

And on the template files where to call it:

innovista_get_page_children($node->nid)

I think using foreach to get $finalID was bad practice. I also think I should have used drupals menu API to call the child links instead of querying the database. So if anyone knows how to improve this in these ways, or tidy up the code in general then comment below :)


How to hide rating field when adding comment to own node?

You should use unset($form['field_stars']); instead of $form['field_stars']['#access'] = 0;

You can keep the fields as required and also remove the else condition.

So your final code would be something like this

function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_stuff_form") {
   if ($form['#node']->uid == $user->uid) {
      unset($form['field_stars']);
      }
    }
}


Remove all styling from views field view?

Yes, you have to override the templates of the child view to remove the markup you don't want.

You will might need to override (in order of how likely it is you need to override them in some way):

views-view.tpl.php
views-view-unformatted.tpl.php (if you are using the unformatted style. Otherwise whichever style template is relevant to your view)
views-view-fields.tpl.php

You need to find where the unwanted line is coming from in the markup/css and then find the template that markup is printed in, then override that template and remove the offending markup.

Alternatively you can likely style it out with css but I would favour the template override option.


programmatically save image to node with link in custom module

The file field will handle the display of the file regarding to its settings in the FieldUI.

So referencing the fid is sufficient:

$node1->field_top_banner['und'][0]['fid'] = $file_temp_top->fid;


Ultimate Cron. Invoke a cron from a cron. Set a cron enabled status to TRUE till its queue gets empty. Then set it to FALSE

Answering my own question.

In your .info file first define ultimate_cron as dependencies

dependencies[] = ultimate_cron

Next, in your .module use hook_cronapi() and define two cron attributes.

/**
 * Implements hook_cronapi().
 */
function mymodule_cronapi() {
  $items = array();
  // This launches at specified time once a day.
  $items['custom_cron_1'] = array(
    'title' => t('This will run once every day'),
    'scheduler' => array(
      'name' => 'crontab',
      'crontab' => array(
        'rules' => array('* 2 * * *'),
    ),
  );
  // Run only when invoked and until & unless condition is met so we are not left for tomorrow
  $items['custom_cron_2'] = array(
    'title' => t('Run when invoked'),
    'enabled' => FALSE,
    'scheduler' => array(
     'name' => 'crontab',
     'crontab' => array(
       'rules' => array('*/1 * * * *'),
     ),
  );
  return $items;
}

Next step is to define the cron job callback and here in first callback we will schedule to run second cron job.

function custom_cron_1() {
  $job = _ultimate_cron_job_load('custom_cron_2');
  // Enable the job.
  $job->enable();
}

Next we will define callback for second cron and continue this cron process each minute until condition is met.

function custom_cron_2($job) {
  // Check for condition.
  if(...) {
    $job->disable();
  }
  else {
    // Continue the process
  }
}


If not hook_init(), what can be used for cached pages?

I think you are asking the wrong question.

If a page is cached, it means that it got generated and cached at some point. At this point, your code in module_init() did run. If your code generated a redirect (via drupal_goto()), this redirect will get cached.

There should not be anything wrong with this scenario, so maybe you should just clear the cache once?


If you want to send private message with file, use Privatemsg module. It used to have issues with attachment privacy, but it is Closed (fixed) - should work for you.


self hosted video player/soution with fallback

You could probably use:

https://drupal.org/project/jwplayermodule

  Full support for JW Player for Flash and HTML5.
  Manage multiple custom players.
  Full skin and plugin support with easy to use plugin customization interface.
  A powerful shortcode system for customizations at embed time.
  CCK Field support.
  Integration with the popular FileField module.
  Integration with the Embedded Media Field module.


How to filter a view to show current month

in the view select filter type your dob field select apply then another popup opens in which you have to select "Date selection form element" as popup (Provided you have enabled the Date Popup module in Date API package) then "Filter granularity" by month select apply operator should be equal to and in front of that theirs a option select a date .. you have to select enter a relative date and in relative date type now.apply and save


creating a function that can create GET url variables as object when I need it

If these $_GET parameters are also route parameters (set up in a module's routing configuration), you can use

 \Drupal::routeMatch()->getParameters();

Or for a specific parameter:

$keyword = \Drupal::routeMatch()->getParameters()->get('keyword');

If the $_GET parameters are not route parameters, you can get all the parameters this way:

$params = \Drupal::request()->query->all();

If you want to set default parameters for parameters that aren't in the URL, you can merge the $params with an array of defaults.  Then depending on how you're going to use the parameters, you may want to XSS filter the params to prevent cross-site scripting attempts.  As @Berdir points out, this is rarely necessary, as twig auto escapes and if you are passing parameters into the query abstraction layer properly, it will also filter your input.  But you could filter your params this way:

foreach ($params as $key => $value) {
  if (!empty($value)) {
    $params[$key] = Xss::filter($value);
  }
}

(If you are using arrays in your $_GET params, this foreach loop would need to be altered to handle that use case.)

Here's some more info on XSS security.

After you have pulled-in and cleaned up your $_GET variables, you could then save these parameters to your object, and then use them conditionally in your query.

Since you asked specifically about Controllers, you can pass the request object to controller in the constructor:

  public function __construct(Request $request) {
    $this->request = $request;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack')->getCurrentRequest()
    );
  }

Then you could use the request object from the container.

If you set up the parameters as route parameters, you can just pass them in as arguments to the controller.


Multiple Image Upload and Rename - avoiding multiupload image field

Plupload has a variety of upload widgets that should allow you to upload without increasing the php limit. You can view examples of the widgets here. You can pick one of the [modules that integrate pulpload on its project page at https://www.drupal.org/project/plupload.


Override the template for that specific field and don't print the label.

field--field-thing.html.twig

{% if multiple %}

    {% for item in items %}

{{ item.content }}

    {% endfor %}

{% else %}
  {% for item in items %}

{{ item.content }}

  {% endfor %}
{% endif %}

Alternatively, you can preprocess the field and remove the label/change the display, but personally I would do it in the templates so later on the label could easily be added back in.


Do contrib modules have to be set to expose settings variables to Strongarm?

Looking at strongarm_vars_load I can see that it loads all variables in the variables table using ctools_export_load_object regardless of any special consideration (other than variables already controlled via strongarm in features).

When I've used it in the past I've never had to specifically define the variables for strongarm to use.


How to pre-populate the username field on the login page when clicking an e-mail link?

You can do it using Prepopulate module. You haven't mentioned the version you are working with. It's in dev version for D7.

When you configure the email, use token in the same format given in the example to pass value of their username, which will be prepopulated when they click on your sent link.


Bulk opening of several node edit screens

As far as I am aware, no module will do this out of the box. However in saying that there is a potential solution in:

Installing Views Bulk Operations (VBO)
Writing a custom action that happens on each selected node

From the VBO page:

How can I write an action that performs a function on all selected nodes AT ONCE?

You need to write a node operation instead of an action. Whereas actions get called once for every selected node, node operations are called once only, and they are passed an array of selected nodes. Check out sirkitree's article for the same concept applied to user operations.
Note: If you use Batch API to execute your actions, VBO will revert to calling the action once per node instead. This is because it doesn't make sense to batch one single action.


Check to make sure you have at least one field listed under 'Fields.'  If you use a display type that requires fields without any being selected you will see the error noted in your question.

If it's bugging out, try to cancel your changes and refresh the page.  Add a field, save and see if the preview works again.


entity_metadata_wrapper - how to remove one item from entity reference field

Use unset instead, followed by a save:

unset($wrapper->field_foobar[$delta]);
$wrapper->save();

To find the delta, you can iterate over the collection and look for the node id:

foreach($wrapper->field_foobar as $delta => $item)  {
  if ($item->nid->value() == $my_id) {
    unset($wrapper->field_foobar[$delta]);
    $wrapper->save();
    break;
  }
}


How to display a field of the parent store in my module?

Sounds fun, Here is an option to do this.

1) make a controller :
routingfile:

my_module.store_terms:
  path: '/store-terms/{store_id}'
  defaults:
    _controller: '\Drupal\my_module\Controller\StoreTermsController::showTerms'
    _title: 'Terms'
  requirements:
    _permission: 'access content'

In the controller:

use Drupal\Core\Ajax\AjaxResponse;

use Drupal\Core\Ajax\OpenModalDialogCommand;

public function showTerms($store_id) {
  $store = \Drupal::entityTypeManager()->getStorage('commerce_store')->load($store_id);

  $terms = $store->field_terms_and_condition->value;

  $render_array = [
    '#markup' => $terms
  ];
  $response = new AjaxResponse();
  // Show a dialog box.
  $dialogText = $render_array;
  $dialogText['#attached']['library'][] = 'core/drupal.dialog.ajax';
  $response->addCommand(new OpenModalDialogCommand('Terms and Conditions',
   $dialogText, ['width' => '500']));
  return $response;
}

then back in your  buildPaneForm method:

$attributes = [
  'attributes' => [
    'class' => 'use-ajax',
    ],
];
$link = Link::fromTextAndUrl(
  t('terms and conditions of the store "@store_name"', ['@store_name' =>
   $store_name]),
  Url::fromUri("internal:/store-terms/".$store_id , $attributes)
  )->toString();


Try this...

function jh_preprocess_html(&$vars) {
$vars['classes_array'][] = theme_get_setting('bg_style');
}

You need to do this at an earlier stage of the processing.


View only content created by that particular user

Follow below steps to resolve the issue !

Enable Content Access Module
Clear Cache
Go to Edit Content Types, and Select Access Control
Set Access Control As shown below. Remove checkbox view any article content for anonymous and authenticated users.
Save Settings
Go to "admin/reports/status/rebuild" and rebuild permissions
Create a Content of content type that you set access permissions.
Logout and Login as another normal user and check for access.

Let us know if still fails :-)


How to add taxonomy term reference field in a custom drupal form

For Drupal 7, the code is something like this, where field_tags is a taxonomy field in the node with widget type autocomplete.

<?php
   $node=node_load($nid);
    $tags = array();
    foreach ($node->field_tags['und'] as $item) {
      $tags[$item['tid']] = isset($item['taxonomy_term']) ?  $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
    }
    $form['tags'] = array(
      '#type' => 'textfield',
      '#default_value' => taxonomy_implode_tags($tags),
      '#title' => 'Add Tags',
      '#autocomplete_path' => 'taxonomy/autocomplete/field_tags',
      '#maxlength' => 1024,
      '#element_validate' => array('taxonomy_autocomplete_validate')
    );
?>


how to change the background image based on the node (the hard way)

The simplest (not necessarily the cleanest) way to do this is:

function mytheme_preprocess_page(&$vars) {
  $node = menu_get_object();
  if ($node->nid) {
    // We're on a node page
    if (isset($node->field_background_image[$node->language][0]['fid'])) {
      // Load the file object
      $file = file_load($node->field_background_image[$node->language][0]['fid']);

      // Get a web accessible URL for the image
      $path = file_create_url($file->uri);

      // Add the background to an inline CSS tag
      drupal_add_css('body { background:url(' . $path . ') left top no-repeat !important; }', 'inline');
    }
  }
}


How can I create two distinct sets of exposed filters for use in a single view?

It looks like what you are describing is faceted search. In Drupal, a good solution for faceted search is using Apache Solr along with the Apache Solr module. Here's a video tutorial on how to install Solr for Drupal. Here you can see an example of faceted search working on a site I built for the company I currently work for.


How to create a link from node view and pass information to a webform

I don't think webform link field can be used to accomplish this as the purpose of Link custom attributes (YAML) is for HTML TAG attributes like

target: _blank

You can use field_token_value to create a field on the node that has tokens as input. Install and enable the module and then add a token field.

The value of this field would be an HTML link with query parameters added (nodetitle in this example) you can browser for all available tokens under field value.

Then on the webform side you have to enable query parameter to populate fields by going to the settings of the webform > form > form behaviours > prepopulate > Allow all elements to be populated using query string parameters.

And then on the field to display the query parameter include the appropriate token.  Here adding the nodetitle to the subject field default value.

For token field to be populated a node needs to be saved.


Is it a bad idea for a view to specify nodes by node id?

It really depends what the View is for to be honest.

Is the node ID ever likely to change?  Is it something that can't be done with entity view modes instead?

I've had a couple of occasions where I'm filtering a View on a specific node ID, but it's mainly because it's a use case that doesn't really require the massive overhead of something like Display Suite (and I don't use Panels - for no other reason that I don't really like the markup it produces).

If the node ID is GUARANTEED to stay the same, then it might not be disastrous.  However if the node ID is ever likely to change (through content migration for example) then it WILL break.  It also means that the client won't be able to fix it themselves unless you show them how to use Views and give them access to the Views UI.


How to search the body of text by content type?

There is a search field called something like "Search: Search terms" which you can add as a filter criteria. Just expose it so the user can enter a search phrase.

Works only for indexed content, so make sure your index is at 100%.


How to add active class to a specific menu only, while ignoring other menus?

Try the  following modules

1)Menu Position

  Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)

  This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

I've used Menu Position module for one of my project and it works great!

OR

2) Menu Trail By Path

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

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

  blog

  blog/category1

  blog/category1/article1


Create content in chinese language in drupal 7?

See how to install a language on Drupal.org.  After installing and enabling Chinese as a language, you will be able to specify that a node is a Chinese language node when creating/editing it.

There is no risk of data corruption, but in order to avoid problems, never change the default language (as quoted from the documentation).


Rule to fire only on first time publish of node

This is how I would try doing it:

create a field for the content type named first_publish, boolean, hidden, default value 0
create a Rule that when that content type is published, as a condition if first_publish is 0, first_publish becomes 1, add email output to user
create a second Rule that when the content type is published, as a condition if first_publish is 1, send out a different email

This will use a data field as a variable that follows the node - the rules will trigger appropriately depending on the conditions of whether or not the variable is set, giving different outcomes.


Commerce Price Table: What would cause sporadic zeroing of prices when adding to cart?

Obviously, something is wrong somewhere when the rules are firing to apply pricing. Read up on debugging rules and you'll likely find your problem.

One thing you may want to consider is just writing your own custom logic and then creating a new rule to call your custom logic, bypassing the logic of Commerce Price Table. You'll likely need to really spend your time adding your logic to commerce_price_table_get_amount_qty since that's where the actual field and price get determined.


Flag a node but create a view of the nodes that reference it

You may use Entity View Attachement module. This module attaches a view to an object. this object may be a node, user , ...  . Select the appropriate bundle and it works well


how to add a redirection after password change without modifying Drupal Core?

You can add your own submit handler to the form using hook_form_alter, and set your redirect here.

Ex:

<?php
function my_module_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'user_profile_form')
  {
    $form['#submit'][] = 'my_module_profile_form_submit';
  }
}

function my_module_profile_form_submit($form, &$form_state)
{
  $form_state['redirect'] = 'some/path';
}
?>


Sorting view results by the number of matched arguments (contextual filters)

Following is one way to achieve the specified ordering

Add a relationship to taxonomy terms.

Turn on aggregation
Set the sort criteria to COUNT DISTINCT of taxonomy term reference field.


Enable/Disable field values based on another field's value

I doubt whether it is possible. You cannot hide certain radio options in a radio group. It is the whole group or nothing. I will look rather at a custom jQuery solution coupled with a server-side validation method.

The jQuery will have to:
display all hidden radio options in destination, then hide the corresponding radio option in the destination when source is selected. You will have to add the jQuery to the page via  hook_preprocess_html or something similar, or use the module JavaScript Libraries Manager.

Server-Side:
You can use the Field validation module. Put the validation against both fields, and use 'Equal values on multiple fields', and set it to reverse.


How can I set page specific user view access by user role?

First of all, you can install nodeaccess module and then configure it. It works for specific pages to restrict based on user access.


Drupal form creating method without using a module

As the comments and the other answer says, there are several possibilities:

A contributed module such as Webform.
Someone with very bad habits hard-coded that form inside templates, other modules or even Drupal core.
A block/node could contain that form, specially if the PHP-filter is enabled. Even with the HTML filter enabled (and submitting the form to another page).

If you see some custom text, or the name of the fields are unique or rare, you could try to search inside Drupal root directory for them:

grep -r 'Custom text' /var/www/drupal

phpMyAdmin includes a functionality to search across an entire database. If you feel desperate, try to search inside the Drupal database for the text you see in the form.

Examining the outputted HTML code could help. You will see if the form has an ID, for example.


uc_quote is a part of the main Ubercart module. You can find it in the directory structure of ubercart at ubercart/shipping/uc_quote. And it is obviously present for Drupal 7 (as part of Ubercart 3.1).
For commerce shipping there is a sandbox project, but I haven't tested it.


How to collect and display visit statistics for a Views page?

Have a look at the Visitors module. Here are some reports you get from it:

  View pages that have recently been visited.
  View pages that have been hit frequently.
  View pages count per month, day of month, day of week, hour.
  ...

Especially these reports should be what you're looking for (it includes hits for paths corresponding to a view):

Top pages (table with columns Title, Path and nr of Hits).
Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor).

Checkout the above (source) links to get an idea of which data are available.

Extra reporting features can be enabled via these sub-modules:

The Visitors GeoIP module, to also report about countries and cities.
The Visitors Browscap module, providing statistics on visiting browsers.

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module.


My question got answered on drupal.org:

  Posted by marcingy on August 16, 2013 at 7:03pm:

    This is mirroring how core storage works. fields_current.node contains the data for the current revision. There is a collection per entity type which is the smallest division in core in terms of storage.

I guess I will have to build in the flexibility myself :-)


Module update manually multiple versions at once

You can replace it with the latest version and run update.php. Drupal modules keep track of what version data schema it's on; update.php will apply the needed DB updates since 7.x-3.5.


I had added the weight and dimension fields to the existing products using defaults. I needed to save each product for these to take effect. Works now.


Dynamic processing of string field based on user IP

Store the data in the cleanest way possible and then use something like Custom Formatters
or a custom module to modify the presentation of the stored data.

As for using $_SERVER['REMOTE_ADDR'] I feel that I need more data on how and where this will be used.  Have you considered using the permissions or roles built into Drupal?

You would likely need to place this in a preprocess function to conditionally call it for a specific IP address.

For example.

/**
 * Implements hook_preprocess_node().
 */
function hook_preprocess_node(&$variables) {
    //Obviously a real IP is required above for correct syntax.
    if ($_SERVER['REMOTE_ADDR'] == xxx.xxx.xxx.xxx) {
        //Next you can edit the output of any field you want if your remote address matches.
        $variables['field_myfield'][LANGUAGE_NONE][0]['value'] = 'Something Modified Here';
    }
}


Is there a way to generate thumbnails within Drupal?

First, create an image style from the Drupal UI, or by implementing hook_image_default_styles in a custom module. An image style contains the resizing and cropping rules for your thumbnail. After that, you can use theme_image_style to create the html output for an image using the thumbnail style. Do not call theme_ functions directly though; call it like this: theme('image_style', ... ). The thumbnail will automatically be created in a non-destructive way when it is first requested.


Hook to run code after a rule has been executed

You can make that "specific task" as an action to a rule using hook_rules_action_info and add that action for the rules which you want to exectue.


Entity creation-form: Prepopulate all existing entity-references of a field collection

You will need to create a custom module that alters the node creation form before it rendered using hook_form_FORM_ID_alter().

You want to edit the form_state which stores the information on how a form is filled out.

It should look something like this:

<?php

/**
 * Module to prepopulate season price list with rooms
 */

/**
 * Implements hook_form_FORM_ID_alter(&$form, &$form_state)
 */

function mymodule_form_seasonal_prices_node_form_alter(&$form, &$form_state){

    // Load all of the room node ids into an array
    $node_type = "room";
    $result = db_query("SELECT nid FROM node WHERE type = '%s' ", $node_type);
    $nids = array();
  while ($obj = db_fetch_object($result)) {
    $nids[] = $obj->nid;
  }

  // Set the form state to include each room
  foreach($nids as $nid){
    $form_state->field_collection_you_want_to_edit[] = $nid
  }
}

You will need to do a bit of sleuthing to figure out what to put in the last line as it is specific to your build, and I don't know whether you need to set it to the $nid or node_load($nid) or something else.  But this should give you a framework to go on with.

If you haven't come across the Devel module yet, install it, and use dpm($form_State); to look at the structure of the variable so that you know what to change.

Finally, make sure you change the name of the function from 'mymodule' to whatever name you have given your module, make sure the machine names for your content types and form ids are correct (I just guessed them), and clear the cache so that Drupal picks up the hook.


Computed Twig solution not showing in preview?

I figured it out. You need to create a "Preview Page" as per Computed Twig example.

webform 5.x has an inbuilt preview page which does not recalculate when viewed.


Pre-populate webform default values with hook_form_alter

I found the values here

$form['#node']->webform['components']

So for the first component, I would change the value like so

$form['#node']->webform['components'][1]['value'] = 'test';


Editing canonical links without a module, contained in $head?

You need the Meta Tags module.

After you activate it, go to /admin/config/search/metatags/config/global and, under advanced, you can change the default canonical link.

Look at the path patterns used for PathAuto and prefix them with the desired base url.


Difference in form when first loaded and submitted

If all you want to know is whether the form is being loaded before or after a submit while debugging, then look at the array in $form_state['input']. If it is an empty array, then it is being loaded for the first time (before a submit). If it has elements then the form is being loaded after a submit.

If you want to see if field values have been changed in a submit, then how you do it depends on where or why you need to check. If debugging, then compare $form_state['input'][FIELD] with $form[FIELD]['#default_value']

You can also add your own functions as submit or validate handlers to the form. After the form is submitted, your function will be called, and you can compare the changed values in $form_state['values'][FIELD] (note: use values here, not input) to the original values in $form[FIELD]['#default_value'].

You add your submit/validate handler by implementing hook_form_FORMID_alter()for the form you are debugging, and adding the names of your functions to the end of the $form['#submit'] and $form['#validate'] arrays respectively. Remember to clear caches.

function my_module_form_other_module_form_alter(&$form, &$form_state) {
  $form['#submit'][] = 'my_module_custom_submit';
  $form['#validate'][] = 'my_module_custom_validate';
}

function my_module_custom_submit($form, &$form_state) {
  $original_field_x_value = $form['field_x']['#default_value'];
  $submitted_field_x_value = $form_state['values']['field_x'];
  if ($submitted_field_x_value != $original_field_x_value) {
    do_something();
  }
}

function my_module_custom_validate($form, &$form_state) {
  do_something();
}


Case difference of Usernames; how to login with Usernames regardless of case in Drupal 7

There are no modules that I know of at this time that provides this functionality.  It can be done, however, by writing a custom module.

I suggest that you look at LoginToboggan as a model for how to write your own module.  The basic flow is this:

LoginToboggan allows users to log in using either their username or email address.  Drupal, by default, does not support logging in with an email address, so LT does a hook_form_alter() to add a function to the login form's #validate.
The Validate function, logintoboggan_user_login_validate() searches for an email address that matches the one provided by the user.  If it is found, then LT provides the username to the form programmatically.
Because the username is provided during the #validate step, the form flow continues and processes the username which was retrieved by LT, and the user is logged in.

Your solution would follow a very similar flow, but instead of checking for an email address, you would check against username.  The LT function uses a LOWER() SQL function to recognize differences in capitalization in the email; you will do the same, except with usernames.

One addition that you may have to make is that, if you allow users to register themselves on your site and pick their own usernames, you may need to ensure that the selected username does not collide with a capitalized version (e.g, Drupal may allow a username mrawesome and MrAwesome because they are different, but you should disallow the latter because they are viewed as equivalents within the confines of your system).


How to theme a view that displays content from a relationship?

With Show: Field, each individual field can be toggled to any of the relationships in the view. It is similar to Show: Content and Show: Rendered Entity except the dropdown list is buried one step further down.

Switch to Show: Field, and edit each field and set the dropdown list to the Featured Person relationship. Then, go about your theming just as you would with any other fields template.


Drupal 7 Views - Date Filter Cannot See Year

To anyone who may be curious, I discovered the issue that was causing the year not to show. @75thTrombone put me on the right track.

After digging through the date popup module, I found that the views filter defaults to the Short date type format, which for my site had been set to M j (e.g. Jan 28). Once I added the year back to the Short date type format, the filter worked as expected.

It may be possible to configure which date type is used in the views filter, but I did not see a way to do that. The date popup module is using variable_get('date_format_short', 'm/d/Y - H:i'). I will also update the module and see if that allows for a custom configuration.


Bypass publish approval on content creation for a certain role

You could user Rules to publish or unpublish content based on a role or any other condition.


Adding different containers to different parts of content from a node

The Field Group module will allow you to group fields into containers you may then be able to alter some of the mark up with the Fences module.

It does sound like you need more control so if those modules don't work you'll have to get your hands dirty in some code. The template files node.tpl.php and field.tpl.php should give you all the control you need over the mark up.


Get translated field value with fallback

Drupal 8 does not have built in field-level language fallbacks. That feature was removed in favor entity level language fallbacks since that is the common case. Usually an entity is translated as a while (or not) and it removes a huge amount of complexity, especially in views or so.

If you have a specific field where you want to apply this, then you need to implement that yourself. You can check if an entity-level translation exists with $node->hasTranslation('en') and if so, get it with $translation = $node->getTranslation('de') ($translation is still a node object, it's a clone of the original one with a different active language). Then check if you have a value and repeat until find one.

Something like this:

$value = NULL;
$language_manager = \Drupal::languageManager();
$current_langcode = $language_manager->getLanguage(Drupal\Core\Language\LanguageInterface::TYPE_CONTENT);
foreach ($language_manager->getFallbackCandidates(['langcode' => $language_manager->getLanguage(]) as $langcode) {
  if ($node->hasTranslation($langcode) && !$node->getTranslation($langcode)->field_my_awesome_field->isEmpty()) {
    $value = $node->getTranslation($langcode)->field_my_awesome_field->value;
    break;
  }
}


Entity fields are in their own separate table(s), they don't get attached to the base entity table.

You can use an EntityFieldQuery to get that data:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_display_name', 'value', 'bubba');

$results = $query->execute();
if (!empty($results['user'])) {
  $users = user_load_multiple(array_keys($results['user']));
}

See Where does Drupal 7 store custom user account fields? for a bit more info


The problem was hook_views_pre_render, for some reason the markup is already render at this stage (weird..),  when I used the same code in hook_views_post_execute it worked perfectly.


How to pass a value validated in Webform to the User's profile page?

Using the "Webform Rules" module, you should be able to have the Rules module react on an event like "Webform submitted". So create a custom rule using this Rules Event, and then add the required Rules Actions. Here is a blueprint of these Rules Actions:

Fetch Entity by id, of type user, using the uid of the user who submitted the form (= current user).
Set a data value, for the field of the user's profile where you want to save that birthday, where the value is the birthday entered in the form.
Possibly (not 100% sure) you may also want to add Save entity, to actually save that field in the profile.

Make it right before you make it better ...

But what about a user submitting the same form again, with a different value for birthday? If you don't want that to happen, you might want to add the Flag module like so:

Flag a user after submitting the form (using Rules), using some global flag.
Improve the 1st rule above, to add a Rules Condition to verify that the user has not been flagged yet.

PS: This answer applies to D7 ...


How to remove mymodule configurations on uninstall

The easiest way is to ensure that the config has a dependency on your module.

dependencies:
  module:
    - yourmodule
  enforced:
    module:
      - yourmodule

Then Drupal will automatically remove that configuration and also warn in the UI that it will be removed.

Note that this only works for new installations, it won't fix existing ones.

An alternative is to put the configuration in config/optional instead of config/install, then it will only be created if it doesn't exist yet and the dependencies are met.


Webform Submission Using Rest API POST method

Looking at the examples on the Webform REST project page, you should be using something like…

{
  "webform_id": "my_webform",
  "checkboxes_field": [
    "Option 3",
    "Option 5"
   ],
   "integer_field": 3,
   "radio_field": "Mail",
   "email": "myemail@mydomain.com.au"
}


Ok found it, the migrate module have a custom Mail Class that blocked all emails send during migration process.

The migrate Mail Class is

  MigrateMailIgnore

To bypass that migrate mail class you can simply do that :

public function complete($entity, stdClass $row) {

    // some stuff here

    // Bypass migrate MigrateMailIgnore Class
    global $conf;

    $conf['mail_system']['default-system'] = 'MyOwnMailClass';

    // Operation.
    $op = 'register_admin_created';

    // Send an email.
    _user_mail_notify($op, $user);
  }


Check out Context.

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

  Think of conditions as a set of rules that are checked during page
  load to see what context is active. Any reactions that are associated
  with active contexts are then fired.


How to attach Dropzone.js uploads to a form element

I now have the files under $_FILES['files'].

My JS code:

(function ($) {

    Drupal.behaviors.dz = {
        attach: function (context, settings) {
            Dropzone.options.picsForm = {
                paramName: "files",
                autoProcessQueue: false,
                uploadMultiple: true,
                parallelUploads: 100,
                maxFiles: 100,

                init: function() {
                    var dz = this;
                    // #edit-next is the id of my submit button
                    this.element.querySelector("#edit-next").addEventListener("click", function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        dz.processQueue();
                    });

                }
            };

        }
      }

})(jQuery);

The '$form_field_name' parameter is a numeric index now, so I just get the count of the $_FILES['names'] array and call file_save_upload() for each one.


FACETS : Add "Apply" button that will apply all filters in one query

i have created an issue on the facet module and the situation is :

Not soon in the drupal 8 version. This would be a big refactor of the way queries are built right now.

https://www.drupal.org/project/facets/issues/3013702


Debugging with var_dump -> where does the output go?

Usually the var_dump() works but gets hidden below the theme. This is because theme rendering comes last.

I could go into it more, but basically just install Devel and use dpm() for your variable dumps. It prints them in a Drupal-style message. You'll love it.


Views Calc always uses contextual filters of master display

As temporary solution :
I've deleted all contextual filters in the Master display and overrided them in other displays

But then i patched Views Cals module.

Views calc realy always executes "filter criterias" and "contextual filters" from default display.
So before executing view we must set view in a needed display. It's very important!
Here is the patch for it:

http://drupal.org/node/1868900#comment-7026538


Drush @sites alias does not work in a multisite installation

I just tested this on HEAD of today's master branch of drush, and drush @sites status worked fine for me with no sites/default folder.  Try upgrading to drush 7.0-alpha9.