Display user picture in User Relationship block

$view = new view();
$view->name = 'user_freinds';
$view->description = 'Shows someone\'s related users';
$view->tag = '';
$view->base_table = 'user_relationships';
$view->human_name = 'User freinds';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'mini';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['style_plugin'] = 'grid';
$handler->display->display_options['style_options']['grouping'] = '';
$handler->display->display_options['style_options']['columns'] = '5';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
  'name_1' => 'name_1',
);
$handler->display->display_options['row_options']['separator'] = ', ';
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['area']['id'] = 'area';
$handler->display->display_options['empty']['area']['table'] = 'views';
$handler->display->display_options['empty']['area']['field'] = 'area';
$handler->display->display_options['empty']['area']['empty'] = TRUE;
$handler->display->display_options['empty']['area']['content'] = 'لا يوجد محتوى';
$handler->display->display_options['empty']['area']['format'] = 'plain_text';
/* Relationship: User relationships: Requestee user */
$handler->display->display_options['relationships']['requestee_id']['id'] = 'requestee_id';
$handler->display->display_options['relationships']['requestee_id']['table'] = 'user_relationships';
$handler->display->display_options['relationships']['requestee_id']['field'] = 'requestee_id';
/* Relationship: User relationships: Requester user */
$handler->display->display_options['relationships']['requester_id']['id'] = 'requester_id';
$handler->display->display_options['relationships']['requester_id']['table'] = 'user_relationships';
$handler->display->display_options['relationships']['requester_id']['field'] = 'requester_id';
/* Relationship: User relationships: RTID */
$handler->display->display_options['relationships']['rtid']['id'] = 'rtid';
$handler->display->display_options['relationships']['rtid']['table'] = 'user_relationships';
$handler->display->display_options['relationships']['rtid']['field'] = 'rtid';
/* Field: User relationship types: Plural name */
$handler->display->display_options['fields']['plural_name']['id'] = 'plural_name';
$handler->display->display_options['fields']['plural_name']['table'] = 'user_relationship_types';
$handler->display->display_options['fields']['plural_name']['field'] = 'plural_name';
$handler->display->display_options['fields']['plural_name']['relationship'] = 'rtid';
$handler->display->display_options['fields']['plural_name']['label'] = '';
$handler->display->display_options['fields']['plural_name']['exclude'] = TRUE;
/* Field: User: Picture */
$handler->display->display_options['fields']['picture']['id'] = 'picture';
$handler->display->display_options['fields']['picture']['table'] = 'users';
$handler->display->display_options['fields']['picture']['field'] = 'picture';
$handler->display->display_options['fields']['picture']['relationship'] = 'requestee_id';
$handler->display->display_options['fields']['picture']['label'] = '';
$handler->display->display_options['fields']['picture']['element_label_colon'] = FALSE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'requestee_id';
$handler->display->display_options['fields']['name']['label'] = '';
/* Sort criterion: User relationship types: Plural name */
$handler->display->display_options['sorts']['plural_name']['id'] = 'plural_name';
$handler->display->display_options['sorts']['plural_name']['table'] = 'user_relationship_types';
$handler->display->display_options['sorts']['plural_name']['field'] = 'plural_name';
$handler->display->display_options['sorts']['plural_name']['relationship'] = 'rtid';
/* Contextual filter: User relationships: Requester user */
$handler->display->display_options['arguments']['requester_id']['id'] = 'requester_id';
$handler->display->display_options['arguments']['requester_id']['table'] = 'user_relationships';
$handler->display->display_options['arguments']['requester_id']['field'] = 'requester_id';
$handler->display->display_options['arguments']['requester_id']['default_action'] = 'default';
$handler->display->display_options['arguments']['requester_id']['exception']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['requester_id']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['requester_id']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['requester_id']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['requester_id']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['requester_id']['validate']['type'] = 'numeric';
$handler->display->display_options['filter_groups']['groups'] = array(
  1 => 'AND',
  2 => 'AND',
);
/* Filter criterion: User relationships: Relationship status */
$handler->display->display_options['filters']['approved']['id'] = 'approved';
$handler->display->display_options['filters']['approved']['table'] = 'user_relationships';
$handler->display->display_options['filters']['approved']['field'] = 'approved';
$handler->display->display_options['filters']['approved']['value'] = '1';
$handler->display->display_options['filters']['approved']['group'] = 1;
$handler->display->display_options['filters']['approved']['expose']['operator'] = FALSE;

/* Display: Block by type */
$handler = $view->new_display('block', 'Block by type', 'block_1');
$handler->display->display_options['defaults']['use_ajax'] = FALSE;
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['block_description'] = 'Display user\'s relationships grouped by relationship type';

/* Display: Block by user */
$handler = $view->new_display('block', 'Block by user', 'block_2');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Related users';
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['style_options']['grouping'] = 'name';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: User relationship types: Plural name */
$handler->display->display_options['fields']['plural_name']['id'] = 'plural_name';
$handler->display->display_options['fields']['plural_name']['table'] = 'user_relationship_types';
$handler->display->display_options['fields']['plural_name']['field'] = 'plural_name';
$handler->display->display_options['fields']['plural_name']['relationship'] = 'rtid';
$handler->display->display_options['fields']['plural_name']['label'] = '';
$handler->display->display_options['fields']['plural_name']['exclude'] = TRUE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'requestee_id';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
/* Field: Broken/missing handler */
$handler->display->display_options['fields']['updated_at']['id'] = 'updated_at';
$handler->display->display_options['fields']['updated_at']['table'] = 'user_relationships';
$handler->display->display_options['fields']['updated_at']['field'] = 'updated_at';
$handler->display->display_options['fields']['updated_at']['label'] = 'Added';
$handler->display->display_options['fields']['updated_at']['exclude'] = TRUE;
/* Field: User relationship types: Name */
$handler->display->display_options['fields']['name_1']['id'] = 'name_1';
$handler->display->display_options['fields']['name_1']['table'] = 'user_relationship_types';
$handler->display->display_options['fields']['name_1']['field'] = 'name';
$handler->display->display_options['fields']['name_1']['relationship'] = 'rtid';
$handler->display->display_options['fields']['name_1']['label'] = '';
$handler->display->display_options['block_description'] = 'Display user\'s relationships grouped by user';


How do I define a separate form template for a multistep form?

I have fixed the issue using D8 temp storage functionality. I was able to get the current step in my form_alter() hook, and I stored it in to a temp variable and accessed it in theme_hook_suggestions() hook().

/**
 * Implements hook_form_alter().
 */
function custom_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if($form_id == 'mywebform_id') {

    $current_page = $form_state->get('current_page');

    $tempstore = \Drupal::service('user.private_tempstore')->get('custom_module');
    $tempstore->set('current_page', $current_page);
  }
}

function custom_module_theme_suggestions_webform(array $variables) {
  $tempstore = \Drupal::service('user.private_tempstore')->get('custom_module');
  $current_page = $tempstore->get('current_page');

  $suggestions = array();

  $suggestions[] = 'webform__'.$current_page;

  return $suggestions;
}


Take a look at this issue:

keys of fulltext searches must be encoded as phrases for terms parse mode

A quick read indicates that you might be able to just escape the spaces, e.g foo\ bar.

Also see the view settings image in comment #10 of that issue.


Use Rules to notify original author when their node is published

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. In your case, either something unexpected happens in your Rules Conditions, or there is some error in your Rules Action.

There are some typical facilities to do such debugging (further detailed below), but a Keep-It-Super-Simple technique I often use, is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

If the above doesn't help, then there are typically 2 ways of more advanced debugging, as further detailed below.

Rules Evaluation Log

Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

More info

For way more details about these 2 variations, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


field_group: the save button is now in the wrong place

You can change the weight of the Save / preview buttons, and place them at the bottom with form alter.

Weight is used to sort the list of form elements before being output; lower numbers appear before higher numbers.

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  // Only change actions container (submit, preview, cancel buttons) weight
  // on node edit forms.
  if (!empty($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE) {
    $form['actions']['#weight'] = 100;
  }
}


How to get all field name of field type?

You are looking for EntityFieldManager::getFieldMapByFieldType():

\Drupal::service('entity_field.manager')->getFieldMapByFieldType('image');


You don't have to specify a suggestion for the front page, it is already one.

The only thing you have to do is create page--front.tpl.php and clear your cache.

See the list of template suggestions.

Then if it doesn't work then something else in your setup is interfering somehow but we don't know much about your site so it's hard to debug from there.


How can I gracefully interrupt an AJAX callback?

That's not directly possible. There is no API in the browser to manually cancel a sent request. All you can do is to register a callback to know when the HTTP response is received, or at least when the browser changes the state on the xmlHttpRequest object. Drupal's AJAX code already handles that for you. The error message you're seeing is shown because another request was sent which did interrupt the background request, but that still looked as if it was completed (readyState == 4). Drupal considers completely empty responses to be an error and the message is shown.

The most common and user friendly approach I've seen is indeed to disable the submit button(s) while a request is in progress. That in combination with a "spinner" animation or progressbar is a good indication that the user should keep waiting and that they will benefit from it. When the request completes (failed or successful), the buttons are unlocked again.

An input field can become unfocused at any time and for different reasons (maybe the user just wants to copy/paste something into it really quick). Triggering a long running background request whenever that happens could quickly become annoying. As you've already noticed, it interferes with the normal form submit flow as well. Maybe you can work around that and trigger the requests by some other means which more clearly indicate to the user that they need to wait for it to complete? Perhaps giving them the choice to initiate the request when they're sure to be done with manual input into the field and are more inclined to wait for automated processing of their input. Or perhaps trigger the request after a short timer which gets stopped when the field is refocused or the form is submitted.

If not, you could try overriding Drupal's AJAX response interpreting code so it won't show that message if the submit button interrupts the background request, first setting some flag to indicate AJAX errors are to be ignored. Whether this works also depends on how important it is that the AJAX operation on your field completed. If it performs some kind of correction on the [email address?] the user entered, they get it wrong, but the correcting routine didn't get a chance to update the field with valid input, this probably means your serverside validation fails and the user needs to submit it again - which could have been avoided if they had waited for the request to complete.


How to load modal form on page load using ctools?

This post I wrote a while back deals with CTools AJAX events at any time. It involves writing your own Javascript handler and executing it on page load.

    Drupal.CTools.AJAX.refreshElements = function() {
  var url = '/mymodule/ajax/refresh-elements';

  try {
    $.ajax({
      type: "POST",
      url: url,
      data: { 'js': 1, 'ctools_ajax': 1},
      global: true,
      success: Drupal.CTools.AJAX.respond,
      error: function(xhr) {
        Drupal.CTools.AJAX.handleErrors(xhr, url);
      },
      complete: function() {
      },
      dataType: 'json'
    });
  }
  catch (err) {
    alert('An error occurred while attempting to process ' + url);
    return false;
  }

  return false;
};
$(document).ready(Drupal.CTools.AJAX.refreshElements);

Set the URL to the callback URL of your module.  The last line tells the ajax to happen on page load but this could be replaced to happen in response to the exact event you need it to.


Referencing an existing image in theme settings

I haven't been able to find an example of this, either, but here's a simple demo setting a reference to a media/image in theme settings (with the autocomplete widget):

use Drupal\Core\Form\FormStateInterface;

function THEME_form_system_theme_settings_alter(&$form, FormStateInterface &$form_state, $form_id = NULL) {
  // Work-around for a core bug affecting admin themes. See issue #943212.
  if (isset($form_id)) {
    return;
  }

  $opts = [
    '#type'          => 'entity_autocomplete',
    '#title'         => t("Call to Action Background"),
    '#description'   => t("Default call to action background media image; may be overridden on individual elements."),
    '#target_type'   => 'media',
    '#selection_settings' => ['target_bundles' => ['image']],
  ];
  if ($default_id = theme_get_setting('call_to_action_background')) {
    // element stores an int ID, but default value has to be the loaded entity
    $image = \Drupal::entityTypeManager()->getStorage('media')->load($default_id);
    $opts['#default_value'] = $image;
  }
  $form['call_to_action_background'] = $opts;

}

To retrieve and render, use a THEME_preprocess hook with parameter &$variables:

$media_id = theme_get_setting('call_to_action_background');
$media = \Drupal::entityTypeManager()->getStorage('media')->load($media_id);
$variables['media_build'] = \Drupal::entityTypeManager()->getViewBuilder('media')->view($media, 'some_media_display_mode');

The render array is then available in twig:

{{ media_build }}


Anyone any good reference about the variables available in the view template?

What I usually do when I need to inspect a views variable, that often can be as complex as you describe is to use dpm. Dpm can't always show all of the items since the information is repeated. But then you can dpm the specific parts you need.

So you often start doing dpm($view); but end up using dpm($view->displays...); to get what you need. Using a reference might be a bit overkill since the view varisble is dymanic, but after doing it a while you start figuring out where you can find stuff. The names is pretty selfexplanatory.


how to add to html.twig from a node twig file?

You're going about it the wrong way, you cannot affect other Twig template files, it needs to be done way before you get to Twig. Everything you want to can be done using the Metatag module:

Supports a large number of commonly used meta tags, including the page title, canonical URL, description, etc, and for Facebook's Open Graph, Twitter Cards and Dublin Core via included submodules (see full list)


How to track users site use in a webform / contact form?

This is more or less the feature of the Google Analytics Contact Form, Webform, Rules Email module.

  This module will instantly append Google Analytics information to the bottom of the Contact Form, WebForm, and Rules emails.

The mail would look something like:


Exist a product discount in Drupal Commerce

If the goal is: "the site administrator can create simple discounts for products".
You can add another field like "discount percentage" . By default would be set as 100 % (or 0% of discount).
Then, with rules, you check if this fields have another value than 100, and recalculates the price.


How to overwrite a file upload so that the filename is always the same?

This would save always save the latest upload to public://importcsv/avenue.csv:

public function submitForm(array &$form, FormStateInterface $form_state) {

  /* Fetch the array of the file stored temporarily in database */
  $csv_file = $form_state->getValue('import_csv');

  /* Load the object of the file by it's fid */
  $file = File::load($csv_file[0]);

  $file_real_path = \Drupal::service('file_system')->realpath($csv_file->getFileUri());
  $file_contents = file_get_contents($file_real_path);
  file_unmanaged_save_data($file_contents, 'public://importcsv/avenue.csv', FILE_EXISTS_REPLACE);

  drupal_set_message('File Uploaded Successfully');
}


How to change the date format for date entity field

You can usually only change the output of a date field, as it is easier to convert an existing date to something else.
The input is often standardised to make sure the system understands the input.

In order to change the output, create a new date format admin/config/regional/date-time/formats and enable it on admin/config/regional/date-time.
Then you can use it as a display for the field on the display tab.


Commerce Kickstart: How do I fix a SQL error on string length after using Features Override to save customizations?

Great news! Kind of.

After looking at the database more (using the Database Admin module), I found that the "info" column is a BLOB. A BLOB has a max char length of 65,000.

Given the number of changes I made to the default settings, my Feature Override complete set of Feature Overrides well exceeded the 65,000 characters allotted. I opted to split the Feature Overrides into individual packets, grouped by type (variable / facetapi / user). This appears to have done the job. Fairly straightforward after better understanding the db setup and limitations there.

In terms of avoiding extensive overrides, I suspect that I created this snag by starting out with the demo store implemented in Commerce Kickstart. That option seemed like a good plan for me at the time because it provided some basic features already setup. I adapted those for what I need, but it may not be a particularly good foundation from which to grow the site. Any feedback there?


"Term reference" for two language versions

is this a Drupal 7 or Drupal 8 question ?

in Drupal 7 you can use i18n_taxonomy submodule of i18n module.


Problem creating redirect from page with %20

If you are using the Redirect module it has an admin page for fixing 404 errors with redirects. Your file should be listed there since it gives you a 404 error.

When clicked on "Add redirect" action link, your old link will be pre-populated on the next page for you to create a redirect.

That should fix the redirect issue.

In case it doesn't try replacing white-space with + (plus) character. In the URLs + can be used instead of white-spaces.


You can use the link function and the route for the login page (user.login), e.g.

{{ link('Login', 'route:user.login') }}


How can I select a user role at the time of the account registration?

Good day,

Have you tried the Select registration roles module? I think this would be a straightforward configuration for the role field that you want.

Hope everything is in order.

Thanks!


If your hook implementation is definitely being fired then it does seem likely that another module (or even a theme, potentially) is overriding your changes.

To ensure your module's implementation runs last, you can implement hook_module_implements_alter():

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

If that isn't the problem, it might be something simpler...if your code is copied verbatim then you're setting the title twice for the same path. You might have meant

$items['node/%node/view']['title'] = t('View Event');

Or it might even be a combination of both of those.


Select an image from a list to an image field

You can try "IMCE for File Field" module for this: https://www.drupal.org/project/imce_filefield

It depends on IMCE module. Gives the option to select a file from the predefined location instead of uploading.


How do I load a field of a product in a custom module?

Have you tried?

$product->get('field_discount')->entity


Assigning a page title to forms created with the form API FAPI

if your page url http://site.com/my_page

you can use

function hook_page_alter(&$page)
{

    if(arg(0)=="my_page")
    {
                 drupal_set_title("Ahmed");
    }
}


"broken/missing" means that Views can't find the field. If you hover over the "broken/missing" link you can look at the address and get a hint of which field it's supposed to be. Once you know which field it is you can remove the broken handler and re-add it to the views output. If it's not available something has gone wrong with the field migration (I assume you did migrate the fields).


reseting the hook_update_n status of a module

FYI, in Drupal 8, the system table has been removed, and this information is now stored in the key_value table.

UPDATE key_value SET value='i:8000;' WHERE collection = 'system.schema' AND name = 'module_name';

(As noted above, the actual value should be less than the hook_update_N() you want to repeat, but higher than or matching the last update that does not need to be repeated.)


Since the latter uses hal_json, you need to do it like this
curl --request GET --user myusername:mypassword --header 'Accept: application/hal+json' \
http://example.com/node/2?_format=hal_json

For more info, see Using other authentication protocols.


You could always add "List" field type to your custom content type. By default you could choose between lists of Text, Integer and Float. While configuring you could choose whether or not it will be checkboxes, radio buttons or select lists.
Later in Views you could filter content with use of these fields.

It's in Drupal core, no additional modules (except of Views of course)


How to Redirect search form to search api views

try this function:

/**
* Implementation of hook_form_alter()
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'search_block_form') {
    $form['#submit'][] = 'mymodule_form_submit';
  }
}

/**
 * Process a block search form submission.
 */
function mymodule_form_submit($form, &$form_state) {
  // The search form relies on control of the redirect destination for its
  // functionality, so we override any static destination set in the request,
  // for example by drupal_access_denied() or drupal_not_found()
  // (see http://drupal.org/node/292565).
  if (isset($_GET['destination'])) {
    unset($_GET['destination']);
  }

  // Check to see if the form was submitted empty.
  // If it is empty, display an error message.
  // (This method is used instead of setting #required to TRUE for this field
  // because that results in a confusing error message.  It would say a plain
  // "field is required" because the search keywords field has no title.
  // The error message would also complain about a missing #title field.)
  if ($form_state['values']['search_block_form'] == '') {
    form_set_error('keys', t('Please enter some keywords.'));
  }

  $form_id = $form['form_id']['#value'];
  $form_state['redirect'] = 'search/mymodule/'. trim($form_state['values'][$form_id]);
  }
  else {
    form_set_error(NULL, t('Search is currently disabled.'), 'error');
  }
}


You need to implement hook_form_alter() and duplicate the Save button.

Something like this should work:

function yourmodule_form_user_profile_form_alter(&$form, &$form_state) {
  // Copy the existing submit button into the account fieldset.
  $form['account']['submit'] = $form['actions']['submit'];
  // Give it a high weight to have it show below the other fields.
  $form['account']['submit']['#weight'] = 50;
}

However, I suggest you also look for ways to shorten your form, maybe through theming or by using http://drupal.org/project/field_group.


How do I manage collaborative development on a Drupal site?

It is a workflow change but you should get used to working on a fresh dump of the live DB. There are three ways to get changes into the DB.

Features. This won't work for everything but will for a lot of things you need.
update hooks. When features won't work you can hard code things into an update hook of a module you own.
Manual changes. Use sparingly. Some things don't come naturally to features or update hooks and are just much easier to do manually. This is a last resort but sometimes is the only piratical way.

If you can. Several times a day get a fresh dump and test your build, you should have less integration problems.


Translate site name in multi language site

I found it .

1 ) Install "Configuration Translation" module.

2 ) Go to "Basic site setting" ( admin/config/system/site-information )

3 ) Click "Translate system information" tab.

4 ) In front of your language click on "Add" button.

5 ) Then set your site name and click on "save translate" .


Suppress watchdog a specific log message

There is no special hook for this. The easiest way to fix this in Drupal 8 is overriding logger.dblog service.

According to the official documentation you need implement a class extending ServiceProviderBase and the alter() method as shown below.

<?php

namespace Drupal\example;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the logger.dblog service.
 */
class ExampleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides logger.dblog service to exclude some unwanted log messages.
    $container->getDefinition('logger.dblog')
      ->setClass('Drupal\example\Logger\DbLog');
  }

}

The logger itself is extremely simple.

<?php

namespace Drupal\example\Logger;

use Drupal\dblog\Logger\DbLog as BaseDbLog;

/**
 * Logs events in the watchdog database table.
 */
class DbLog extends BaseDbLog {

  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = array()) {
    if ($message != t('Cron run completed.')) {
      parent::log($level, $message, $context);
    }
  }

}


Short answers -

Drupal 6: Use Signup

Drupal 7: Use Entity Registrations

Both of these modules do pretty much exactly what you want on both counts.


Send push notifications by limit per user

A simple way to do this is to add a user field. This field will keep track of the number of push notifications sent and will increment every time you send a new push notification to the user.

In your rule, add a condition that checks the value of the field and execute the actions if value <= 4.
Then, in the action part of the rule, increment the value of the field by one.


Rules: How to send an email when an OG membership field changes its value?

I believe the answer lies in your Conditions.

You are checking whether the current user has the appropriate role.

See if you can find a token for the user whose membership has been changed.


Duplicate / Triplicate inline javascript

The problem ended up being the module Panelizer.  I was using the Default view and should have been using the Full Page Override view.


Drupal 6 - Get 5 newest nodes of a certain type


You could use Crumbs module.
Now, if you say these nodes are "associated", I wonder how exactly? With an Entity reference field? Or just that you know the parent? Is this for all nodes of this type, or just for this specific one? Are these nodes somewhere in a menu?

If you can arrange either of the criteria above, you can use existing Crumbs plugins. Otherwise, you could do a custom module..


@Berdir
Applying patch #14 on this page has solved the problem!
Thank you very much!

Twig template variables containing result of Drupal::url() and Drupal:l:() don't bubble up their cacheability and attachment metadata (e.g. token placeholder)


Consider using the Markdown Filter. It not only solves your problem, but gives a more intuitive input option.

If your users are used to using Markdown on StackOverflow, then they will love it ;)
In fact, StackOverflow was one of the first sites to integrate the Markdown format.


Comment notify options confusing for users

As discussed in the comments: no, you haven't got a configuration issue, and yes the module is working exactly as designed.

If your users are likely to find that confusing, you can use hook_form_alter() in a custom module/theme to change the text to something that makes more sense. Or even hide one or more of the options altogether, if that's what you need.


limit access to private files uploaded by webform to specific role

By default, users with the 'access all webform results' permission can view all webform private files.

If, for some reason you need them to be able to access the files but not the webform results, you could implement hook_file_download() - you could base your implementation on webform_file_download() in webform.module


When to use Views vs. a hardcoded query?

As posted in the issue thread he's asking about caching, which Views can give you -- or as @Chapabu mentions one could cobble together yourself.

1 thing Views does give you is an ability to Alter query or presentation of results relatively easily with hook_views_pre_execute or hook_views_query_alter to tweak the standard module to make it more customizable.

I could see some merits going this route. You could also supply the default listing as a default View provided by the module. Allowing other modules to copy/override it later in code ...


custom module to display content (nodes and fields) from another database

Absolutely you can use a different db for a view. First create a custom module use hook_views_data() in a .views.inc file to define the fields of the external db. Once you have defined the fields and cleared the cache you will be able to select a different base table for your view.

With some custom coding and db_set_active() or views relationships you should be able to use both.

EDIT: Assuming Drupal 7.


Can you dynamically request a (cached &) scaled image via imagecache in css?

The URLs imagecache produces are pretty reliable, and contain the name of the preset. Looking at the code in imagecache_create_url() you could build up a path in your CSS that looks something like this:

/sites/default/files/imagecache/preset-name/path/to/image.jpg

Assuming that your files are stored at /sites/default/files


Two random blocks displaying different fields from the same node

Define helper function like _random_node_id() which stores generated id in the static variable.
Use this function as an argument in the view.

This function will return a random node id, but called twice on the same page it would return the same id (because it is static).


What are the significant differences between the Sharethis, Addthis, and Service Links modules?

There is some detailed information on each of these, and others, over at Comparison of Social Network connectors/Sharing modules.  It would be best to add any new information to that wiki page so that we have something that's always up-to-date.


The answer was simple, $user is the user logged in. As my logged in user didn't have a profile image, all I kept seeing was the default. Unfortunately, elsewhere on the page I am not using $user but just $field_*, so it looked like I was using the right variable. This fixed it:

<?php $account = $elements['#account'];?>

And then updated $user to $account.

<?php $to_render = field_view_field('user', $account, 'field_image', array('settings' => array('image_style' => 'header_image_160x160'))); print render($to_render);?>

You cannot believe how much time and searching I did to fix this, and it turned out I was looking at the wrong variable the whole time.

Thank you,
Paul.


Creating a block with installation profile

I think that's not the correct way of creating the block as it won't fire the required api call for block creation and later on will cause issue.

Delta: This is a unique identifier for the block within the module. Delta values only need to be unique and is used in following purposes:

Passed into the other block hooks in your module as an argument to identify the block being configured or viewed.
Used to construct the default HTML ID of "block-MODULE-DELTA" applied to each block when it is rendered. This ID may then be used for CSS styling or JavaScript programming.
Used to define a theming template suggestion of block_MODULE_DELTA, for advanced theming possibilities.

Module: Name of module creating that block. E.g: If you are creating the block from custom module than it will take the value of that module name.

To programatically create the block, you need to use hook_block_info(), hook_block_view() in your custom module something like below:

/**
 * Implements hook_block_info().
 */
function MyModule_block_info() {
  $blocks['test1'] = array(
    'info' => t('Block info 1'),
  );
  $blocks['test'] = array(
    'info' => t('Block info 2'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function MyModule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'test1':
      $block['content'] = 'Required content 1';
      break;

    case 'test2':
      $block['content'] = 'Required content  2';
      break;
  }

  return $block;
}


Updating entities/posting data via ajax?

The AJAX callback URL will be a route you define in a module. The route will call a controller, which can optionally return an AjaxResponse. First define the route.

example.routing.yml:

example.ajax_callback:
  path: '/example/ajax'
  defaults:
    _controller: '\Drupal\example\Controller\AjaxController::ajaxCallback'
  requirements:
    _permission: 'some permission'

The path to set in your $.ajax() call is set above.

Then create the controller:

example/src/Controller/AjaxController.php:

namespace Drupal\example\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Controller\ControllerBase;

class AjaxController extends ControllerBase {

  public function ajaxCallback($nid, $key, $value) {
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
    $node->set($key, $value);

    return new AjaxResponse(['success' => TRUE]);
  }
}


You need to implement hook_preprocess_HOOK(&$variables), and add processing there, like this:

<?php

function MYTHEME_preprocess_node(&$variables) {
    // Check if field tid (term id) is filled up
    if (isset($variables->field_term_color[LANGUAGE_NONE][0]['tid'])) {
        $color = $variables->field_term_color[LANGUAGE_NONE][0]['tid'];

        $text = '';
        // You need to look up tid of each color
      switch ($color) {
        case 123:
            $text = 'Red is the color of fire.'
            break;
      }

      // Assign value to markup (text) node field
      $variables->field_markup_field[LANGUAGE_NONE][0]['value'] = $text;
    }
}

?>

You should place the right field names instead of the ones I use, of course.


You need to define a new URL by using hook_menu.

There, 'type' is set as MENU_LOCAL_TASK and URL is like 'node/%node/CUSTOM_CONFIG'.

Code snippet from the hook_menu in node.module:

 $items['node/%node/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'node_page_edit',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('update', 1),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'node.pages.inc',
  );


How do call the template for a module block

The markup render #type takes a string for its #markup element property, not a render array. However you do not need to wrap your custom theme/template with the markup type.

  public function build() {
    return array(
      '#theme' => 'scadfashblock',
      '#source_text' => $this->siteContent(),
    );
  }

  public function siteContent() {
    return some_function_returning_html_from_user();
  }

Then implement scadfashblock in hook_theme, provide a template_preprocess_scadfashblock and a templates/scadfashblock.html.twig with your markup.


Using db_query() or db_select() to connect to multiple databases

If the settings.php file defines the information to connect to the other database as $databases['extra']['default'], then you can use the following code, which is possible because SelectQuery::join() accepts also another SelectQuery object as $table argument.

$subquery = Database::getConnection('default', 'extra')->select('emplist', 'b');
$query = db_select('empidmaster', 'a');
$query->join($subquery, 'b', 'b.empid = a.empid');
$query->addField('a', 'empid');
$query->addField('b', 'empname');

A better code would be similar to the following one. In this case the alias used for the table used for the subquery is the one returned from SelectQuery::join().

$subquery = Database::getConnection('default', 'extra')->select('emplist', 'b');
$query = db_select('empidmaster', 'a');
$alias = $query->join($subquery, 'b', '%alias.empid = a.empid');
$query->addField('a', 'empid');
$query->addField($alias, 'empname');

SelectQuery::join(), and SelectQuery::addField() don't return the $query object; that is the reason you cannot the following code.

$query = db_select('empidmaster', 'a')
  ->join($subquery, 'b', 'b.empid = a.empid')
  ->addField('a', 'empid')
  ->addField('b', 'empname');

PHP would return an error about a method not being called on an object. In fact, SelectQuery::join() and SelectQuery::addField() return a string: the alias for the table, or the field.


Anonymous users can't see new content type in feed

There are multiple possible problems. First of, dealing with unpublished content - assuming you created a content type with unpublished option as default, you will have to make sure that you tick the publish option on save/ create of new items. As per default registered and anonymous users can't see unpublished content.

Going further there could also be a problem inside of your view. You can manage access for the view itself in the middle column of the views ui edit page. There might also be a filter to only show published / published or admin items only.

also make sure that anonymous user can see content at all: /admin/people/permissions


Code Adding Additional Node Reference to Existing Node

Found a solution, which was replacing this line:

 $node->field_video['und'][0]['target_id'] = $node_id;

With:

 $new = array('target_id' => $node_id);
 $node->field_video['und'][0] = $new;


You're approaching this correctly in trying to add this in your own info file - not every jQuery library needs its own Drupal module and its often more overhead than its worth to try and set one up. If the jQuery tools module is what you need but its not compatible with the current version of Drupal 7, than use jQuery Update module to upgrade your version of jQuery.

If all you need is the overlay and you're not tied to the jQuery Tools implementation, you have a couple of customized Drupal options that should be easy to implement:

The built-in overlay functionality in Drupal 7.x core (see https://drupal.org/node/1087026 for guidance on how to implement)
Use one of the specialized overlay libraries - best one I've found is Colorbox, which has a Drupal module with easy to implement solutions (i.e. no hand-coding javascript)


You can just get the element like this:

$variables['elements']['#id']

And then if you would of some reason need to load the block you can do like this:

$block = entity_load('block', $variables['elements']['#id']);
$block_id = $block->id;


How to unzip or uncompress a file .epub on Drupal?

PHP already has a built in class to process zip files. You can combine that with a hook_node_presave invocation in a custom module to process the field containing your ePub file and extract it to a directory in your file system.

/**
 * Implements hook_node_presave().
 */
function MYMODULE_node_presave($node) {
  if(isset($node->field_MYFIELD[LANGUAGE_NONE][0]['fid'])) {
    $file = file_load($node->field_sss[LANGUAGE_NONE][0]['fid']);
    $file_path = drupal_realpath($file->uri);
    $file_name = pathinfo($file_path, PATHINFO_FILENAME);
    $zip = new ZipArchive;
    if ($zip->open($file_path)) {
      $zip->extractTo(drupal_realpath("public://MYMODULE_customdir/$file_name"));
      $zip->close();
    }
  }
}


Fire Autocomplete after input reaches 4 characters

Check this answer : https://drupal.stackexchange.com/a/143720/30200

In short, you can defined a custom jquery event and associated it to your form_item. This event would fire only after a certain number of character


Outdated documentation is one of the reasons why Simplenews is only in Alpha. Sorry you had a frustrating experience, but a lot of work of porting modules and writing documentation is done in (my) free time. It is one of the many contrib modules that I help maintain.

You're more than welcome to help improving the module and documention so the next person will be able to figure this out faster. Patches or simply  by writing documentation on drupal.org.

The template extension is now .html.twig, which you should quickly see in the templates folder of the module.

Also, the very first paragraph on the project page contains this:

  Simplenews publishes and sends newsletters to lists of subscribers.
  Both anonymous and authenticated users can opt-in to different mailing
  lists. HTML email can be sent by adding Mime Mail module for D7 and
  Swiftmailer for D8.

Swiftmailer requires a composer dependency and is a bit more complicated to install due to that, but it is what we've been using in our projects and should work well.

Also, make sure you enable HTML in the newsletter settings. And possibly try the latest dev versions if you have problems.


Allow Anonymous user to Subscribe while site under maintenance mode

Maintenance mode is not really for this.

I would recommend using a custom theme for "Coming soon".   That way you can have them come to a home page with information and sign up/register for the site.

When you're ready to put the real site up, change themes.


Countdown timer for schedule unpublish date

You could add the snippet below as a new module scheduler_unpublish_countdown. It defines a block which you can shown on the node page of any content type you choose and allow it to countdown to the scheduled unpublish time for that node. As the block that comes with the jquery_countdown module counts down to a global event; this might be better for your use case.

<?php

/**
 * Implements hook_block_info().
 */
function scheduler_unpublish_countdown_block_info() {
  return array(
    'unpublish_countdown' => array(
      'info' => t('Scheduler Unpublish Countdown'),
      'cache' => DRUPAL_NO_CACHE
    )
  );
}

/**
 * Implements hook_block_view().
 */
function scheduler_unpublish_countdown_block_view($delta) {
  if ($delta == 'unpublish_countdown') {
    $node = menu_get_object();
    // Ignore non-node pages, already unpublished nodes, nodes that don't have a
    // date/time set for unpublishing and nodes whose unpublishing date-time is in the past.
    if (!$node ||
      empty($node->status) ||
      empty($node->scheduler['unpublish_on']) ||
      ($node->scheduler['unpublish_on'] <= REQUEST_TIME)) {
      return;
    }
    $variables = array(
      'id' => drupal_html_id('jquery_countdown-' . $delta),
      'options' => array(
        'until' => date("F d, Y g:i a", $node->scheduler['unpublish_on']),
        'description' => ' ', // So that the CSS doesn't get screwed
        // Reload the page when the countdown is done
        'onExpiry' => '(function() { location.reload(); })',
      )
    );
    return array(
      'subject' => t('Scheduled unpublish in..'),
      'content' => theme('jquery_countdown', $variables)
    );
  }
}

Once the countdown is complete, the page will simply reload (see onExpiry option above). As unpublishing happens only either during the normal Drupal cron run or through the Scheduler's own light-weight variant, it may not happen exactly at the time of unpublishing meaning the page would reload and nothing would happen (except for the timer not showing up anymore) which might be slightly awkward.

I'd recommend, therefore, to redirect to a custom page once the countdown expires where you explicitly call _scheduler_unpublish() and then redirect back to the node page. You might want to send a one-time-only token along for security.

Remember to add scheduler and jquery_countdown as dependencies for your new module.


You can do this with theme_menu_link().

A menu item's description is by default output as a tooltip (ie, in the title attribute).  Here's a thread that shows how to do take advantage of that using hook_menu_link() to achieve more or less the result you want.


hook_form_alter is a drupal API function. You can google "hook_form_alter" and the 1st result will be the API documentation for this function; it includes examples.

Using this "hook" function you can inject, or otherwise change, any form in your drupal website. A "form" is an HTML construct that can send data to a webserver via either POST or GET.

So, you can create a custom drupal Module (which consist of in this case an .info file and a .module file). In your  module you can create a function that implements "hook_form_alter" and adds in the zendesk field.

A simple simple example of this would be:

# in the below examples lets assume you have named your module folder as "zext" (kinda short for zendesk extensions .... i dunno :P

# in zext.info
name = Custom Zendesk Form Extensions
descrption = We want to add custom fields to the zendesk form.
package = Other
core = 7.x

# in zext.module
<?php

/**
 * Implements hook_form_alter().
 *
 * Alter the zendesk form and add a custom color text field.
 */
function zext_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'zendesk_form') {
    $form['zendesk_favorite_color'] = array(
      '#type' => 'textfield',
      '#title' => t('Favorite Color'),
      '#description' => t('Please tell us what your favorite color is!'),
      '#weight' => 99,
    );
  }
}

# that is all the code that would be in the 2 files.

With the above 2 small pieces of code we have modified the default zendesk_form (I assume its $form_id is zendesk_form ... it may be different examine the module's code to see how it IDs the forms ...) and added 1 single new custom field to allow the visitor to submit their favorite color. Drupal doesn't store these values anywhere -- they are just passed onto Zendesk upon form submission; You simply need to create the folder + 2 files and install the module in the drupal administration. Your module folder should be called zext.

There is alot of documentation online for creating modules, and using hook_form_alter. Look on drupal.org and Google.

Happy Coding!


How to allow multiple values in a single value textfield

There is a patch for this for anyone else looking for a solution.
https://www.drupal.org/project/views_conditional/issues/2690167


Configuring views to display book pages as teasers, in the correct order

In the sort criteria use:

Book: Weight (asc)

If you take the weight of the parent then all childs will return the same value.

To avoid confusion a Views example to import is added at the bottom. It presumes that:

the top parent node is NOT of the type 'book'
all  child pages are of the type 'book', also sub-childs.

Do not forget to:

'create a new book' in Book outline for the top page (even if it is not of the type 'book')
enable the block 'View: Child page teasers', probably in the 'content' area.

You can try at admin/structure/views/import the example below on your site or with https://simplytest.me/project/views (after deploy enable the Views UI and Book module):

$view = new view();
$view->name = 'child_page_teasers';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Child page teasers';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Child page teasers';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Relationship: Book: Parent */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'book_parent';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Book: Weight */
$handler->display->display_options['sorts']['weight']['id'] = 'weight';
$handler->display->display_options['sorts']['weight']['table'] = 'book_menu_links';
$handler->display->display_options['sorts']['weight']['field'] = 'weight';
/* Sort criterion: Content: Title */
$handler->display->display_options['sorts']['title']['id'] = 'title';
$handler->display->display_options['sorts']['title']['table'] = 'node';
$handler->display->display_options['sorts']['title']['field'] = 'title';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['nid']['specify_validation'] = TRUE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'book' => 'book',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');


Set default frontpage to Front Page view

you need to set it here:

http://www.DOMAIN.com/admin/config/system/site-information

You set the "Default Front Page Link" there.

When you hit your root (/) url, it will not "redirect" to that custom url you set, but it will auto render the url you inputted.

If you want to do a true redirect when hitting the frontpage you might have to do it via the .htaccess file as I'm not sure if there is module that can do a redirect from the frontpage.


Display taxonomy term description within the content page

You can do this with the display suite module. Install and enable the ds module. Then you will have a new 'Rendered taxonomy term' formatter. Go to the 'manage display' option for the content type you created. Just select the 'Rendered Taxonomy Term' for the format for your taxonomy field and you will get the description displayed.


How can I download files from public folder?

I think just giving a link to the file itself will download the file. In case of an image or PDF file, won't opening the file in new tab from where they can download suffice for you?

Regards,
Supriya Rajgopal


You can metatags from fields on the node with

hook_preprocess_html

e.g

/**
 * Implements hook_preprocess_html
 */
function THEME_preprocess_html(&$variables){
  // Only add on node pages
  if($node = menu_get_object('node')){
    // Read node fields, wrapper requires entity api module
    $wrapper = entity_metadata_wrapper('node', $node);
    if(isset($wrapper->field_some_field)){
      if($some_content = $wrapper->field_some_field->value()){
        $element = array(
          '#tag' => 'html_tag',
          '#type' => 'meta',
          '#attributes' => array(
            'name' => 'some-metatag',
            'content' => $some_content,
          ),
        );
        drupal_add_html_head($element, 'some_metatag');
      }
    }
  }
}


How can I reduce the file sizes of the original versions of uploaded image files?

Interesting question - this should be a standard option on community distributions to avoid the space issue you raised but you're right that the focus seems to be on image styles as a solution..

Two ways to handle this

More custom way would be to add a hook_form_alter to your form that would add a submit handler to resize the image file after uploaded to the correct size -- if you are able to do image styles than your server already has the image libraries needed to do this.
An easier way would be to use an uploader that can be configured to do this work for you on the upload. One example is the plupload module / widget which has a clientside resize option during the upload (also saving bandwidth)

resize

Enables plupload to resize the images to clientside to the
specified width, height and quality. Set this to an object with those
parameters.


Using Drupal 5 Gmap + location. What's the Drupal 7 equivalent?

I found this blog post which looks promising: Placing Users on a Map in Drupal 7 - with Openlayers, Addressfield and Geocoding

It says to use a combination of:
Addressfield
Geofield
Geocode
Openlayers

Except geocode doesn't seem to have an official 7 release

UPDATE

I successfully got this working, using this blog post as a foundation.  The article is talking about adding map data to user profiles.  In my case, I wanted to add map data to content nodes so I didn't need the Profile stuff. I used the following modules (and their dependencies):

Address Field  7.x-1.0-beta2
Geofield   7.x-1.0-beta2
Geocoder   7.x-1.x-dev
OpenLayers   7.x-2.x-dev

Yes, some of these are dev modules which is not ideal, but it seemed unavoidable to get the functionality I wanted.

In the article he talks about using his own fork of the Geocode module, but I found using the Geocoder (note the "er" ending) module (as suggested by the geofield module) instead worked fine.

Overview

In a nutshell this solution uses Address field to hold the address data and geofield to hold the coordinate data and OpenLayers to display the map.  The geocoder module is the glue between the address data and the empty geofield, taking the address data and populating the geofield.  The OpenLayers module uses the geofield coordinates to display the map.

Steps

I created a "Map" in OpenLayers which is basically like a preset of how you want the map to look and behave (e.g, map type, zoom level, etc).  This takes some tweaking to get things setup the way you want them.

Then I added a content type xyz.  In that content type I clicked "Manage Fields" and added an address field (Postal address).  Then I added a Geofield, and in the widget drop down I chose "Geocode from another field".  In the settings for the field I was able to choose the Address field I created earlier as the source.

Then in the "Manage Display" section of my xyz content type, for my geofield I chose "OpenLayers" from the Format drop down list.  And in the configuration of that field I chose the OpenLayers map type I had created earlier.

One thing I'm not crazy about is with the OpenLayers module; I can't seem to get the normal Google Maps pan and zoom controls and instead get some somewhat funky looking pan/zoom controls.

UPDATE

Apparently you can customize the pan and zoom controls using any images you like via css.  This blog post discusses it at the end: Take Control of Your Maps


Getting image URL and rewrite results for Views Module

Views does reject having style attributes to any of the html elements even though the style attribute is explicitly included in rewrite results of any field in the view.

The reason and workaround maybe found here: Rewrite results strips some html attribute

My recommendation is, you can write tpl for that particular field and use the output text (which will be the url in your case) to build the div or any html element around it.


This will select the next free ID:

$next_free_id = db_query("SELECT MAX(field_name) + 1 FROM table_name")->fetchField();


dump(), kint() & print_r() are not working in .theme file

Just include Kint debugger in your theme file:

require_once('modules/devel/kint/kint/Kint.class.php');

and use Kint like so:

Kint::dump( $_SERVER );


Set the custom initial date on FullCalendar based on a field in the current node

So this and two additional Content Node Fields edit worked for me. Starting around line 629 in includes/views/fullcalendar.fullcalendar.inc, I changed to the following. Don't forget to add two additional fields to your Content Type with machine names field_default_calendar_year and field_default_calendar_month.

Update on project's issues list: Patch Submitted, Requested Review

See Patch code: http://drupal.org/files/fullcalendar-7.x-2.x-custom_init_date_1.patch


Under admin/structure/contact/edit/1 you can add or remove any e-mail address(es) you want from the "recipients" box.


What does the "Vary: Cookie" header actually do for serving pages from Varnish?

To answer my own question. I've found that with $conf['omit_vary_cookie'] = TRUE;, users who visit a page as anonymous users and log in will see the cached version of the page until they click "refresh" on their browsers. It is a subtle difference that I didn't notice at first as  admininistrator user.


Newly contributed theme not showing in Project Application issue queue

It doesn't appear because you didn't create an issue in the Project Application issue queue, but in the issue queue for your theme.
To create a issue in that queue, go to https://www.drupal.org/project/issues/projectapplications and click on Create a new issue.

Since I am a Drupal.org webmaster, I have already moved the issue in the correct queue; you don't need to do anything more.


Add slideshow option to 'link image to' in Views

I assume you already have a Gallery or Slideshow working (otherwise check other modules, e.g. Juicebox). If you want the image to link to a specific path you need to choose the option Rewrite Results > Output this field as a link. You can use tokens if you want to change this path dynamically according to other fields in the View.


Make Conditional Field work with Price widget

Conditional field module is base on the States API. You can probably do this via a hook_form_alter in a module.

The example below will make the field 'my_field_price' visible and required when 'my_checkbox' is checked.

  $form['my_field_price']['#states'] => array(
    // Show and make the field required if 'my_checkbox' is checked.
    'visible' => array(
      ':input[name="my_checkbox"]' => array('checked' => TRUE),
    ),
    'required' => array(
      ':input[name="my_checkbox"]' => array('checked' => TRUE),
    ),
  ),


Getting custom body class from node field

function TEMPLATE_preprocess_html(&$vars) {
    $node = menu_get_object();
    if ($node && isset($node->nid)) {
        $field_body_class = field_get_items('node', $node, 'field_body_class');

        if (isset($field_body_class[0]['value'])) {
            $vars['classes_array'][] = $field_body_class[0]['value'];
        }
    }
}

This is how it would look today in Drupal 7, assuming your field name is what it is in the example. (The difference with the other answer being instead of $vars['attributes_array']['class'][] using $vars['classes_array'][])


Use hook to get the domain configuration from language

The domain associated with each language is stored as configuration. Using the following code, $prefix will contain the prefix, and $domain the domain used.

  $config = \Drupal::configFactory()->get('language.negotiation');
  $languages = \Drupal::languageManager()->getLanguages();
  $prefixes = $config->get('url.prefixes');
  $domains = $config->get('url.domains');
  foreach ($languages as $langcode => $language) {
    $prefix = $prefixes[$langcode];
    $domain = $domains[$langcode];
  }

I wrote the code basing on NegotiationUrlForm::buildForm(), which is the form builder for the form that sets the negotiation URL for each language.


How to set a banner slideshow to run if images are only fully loaded

You can visit this post  Slideshow Tutorial to create slide show On drupal site in Drupal standard way. Try to use Drupal standards.


Changing "Product [product:title] added to your cart." message in Drupal Commerce

There are several Options,

got to rules and disable the add to cart rule, then create your own.
Use this module https://drupal.org/project/stringoverrides to override the string. The string to override is this "%title added to your cart."

I wouldn't edit the module file commerce_cart.rules.inc -> function commerce_cart_rules_add_to_cart_message($product) as when you update it will just overwrite what you have done


White screen of death but only on log in page?

Turns out I had to disable the secure pages module.


Check with including namespace.  Also, check if any other code override configuration or do you enabled settings.local.php. Add this code to the bottom of settings.php

 $databases['default']['default'] = array (
  'database' => 'my_db_database',
  'username' => 'my_db_user',
  'password' => 'my_db_password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);


How should a custom configuration entity define a dependency on other configuration?

ConfigEntityInterface::calculateDependencies returns $this, so this line:
$this->dependencies = parent::calculateDependencies();

Is causing problems (replacing the dependencies array with the instance of the current class, which is presumably a MyAccessDefaults).
Looking at the code, and other core classes which implement ConfigEntityInterface, your code should be:
public function calculateDependencies() {
  parent::calculateDependencies();
  $this->addDependency('module', 'user');
  if (isset($this->role_id)) {
    $this->addDependency('config', "user.role.{$this->role_id}");
  }
  return $this;
}


Finnaly I have find the answer to my problem's .

It was a drupal permission problem's .

User Anonymous users do not have permission to use the general contact form. I gave permission and everything worked .

Thank you alot for the advice .


Add subquery with count, having, and orderby

So, from reading your question, it seems you're missing a fundamental step to data modeling with Drupal. The first thing you're going to want to do is to build out content types and fields for your data. This is done through the content types user interface. Once you have all of your data in node content types and fields, it becomes much easier to access this data in views.

When it comes to creating joins in views, you'll want to use "relationships" under "advanced" on the right hand side of the views UI. Since you're new to Drupal, but not to SQL, you might find it helpful to turn on "Show the SQL Query" here: /admin/structure/views/settings

So, the big realization here is that you don't create custom tables in Drupal databases manually. There are use cases where using a node doesn't make sense. In that case, you'll want to create a custom content entity. This is not done manually in Drupal. While creating entities can be done through code, you're better off using this module to generate your tables:

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

Finally, most Drupal developers prefer nodes for data storage because Nodes are special entities that have many wonderful features that almost all data in Drupal needs.


I just had to implement this on a site in a similar fashion. You can use MIME Mail and it's submodule MIME Mail Attachments along with the Print and the Rules Download module. It will allow you to create a rule and email (with attachment.


Unable to export and import custom block type fields

The field definitions are in their own yml-files. To check this, export the full archive and search for the dependencies. For example the body of the block content type basic has this yml-file:

field.field.block_content.basic.body.yml

and there you find the dependencies for the block content type:

dependencies:
  config:
    - block_content.type.basic


drupal 7 frontpage image scroller: getting image URL in overwritten view template?

here two alternatives to get the image address:
(to both examples the machine name of the image field is *image_test_field*).

1) this example is using the $row offer by view template (in this case the name of the field was obtained using dsm($row) or print_r($row)):

  $uriImagefromView = $row->field_field_image_test_field[0]['rendered']['#item']['uri'];
  $urlImagefromView = file_create_url($uriImagefromView);
  // $urlImagefromView variable now has the path to the image

2) this example is loading the data from entity_load  (in this case the name of the field was obtained using dsm($entity) or print_r($entity)):

  $nid = $row->nid;
  $entity = entity_load('node', array($nid));
  $uriImagefromNode = $entity[$nid]->field_image_test_field['und'][0]['uri'];
  $urlImagefromNode = file_create_url($uriImagefromNode);
  // $urlImagefromNode variable now has the path to the image

I hope this information be useful.


Rendering a simple PHP array into an HTML table

Assume you have code similar to this:

$table_data = array(
  array( 'Some Index', 'Some value'),
  array( 'Some Index', 'Some value'),
);

In this case, just call theme('table', array('header' => array(), 'rows' => $table_data));.

This will call theme_table(), unless your theme overrides that particular theming function. Any override, however, should expect the array to be structured in the same way as described for theme_table(), so look there about the specifics. In particular, you might want to replace 'Some Index' with array('data' => 'Some Index', 'header' => TRUE) to indicate that this cell is a table header cell.


Why making a Views page instead of Views block?

Blocks are appropriate to display piece of content but a Page is for displaying the whole content.

If you create a block of a View, using admin UI you can easily place it in any region (or panels) and reorder it but this option is not available if you use Page.

In Panels, if you use Place In-Editor option to build the pages (like the following image) pages will not be available. This is a very powerful tool in Drupal so if you don't use the appropriate structure you will miss it.

So as a result, by using blocks even a regular user can also easily change the structure of the site and no coding is necessary.

If you create a Page display of a View, to display it's result in some section of the page you must use views_embed_view (or similar ones) function to load that View. This function doesn't load the View title, widgets and ... .

You can use 30 variables to store 30 numbers but you can also use an array with 30 cells. Both approaches work but you should use the reasonable one. It is like your question. you can build your site using both display modes but you should use each one in it's right position.


Create a node programmatically on installing a module

The problem is that install/uninstall and enable/disable are two separate things in Drupal.

When you enable or disable a module, hook_enable() and hook_disable() are invoked respectively.

When you install or uninstall a module, hook_install() and hook_uninstall() are invoked respectively.

If you want to keep your code in hook_install() / hook_uninstall() you'll need to disable the module, and then uninstall it at http://mysite.com/admin/modules/uninstall. Once you re-install it (which will also enable it), your code will be run.

It might be worth having a think if this code would be better served in hook_enable() / hook_disable(), but it will depend on your particular situation.


Drupal 6 - How to programatically create a content type

You can use the Features module to export out the content type and the fields associated with it. Once you have done this you will have a .tar or .zip file of the export code in a functional module.

From here you are able to move that directory into your sites/all/modules directory and have a fully functional module.

Do remember to remove your content type and fields, before installing the module on your site. The new module will recreate them for you.


Views Accordion to be accessible by keyboard

iput this in a block

<script type="text/javascript">
(function ($) {
  $(document).ready(function(){
$('a')

 .each(function(){ // loop through all matched elements

  $(this).removeAttr("tabindex");

});

});

})(jQuery);
</script>


Use hook_form_alter to change the date field on the node form you can only select those two months (and disable the rest).


How to get varchar type input from users on my website?

Use the Custom Formatters module

Consider using the Custom Formatters module, which is very easy to use and configure. And it integrates with various other modules.

Here is an excerpt from its project page:

  ... allows users to easily create custom Field Formatters without the need to write a custom module.

  Pluggable editor/renderer engines:

  Formatter preset: Create simple formatters from existing formatters with preset formatter settings.
  HTML + Tokens: A HTML based editor with Token support.
  PHP: A PHP based editor with support for multiple fields and multiple values.
  Twig: A Twig based editor provided by the Twig filter module.

  Supports for all fieldable entities, including but not limited to:

  Drupal core - Comment, Node, Taxonomy term and User entities.
  Field collection module - Field-collection item entity.
  Media module - Media entity.

The Community Documentation for this module seems to only be a placefholder for now (which is also where the Read documentation links to on the module's Project page).

However there are a few other resources about it that are worth checking out:

Custom Formatters for Easy Drupal Embeds for a tutorial about using this module.
Video about What's new in Custom Formatters 7.x-2.1/2.2.

Create your custom module

Here are some tutorials about how to solve your question using a custom module (all for D7):

Create a custom field formatter in Drupal 7
Creating Custom Formatters with the Field API.
Creating new field formatters in Drupal 7.
Field API - Creating your own field formatters.


You can do this with jQuery, like this:

$(".link-class").click(function(event){
    event.preventDefault();
});


How to use a view as a search result page with facets?

For #1 You could try using Rules to catch the term and do a redirect.  You could also use hook_form_FORM_ID_alter to catch it

Edit:

You can use "Drupal is initializing" for the event, and add a condition that examines the args coming in.  For instance, search/some%20search%query would be:

arg(0) = search
arg(1) = some search query

So here are the steps:

Event -> Drupal is initializing
Condition -> Execute Custom PHP

$arg0 = arg(0);
$arg1 = arg(1);
if ($arg0 == 'search' && $arg1 == 'some search query') {
  drupal_goto('search/my-predetermined-facet');
}

That should do it.


There's a default view that comes with the Views module that will provide the block, it's called Archive and that'd be your best start point, enable it in admin/structure/views and  you'll get both the block with the items grouped by date and a page.

Find an advanced customization of this in http://www.webbykat.com/2012/02/creating-monthly-archive-block-drupal-7-views


What is the best method to build a form to track N number of values?

That, or step 1) you could use http://www.drupal.org/project/flag which would allow the editor(s) to click / unclick a toggle on a user's profile that says they are "curated" and step 2) create a view that lists which users have been flagged.


How to add text to the user registration form?

You can use hook_form_alter like this.

  function MODULENAME_form_alter(&$form, &$form_state, $form_id){
    switch($form_id) {
      case 'user_register_form': // the value we stole from the rendered form
        $form['cutomtext'] = array(
        '#type' => 'item',
        '#markup' => '<div > Your text goes here... </div>',
        '#weight' => 1, // Adjust so that you can place it whereever
        );
        break;
    }
  }

Form API Reference

Also you could try hook_form_FORM_ID_alter

Usage :

function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  // Modification for the form with the given form ID goes here. For example, if
  // FORM_ID is "user_register_form" this code would run only on the user
  // registration form.

  // Add a checkbox to registration form about agreeing to terms of use.
  $form['terms_of_use'] = array(
    '#type' => 'checkbox',
    '#title' => t("I agree with the website's terms and conditions."),
    '#required' => TRUE,
  );
}


Export your current config using drush cex -y
Copy/paste the /web/core/modules/taxonomy/config/optional/views.view.taxonomy_term.yml into your config directory (usually /config)
Import the config using drush cim -y


If you want to change the visibility of many blocks at the same time, this module would be perfect:

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

  Block Visibility Groups allows the site administrator to easily manage
  complex visibility settings that apply to any block placed in a
  visibility group. The visibility settings for all blocks in the group
  can be edited on one administration form.

  This modules works in conjunction with the Drupal 8 core's block
  administration system. It is a simpler alternative to modules like
  Panels.

Even you want to code this yourself, you can use this module as a starting point. The author of this module has a 2 hour video how this code was built.


How to set Link field value via entity metada wrapper?

Try this code:

$node = node_load(nid);
$wrapper = entity_metadata_wrapper('node', $node);
$link = array(
  'url' => 'url',
  'title' => 'title',
  'attributes' => array()
);
$wrapper->field_link->set($link);
$wrapper->save();

Don't missing $wrapper->save();


The whole "Products Listing" requires the "super permission" (a permission that grants all kinds of access, including the ability to quick edit) "administer products." I have filed a feature request in the Commerce Kickstart Issue queue that requests the quick edit button have a more granular permission.

http://drupal.org/node/1883280

Josh


How can I display a picture from a field as the user picture rather than the drupal default with user-picture.tpl.php?

I don't think $user->field_profile_picture['und'][0]['filename'] would be set by default, you normally only get the fid column (this does vary depending on context, but you should always get the fid column either way).

This sort of code always works for me:

if (!empty($user->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($user->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file->uri));
}

If you're worried about the extra overhead involved with potentially loading the file twice, don't be, Drupal caches the object the first time round.

It the above doesn't work it's likely that the $user object is not fully loaded and so the fields haven't been attached. If that's the case, load the user like this:

$account = user_load($user->uid);

And then use the $account object to test for the field value.


So to add a decimal field.

edit your content type.
manage fields
add new field
select Decimal from the Field Type dropdown, click the 'Save' button
Change 'Scale' to 2. These are the cents, 'Save field settings' button.
In the Prefix field add '$' and save settings.


IF it is Drupal 7

Navigate to Administer >> Reports >> Security Review to run the checklist.


fetching taxonomy tree from database from query

This is a way to do it!

$vocabulary = taxonomy_vocabulary_machine_name_load('Services');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));


There are few ways of speeding up the Simpletests:

Consider upgrading your PHP to >5.5 with cache benefits of OPCache.
For PHP <=5.5 try to implement PHP caches such as XCache, APC, eAccelerator.
Install and configure memcached.
Patch your Simpletest to exclude testing of disabled modules.

See: Tests of disabled modules shouldn't be parsed, Strengthen tests by not autoregistering non-test namespaces of disabled modules
Use SimpleTest Clone

(consider patching the module to exclude some big tables while cloning).
Optimize your MySQL instance e.g. via MySQLTuner-perl.
For sites that have lots of slow queries, disk access is often the bottleneck. So speed up by moving MySQL temporary directory to tmpfs., How to setup mysql on tmpfs?
Test only specific Simpletests groups that you need.

Other option to consider:

Try to identify the bottleneck and upgrade your hardware.
Break down simpletests into groups and run on separate machines.
Forget about the speed by integrating Simpletests with Continuous integration (CI) such as Jenkins, Travis CI, AWS, etc.
Use alternative test frameworks (e.g. PHPUnit), see: [meta] Replace the testing framework with PHPUnit and possibly rewrite Simpletest.

Use alternatives:

Behat (recommended)
PHPUnit (which has been added to Drupal 8)
Selenium web driver or Selenium IDE (which is slow as well:)


How can you prepopulate a field based on another field's value?

FYI, the module maintainer will send you here if you enter a support question - he will not answer it in the issue queue.


You're saying that you have this in your routing.yml file:

user_profile_update.callback:
  path: '/user-update'
  defaults:
    _controller: '\Drupal\user_profile\Controller\ProfileUpdateController::updateUser'
  requirements:
    _user_is_logged_in: 'TRUE'
    _permission: 'access content'

You're still calling updateUser and not updateUser123

Your controller should be looking like this:

class ProfileUpdateController extends ControllerBase {

  public function updateUser123() {
  //your code here
  }

}

And now you'll need to call the method:

user_profile_update.callback:
  path: '/user-update'
  defaults:
    _controller: '\Drupal\user_profile\Controller\ProfileUpdateController::updateUser123'
  requirements:
    _user_is_logged_in: 'TRUE'
    _permission: 'access content'

Also I recommend clearing your cache with Drush.
This will empty all caches and rebuild the data required for Drupal to execute the page request


So I tested and there is a significant difference between the two that I failed to understand originally.  Calculations not surrounded with ...

$render_array = &drupal_static(__FUNCTION__);
  if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $render_array = $cache->data;
    }
    else {
      // Do your expensive calculations here
      cache_set('my_module_data', $render_array, 'cache');
    }
  }

...are executed every time the menu callback function is called (every time user visits that page).

Method #2 caches only the final, rendered output.  So if your calculations/processing in the method has changed the output value and you've cached the rendered output, you will not see the updated value until the cache is cleared.


Using variable_get() still returning a form with the default value?

If I understand your question correctly, your values are not saved.

This is because you either need to handle storing variables (using variable_set()) in your submit callback, or use system_settings_form() to do this for you.

The latter approach is generally used for administrative settings, unless you need some additional processing or storing part of the settings somewhere else.

Do note that with system_settings_form() you don't need to add the form actions - they will be added for you.

Here's an example:

function my_module_admin_settings_form($form, $form_state, $nid = 0){
  $form = array();
  $form['subject'] = array(
    '#title' => t('Subject Line'),
    '#descirption' => t('Default email subject line.'),
    '#type' => 'textfield',
    '#size' => '50',
    '#required' => TRUE,
    '#default_value' => variable_get('subject', 'You have not enabled TFA'),
  );

  // Add more fields.

  return system_settings_form($form);
}


Can add the new variable in the existing node--contenttype.tpl.tpl?

You'd be better off doing in here:
https://api.drupal.org/api/drupal/modules%21node%21node.module/function/template_preprocess_node/7.x

"Processes variables for node.tpl.php" so should be ideal for what you need


How to remove Submission information from webfrom module

Follow these steps to modify the email content, which comes to you on webform submission :

Login to the system by Admin credentials.
Go to webform page.
Click the Webform tab.
Click the E-Mails tab inside Webform tab.
Click Edit in Operation column infront of email address set by you for mail.
Find E-mail template & edit the content which goes to the email address set by you.

Check it as you are done.


In Drupal 7, node_build_content() governs the generation of the render array for the node's content:

$node = node_load(1);
$content = node_build_content($node);

If you take a look at the source for it, you can see how the final render array is built and you can pick and choose what you want in the render array by copying the relevant parts from node_build_content().

For example, if you wanted to just render the node's fields, you might do:

$view_mode = 'full';
$langcode = LANGUAGE_NONE;

$node->content = array();

field_attach_prepare_view('node', array($node->nid => $node), $view_mode, $langcode);
entity_prepare_view('node', array($node->nid => $node), $langcode);
$node->content += field_attach_view('node', $node, $view_mode, $langcode);

If you did that, $node->content would then contain the render array for just the fields without all the extraneous stuff like links or other stuff third-party modules might add.


How to use voting results to boost relevance for solr search?

Do you have the voting api results in your apache solr index?
If you do and they are stored under a name ss_votingapi, here is what you need to do:

/*
 * Implements hook_apachesolr_query_alter().
 */
function MYMODULE_apachesolr_query_alter($query) {
  $query->addParam('fl', 'ss_votingapi');
  $query->addParam('bf', "recip(rord(ss_votingapi),1, 1000, 1000)");
}

More here, here and here


storage_api is the right module for seamlessly transferring data such that the user's upload lands first on the servers local filesystem and by rules can have it automatically propagate to any number of containers (S3, Cloud Files etc..)  And even more you can control the priority in which the files are served from the site simply by ordering them in prefered manner.  the URLs will change automatically. pretty slick.


Assuming you have the date popup module installed and enabled:

$form['starting_date'] = array(
  '#type' => 'date_popup',
  '#title' => 'Starting date',
  '#date_format' => 'd/m/Y',
  '#default_value' => date('Y-m-d'),
);


How can I add a cancel button to the content add form for a single content type?

I would use the following code.

function mymodule_form_my_image_node_form_alter(&$form, &$form_state) {
  // If the node is being created, redirect the users to the page where
  // they can choose the content type for a new node; otherwise, redirect
  // them to the page showing the node.
  $destination = (!isset($node->nid) || isset($node->is_new)) ? 'node/add' : "node/{$node->nid}";

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );
}

Notes

markup is the default form element type; there is no need to use #type = 'markup'.
In the node edit form, all the buttons are inside $form['actions']. The weights used from the buttons that form is using are 5 (Save), 10 (Preview), and 15 (Delete). I used 20 to show the link after those buttons, but you can change its weight to show it in a different position.

// Add the buttons.
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
  '#value' => t('Save'),
  '#weight' => 5,
  '#submit' => array('node_form_submit'),
);
$form['actions']['preview'] = array(
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED,
  '#type' => 'submit',
  '#value' => t('Preview'),
  '#weight' => 10,
  '#submit' => array('node_form_build_preview'),
);
if (!empty($node->nid) && node_access('delete', $node)) {
  $form['actions']['delete'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
    '#weight' => 15,
    '#submit' => array('node_form_delete_submit'),
  );
}

There isn't the need to use arg() to understand if the form is for editing an existing node, or for creating a new one. I checked !isset($node->nid) || isset($node->is_new) is TRUE, to verify the node is being created. Drupal seems to simply check empty($node->nid), even though node_object_prepare() uses !isset($node->nid) || isset($node->is_new).
If $_GET['destination'] is set, the link added with l() will point to that path.


Views data export only exporting for current page

In the data export display you need to set the pager to: Display all items. This will return you all the data in your file without pagination.


How to make an external database available to Views?

I've done this successfully a couple of different ways:

Use a SQL View to create a virtual table in db_local that refers to the corresponding table in db__extra. The query to create that would look something like this:

USE db_local;
 CREATE VIEW some_table AS
     SELECT * FROM db__extra.some_table;

You can then refer to this SQL View as if it were a native table in your Drupal database, and you don't even need to add the external database at all in settings.php. Note that this might not be compatible with Data module (see https://www.drupal.org/node/1973806), but you should be able to describe the SQL View to the Drupal Views module by implementing hook_views_data(), and stop using Data module.

Here's another possibility: use selective table prefixes to trick Drupal into rewriting {some_table} to db__extra.some_table. This is not the same as prefixing your Drupal tables.

Your $databases setting would look like this:

$databases = array (
          'default' => array ('default' => array (
                    'database' => 'db_local',
                    'username' => 'db_local',
                    'password' => '_________',
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'mysql',
                    'prefix' => array(
                            'some_table' => 'db__extra.',
                    ),
          ))
);

Again, I'm not sure if this is compatible with Data module, since I don't use it. But it should work with Views if you implement hook_views_data() yourself.


How to create global pattern for terms title (not page title)?

As I said above (in the question), there isn't any module for overriding the H1 heading (title).

I could do this as explained here:

I copied (and pasted) the page.tpl.php into my theme folder.
I renamed it page--vocabulary--[machine name].tpl.php

(for me it was: page--vocabulary--cities.tpl.php
Opened the template.php file in the theme folder. And added this function:

(I've already had the preprocess_page function in the template.php file and I didn't add the preprocess_page function again, I added the if (arg(0) ... part. Don't forget to change the THEME to your theme name.)

function THEME_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));
    $vars['theme_hook_suggestions'][] = 'page__vocabulary__' . $term->vocabulary_machine_name;
  }
}

Opened the page--vocabulary--cities.tpl.php file and found that line:

(Your theme's template.php file may be different but the main structure is the same.)

<?php if ($title): ?>
<?php print $title; ?> CUSTOM TEXT
 <?php endif; ?>

Cleared all caches.

Done! It works :)

(Note: This solution is per vocabulary solution and if you've got a large amount of vocabularies this solution maybe not very for you.)


Created a sitemap using the modules views and views data

You'll need to edit the views-data-export-xml-header.tpl.php that corresponds to the view your wanting to edit. To find this out, click on Advanced, Theme, and then Information. You're looking for a line like this:

  Alternative style: views-data-export-xml-header.tpl.php, views-data-export-xml-header--test.tpl.php, views-data-export-xml-header--views-data-export.tpl.php, views-data-export-xml-header--test--views-data-export.tpl.php, views-data-export-xml-header--default.tpl.php, views-data-export-xml-header--default.tpl.php, views-data-export-xml-header--views-data-export-1.tpl.php, views-data-export-xml-header--test--views-data-export-1.tpl.php

Pick a filename and make the changes. Note that if you're looking to wrap the results in additional tags, you'll need to override both the header and the footer files.

You'd change:

// Short tags act bad below in the html so we print it here.
print '<?xml version="1.0" encoding="UTF-8" ?>';
?>

<<?php print $root_node; ?>>

To also include any other information:

// Short tags act bad below in the html so we print it here.
print '<?xml version="1.0" encoding="UTF-8" ?>';
?>

<<?php print $root_node; ?>>
<header-data>
</header-data>


Is it possible to alphabetize a sorted view?

It is definitely be possible to add a second sort to the query which will give the desired effect, but you will have to write some custom code.

There are several hooks that Views provides that you can use in a custom module.  I suggest looking at hook_views_query_alter().  The example code on the API page actually shows it altering a WHERE clause, but creative use of dsm()'s will help you figure out what you need to change.

I'm sorry that I can't give you code (because this kind of modification is highly specific to your installation), but this is definitely the way to go.


Updating core modules independently of core?

For example, could you update Views without updating core?

First of all, you should check if you could get away with implementing those changes via a hook, event subscriber, or altering/overriding a service.

If not, download Lastest_Drupal_8.zip and unzip only /core/modules/views folder onto your projects /core/modules/views folder.

If you like, you could create a patch for that particular core module using git diff between latest and current version.

Although, I wouldn't recommend to do this to begin with, this is bad practice!, but if there is a really, really, and I mean, really good reason sure.

Caveats:

You'll have to test the core module to make sure all is good.
You won't be able to use composer update unless you find a way to make it run the patch.


What module to edit theme css in my drupal site

Live CSS is the module you are looking for:

  Edit CSS live within the page, and save the changes back to any css
  file if you have write access.

  Additionally, this module enables the ability to render and perform
  live editing of LESS stylesheets, included just like css files. Users
  without the live editing permission will still see properly rendered
  LESS displayed.


So I was able to resolve this problem with a simple fix - though it took a good deal of time to find it, so I figured I'd post it here to inform others in the event they have a similar difficulty.

I simply used the Field validation module which gives the user the capability of selecting his/her own UID for any field instance...quite straightforward.

Hope that helps!


Feeds Soap - importing items but can only add 1 item at a time?

I managed to solve my question by my self, In order to do that I had to create simple module

<?php
function feedspop_node_presave($node) {
  if($node->type == 'ubrania_a') {
      $numeraukcji = $node->field_import_id['und'][0]['value'];
      $node->feeds['FeedsWSClientFetcher']['operation_arguments']['parameters']['itemId'] = $numeraukcji;
      dpm($node, $name = NULL);
  }
}
?>


How to set up a contextual filter or child relationship?

Apparently there is no way to solve it using contextual filters and relationships. I solved the b2 part by using a separate dedicated view of content nodes as a No results view. It works because the taxonomy has consistent, non-mixed level contents.