Drupal 8: How to put a comma in addressfield display?

It appears you would need to write a custom address-plain.html.twig file and add it to the templates folder either in a module or in your theme.

Code:

  {% if given_name or family_name %}
    {{ given_name }} {{ family_name }},

  {% endif %}
  {% if organization %}
    {{ organization }},

  {% endif %}
  {% if address_line1 %}
    {{ address_line1 }},

  {% endif %}
  {% if address_line2 %}
    {{ address_line2 }},

  {% endif %}
  {% if dependent_locality.code %}
    {{ dependent_locality.code }},

  {% endif %}
  {% if locality.code or postal_code or administrative_area.code %}
    {{ locality.code }} {{ postal_code }} {{ administrative_area.code }},

  {% endif %}
  {{ country.name }}.


Display full webform submission on submission page

It's the webform-confirmation.tpl.php that you'd want to edit.

There's an article here explaining exactly what you want to achieve. https://www.drupal.org/node/1515548


What alternatives do I have to use the Computed Field module?

Using rules you can do basic calculations with field values and write the result into an other field. If you do the calculation after an instance of your content type has been saved you make sure the value is always up to date.

Of course you can implement your own action as well and hook it into rules. See hook_rules_action_info.

Whether your users find rules easy to manage and you can trust them to give them access to the rules system is an other story. Depending on what you want to evaluate you might just add some fields to get all the information you need and add a custom action to do the evaluation.


You can split your code in as many files as you want. For every file except the *. module file add a line to your *.info file:

files[] = inc/my_form_1.inc

You can also place functionality into seperate files by specifying the path to the files in hook_menu. Have a lookt at the file property in the hook_menu description.


I would like to know how can I also list the blog previews (or teasers) on the home page

You can do this using views in both D7 & D8. If you go at Structures/Views, you will find the view name Front page, you can enable that view which by default works as front page in Drupal. So as per you need, you just need to apply filter for blog content type and in view mode you can set it as teasers.

as well as the main blog page?

Same way you can make new view and give new path/url to that view and set it as main blog page.

Illustrations of above details:

1. Default front page view at Structures/views

2. Front page view setting page: I have changes the filter parameters so it will show only blog posts at home-page.

3. Output image: HOME page showing only blog previews.


As documented here, I went with overriding the views row style plugin. All I did in the override was add the render() method and add my own modifications to the $build array to make it work.

<?php

namespace Drupal\video_export\Plugin\views\row;

use Drupal\views\Plugin\views\row\RssFields;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Renders an RSS item based on fields.
 *
 * @ViewsRow(
 *   id = "mymodule_rss_fields",
 *   title = @Translation("Custom Fields"),
 *   help = @Translation("Display fields as RSS items."),
 *   theme = "views_view_row_rss",
 *   display_types = {"feed"}
 * )
 */
class MyModuleVRssFields extends RssFields {

  /**
   * Override of RssFields::render() with additional fields.
   *
   * @param object $row
   *
   * @return array
   */
  public function render($row) {
    $build = parent:: render();
    $item = $build['#row'];

    // Add MRCTV nid
    $item->elements[] = array(
      'key' => 'source-nid',
      'value' => $row->nid,
    );

    // Add channels and their target nids. We can get them from $row->_entity.
    $site = $this->view->args[0];
    // Get source nids from view.
    $channel_tids = array_column($row->_entity->field_channels->getValue(), 'target_id');
    // Now, get destination tids from config.
    $mapping_config = \Drupal::config('video_export.mappings');
    $all_mappings = $mapping_config->get('sites');

    foreach($channel_tids as $source_channel) {
      if(in_array($source_channel, array_keys($all_mappings[$site]['mappings']))) {
        $item->elements[] = array(
          'key' => $site . '-channel-map',
          'value' => $all_mappings[$site]['mappings'][$source_channel],
        );
      }
    }

    // Re-populate the $build array with the updated row.
    $build['#row'] = $item;

    return $build;
  }
}


menu_links is a Twig macro, that is called recursively. That macro is located in menu.html.twig. In there you can do stuff based on current menu_level.

{% if menu_level == 0 %}

{% else %}

{% endif %}

Notice that this macro is called recursivly, so if you are adding a classes like {% set attributes = attributes.addClass('menu--level' ~ menu_level) %}, this additional class is also stored and passed down recursivly!

Also take a look at core/themes/classy/templates/navigation/menu.html.twig to get an example of a full menu template file.


The differences between date time zone handling

The Date module's documentation page describes the difference between the 5 options fairly well.

From that page:

There are 5 different options for field Time zone handling:

Site's time zone - When entering data into the field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
Date's time zone - With this option enabled, the date field adds a select box to explicitly specify the time zone for the date entered. When the date is saved to the database, it is not converted & the time zone information is saved with the date. When retrieved from the database, no conversion is performed and the date is displayed exactly as entered.
User's time zone - When entering data into the field, the data entered is assumed to be in the user's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
UTC - When entering data into the field, the data entered is assumed to be in UTC time zone. When the data is saved to the database, it is converted to UTC (e.g. no conversion necessary). When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
No time zone conversion - The date entered is not converted when saved to the database. When retrieved from the database, the data is NOT converted and is displayed exactly as entered.


Adding/Editing Node tab links through preprocess method

All _alter() hooks can be implemented by themes as well as modules, so in that specific case you can just use

function mytheme_contextual_links_view_alter(&$element, &$items) {
  ...


I see in your page source it says:

http://www.athleteyouniversity.com/sites/all/themes/nexus/sites/all/libraries/galleria/plugins/history/galleria.history.min.js?o30qzc

You have a sites/all/ folder inside your theme /nexus folder, which is not how it's suppose to be. The libraries folder needs to be outside of your theme folder.

It's suppose to be /sites/all/libraries/galleria/plugins/history/galleria.history.min.js


How do I add the number of rows shown in a view to a menu link?

You can do this with a view, assuming each item is a content type.

Create a new view of Content as an unformatted list of fields. Under 'Advanced' set Use Aggregation to Yes.

Under fields delete the title field, and add Content:Type and Content:NID.

Configure the Content:Type field as no label and "group by" under Aggregation Settings. Under 'Rewrite Results' check 'Output this field as a link', set it to replace spaces with dashes and to convert to lower case. In the path enter something like "list/[type]", depending on your desired target.

Configure the Content:NID field as no label, and add the prefic " (" and the suffix")". Set it to 'Count' under Aggregation Settings.

Use CSS to have both fields float:left; to line them up.

You can leave the view unsorted or sort by Content:NID->COUNT or by Content:Type. You should leave the filter for Published nodes, and you can add a filter to restrict the content types which will appear.

Then place the block where you want the menu to appear.


How to better search: replacing %20 with +

I don't know what you mean by "better search", as the search works as-is. However, I think the reason it works this way is because drupal_goto() eventually calls drupal_http_build_query(), which calls rawurlencode(). Drupal uses this for URL query parameters. The docs for the function say it returns:

a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC 1738 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).

https://php.net/manual/en/function.rawurlencode.php
RFC 1738: https://tools.ietf.org/html/rfc1738
To change this, you could create your own module or function that does not does escape :. If you use an exposed view search form, it should already encode spaces as +.


Showing list of nodes related to logged in user using views

I'm not sure about the details of your use case, but it might be easier to set the author of the node to the user rather than setting up a field with a reference.

You can set the author manually if you have administrator permissions.  You could also use the Rules module (via the "Set a data value" action) to do so automatically.

If you use this method, you can simply set the permissions for "View own content of type ABC" and "View all content of type ABC" that are provided by default to limit access.

For your view, you can add a "Contextual filter" of "Author".


Need to know if user is coming from frontpage using jquery

jQuery(document).ready(function($) {
  var referrer =  document.referrer;
  if (referrer == 'http://domain.tld/') {
    // Make whatever you like
  }
});


How to give access to delete his own comments

Are you familiar with coding? You can try this tutorial.

edit: and i ran into this site, wich is a patch to the module 'Comment Goodness'. There's also some extra info about flat comments (the default structure is nested, not flat).


PDO Error, __construct(): php_network_getaddresses: getaddrinfo failed:

The default settings.php is located at sites/default/settings.php, not in the root of your drupal installation.  I have no idea why one of the server techs at my hosting company moved the settings.php into the root, but that was what my previous confusion was.

As a side-note, if your moving from a production to a development server, make sure that you setup your host in settings.php to localhost.  As a corollary, if you're moving from development to production, make sure you set your host field from youraddress.com (or youraddress.hostingaddress.com) from localhost.  It would be nice if there was a field somewhere in drupal settings to handle this, so that you didn't have to snoop through the settings.php to find/set it.  However though, this is likely not possible since drupal pulls everything like this from databases and it has to have these settings in order to see the database.  Just food for thought.

I also normally find it useful to look at code snippets rather than trying to understand what someone said, so here's an example of what your database line in settings.php should look like if your settings up a generally basic development server.

$databases = array (
  'default' =>
     array(
        'default' =>
         array (
            'database' => '##Your_database_name##',
            'username' => '##your_database_username#', #comment & store old user from production server here for safe keeping
            'password' => '##your_database_password##', #comment & store old pw from production server here for safe keeping
            'host' => 'localhost',   #comment and store production database url here
            'driver' => 'mysql',
            'port' => '',  #localhost shouldn't normally need a port, but your production sever likely does, so comment and store that on the side here.
            'prefix' => ''
         ),
    ),
);


Instead of fetchAll(), try fetchCol(), like this:

$latitude_values = db_query("SELECT field_latitude_value FROM {field_data_field_latitude}")->fetchCol();


Kernel Test: Programmatically create a vocabulary and add a field to it

You need to enable the field module so its entity types are present. Kernel test base does not enable required modules so the FieldConfig and FieldStorageConfig entity types don't exist until you enable the field module. Put it in the $modules property with 'taxonomy' and 'text'.


how to define entity preprocess function

I created a general mymodule_preprocess(&$variables, $hook) function and it showed that the specific function name should be mymodule_preprocess_myentity. Where myentity is the proper name of the entity.

So, this code is working for me:

function mymodule_preprocess(&$variables, $hook) {
  if (isset($variables['elements']['#entity_type'])) { // or maybe check for $hook name
    $function = __FUNCTION__ . '_' . $variables['elements']['#entity_type'];
    if (function_exists($function)) {
      $function($variables, $hook);
    }
  }
}

function mymodule_preprocess_myentity(&$vars) {
  ...
}


How do I load entities with Null values?

The example of getting articles that has empty body:

  $entityStorage = \Drupal::entityTypeManager()->getStorage('node');
  $query = $entityStorage->getQuery();
  $query->condition('type', 'article');
  $query->notExists('body');
  $nids = $query->execute();
  $nodes = $entityStorage->loadMultiple($nids);


It's hard to say without seeing your Views settings but you may need to change the Field settings to link back to the full article.

E.g. See the bottom checkbox.


Redirect to login page if login fails from a login block?

You can do this by form_alter

function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'user_login_block':
      $form['#validate'][] = 'my_custom_login_val';
      break;
    default:
      break;
  }
}

function my_custom_login_val($form, &$form_state) {
  $form = form_get_error($form['name']) . form_get_error($form['pass']);
  if($form != '') {
    $_GET['destination'] = 'user/login';
    drupal_goto('user/login');
  }
}

If you need like after the correct login redirect to a page use Login Destination


If parent feeds (import) node is unpublished, how do I not include it in the import schedule?

It looks like, when a node is saved, Feeds module starts importing the feed from that node.

function feeds_node_insert($node) {
  // Source attached to node.
  feeds_node_update($node);
  if (isset($node->feeds) && $importer_id = feeds_get_importer_id($node->type)) {
    $source = feeds_source($importer_id, $node->nid);
    // Start import if requested.
    if (feeds_importer($importer_id)->config['import_on_create'] && !isset($node->feeds['suppress_import'])) {
      $source->startImport();
    }
    // Schedule source and importer.
    $source->schedule();
    feeds_importer($importer_id)->schedule();
  }
}

There is an option in the importer's setting page called Import on submission. If you uncheck this box, hopefully your feed won't be imported.  Feeds maintainer still need to make changes in feed_cron() so that it won't fetch the unpublished nodes.

While you wait for a better fix from module maintainers, you can quickly fix this code by changing the first if statement to add $node->status==1  condition as follows:

if ($node->status==1 && isset($node->feeds) && $importer_id = feeds_get_importer_id($node->type))


How can I convert the code that used drupal_get_http_header() to check if a 403 or 404 error is returned?

You can subscribe to the Symfony KernelEvents::RESPONSE event:

The RESPONSE event occurs once a response was created for replying to a request
This event allows you to modify or replace the response that will be replied. The event listener method receives a Symfony\Component\HttpKernel\Event\FilterResponseEvent instance.

To do so, create a new module ("response_test" in this example), with the usual .info.yml and .module file.
Then register your event subscriber in the module's services file:
response_test.services.yml
services:
    response_test.response_subscriber:
      class: Drupal\response_test\ResponseSubscriber
      tags:
        - { name: event_subscriber }

Now all you need is the class to handle the event:
lib/Drupal/response_test/ResponseSubscriber.php
<?php

namespace Drupal\response_test;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ResponseSubscriber implements EventSubscriberInterface {

  public function onRespond(FilterResponseEvent $event) {
    if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
      return;
    }

    $response = $event->getResponse();
    if ($response->getStatusCode() == 404) {
      // Prepare a new Symfony\Component\HttpFoundation\Response and use
      $event->setResponse($new_response);

      // or call one of the setter methods on $response, the changes will persist
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('onRespond');
    return $events;
  }

}

I'm a little unsure about changing the HTML content in this context; you have access to $response->getContent() and $response->setContent() so you can manipulate the raw string directly, but as far as I can tell everything's already rendered at this point.


Concatenation with %keyword in mini-panels

I've figured out but not sure either it's a standard way or not but I believe override title field is not accepted "prefix or postfix" for %keyword like mentioned in the question.

Solution

1) Removed tag h1 from the attached image in the question.

2) Created new tpl named as panels-pane--event-node-title.tpl.php and added some code in it

<div class="pane-content">
  <?php if ($title): ?>
  <h1> <?php print $title; ?> </h1>
  <?php else : ?>
    // Here we can set any prefix or postfix within the tag
    <h1> Event in <?php print render($content); ?> </h1>
  <?php endif; ?>
</div>

$content variable will get content of the field along with its all settings (ID, class, tag etc.)

I hope this will help someone.


I had a project that needed some specific markup for different fields, using field.html.twig only at least saved managing multiple files.

field.html.twig:

{%
  set themeGroupOne = [
    'first_field',
    'second_field',
  ]
%}

{%
  set themeGroupTwo = [
    'third_field',
    'fourth_field',
  ]
%}

{# field markup option #}
{% if field_name in themeGroupOne %}

  {% for item in items %}
    {{ item.content }}
  {% endfor %}

{# field markup option #}
{% elseif field_name in themeGroupTwo %}

  {% for item in items %}
    {{ item.content }}
  {% endfor %}

{# Final option, default field template #}
{% else %}

{% if label_hidden %}

  {% if multiple %}
    {% for item in items %}
      {{ item.content }}
    {% endfor %}
  {% else %}
    {% for item in items %}
      {{ item.content }}
    {% endfor %}
  {% endif %}

{% else %}
{{ label }}

  {% if multiple %}
    {% for item in items %}
      {{ item.content }}
    {% endfor %}
  {% else %}
    {% for item in items %}
      {{ item.content }}
    {% endfor %}
  {% endif %}

{% endif %}

*Note that the two fields:

field.field.paragraph.paragraph_type.field_h2
field.field.node.node_type.field_h2

will both register as field_name == 'field_h2' in field.html.twig, making it even easier to theme fields across your site.


The screen cast from Sean Buscay : How to use Drupal 7's built-in Ajax framework almost do that. The only difference is that the loaded nobe is always display on the same div base is id.

<?php

function ajax_reader_init() {
  drupal_add_js('misc/jquery.form.js');
  drupal_add_library('system', 'drupal.ajax');
}

/**
 * Implements hook_menu().
 */

function ajax_reader_menu() {
  // A menu callback is required when using ajax outside of the Form API.
  $items['ajax-reader'] = array(
 'page callback' => 'ajax_link_response',
 'access callback' => 'user_access',
 'access arguments' => array('access content'),
 'type' => MENU_CALLBACK,
  );
 return $items;
}

function ajax_link_response($type = 'ajax', $nid = 0) {
  $output = _ajax_reader_load_noder($nid);
  if ($type == 'ajax') {
    $commands = array();
    $commands[] = ajax_command_replace('#block-block-6', '
' . $output . '
');
    $page = array(
      '#type' => 'ajax',
      '#commands' => $commands
    );
    ajax_deliver($page);
  }
  else {
    $output = '
' . $output . '
';
    return $output;
  }
}

function _ajax_reader_load_noder($nid = 0) {
 return views_embed_view ('front','block', $nid);
}

Now the problem is I don't wan to send the result always to the same div. I wan to replace the view row by the new ajax loaded view. But I don't know how to pass the result to the good div.

    $commands[] = ajax_command_replace('#block-block-6', '
'

Lets say I click the title of the third view row the nid of this third element is process in the module but I nead a way to pass the parent div class (view-row-3) to the function ajax_reader_menu()

Did anybody can guide me on that, thanks
I know that I'm not super clear, but all this still vary obscure for the moment, sorry.


Provide several download option for same image in Drupal 7

Do you mean different resolutions? Simply, you have to upload them, and link the files.

Then there are the following modules:

DownloadFile
Download


how to add "create node form" in a block?

there are two modules which can give option to create node from block
Formblock module ,
Advanced Form Block


Seems Menu Item Extras is the way to go now. It makes menu items fieldable. And you probably also get the proper template suggestions already.

  Menu Item Extras provides extra fields for the Menu Items without
  using additional entities. This module is NOT an alternative of all
  Mega Menu modules - it is unique implementation of Drupal core’s Menu
  system. All fields are placed upon the Menu Item edit/add form and use
  core Menu link content entity for storing all data.


Printer - PDF format: How can I change the header info and add page count on the footer?

The Print module uses a separate template for the print, email, and PDF versions of a page.  You would need to implement a hook_preprocess_print() to set up some addtional variables, and then duplicate print.tpl.php into your theme and use your new variables (and/or change the markup in the template).  The default template file is rather well documented, and explains what is possible.


You should be able to access it via

www.example.com/endpoint/salesforce_subscriptions/[ids]/delete

If that doesn't work, you may need to experiment with the id parameter source, e.g path argument vs param

For more info and example, see the node resource definition here:

_node_resource_definition


Error reindexing attachments in Drupal 7 using Apache Solr Attachments module

So I figured this out in case anybody else runs into this issue.

In the 7.x-1.x version of Apache Solr Attachments, there is a line of code in apachesolr_attachments.index.inc that uses the PHP function mb_detect_encoding.  That command relies on the PHP EXIF extension being installed and it is not by default.  Once I modified my PHP installation to include it, it was able to process the files.  I ran into some other issues though but finally got it all working.  Details are posted here -> http://drupal.org/node/1377416


Sounds like a perfect use case for the Menu Badges module, which can be used to add notifications to any menu item and/or menu tab of your choice. Here are some details about it (from its project page):

Provides a method for adding iOS-style badges to menu items. (see screenshot)

Because of how it integrates with the Views module, you basically reduce the solution specific to your question here to something like this:

Create an appropriate view about "new pieces of content relevant to their page has been published" (as in your question).
And create a menu item or menu tab for it.
Grant access to that view for those users who fit "a fellow publisher within the Drupal permissions group" (as in your question).
Perform the required Menu Badges configuration to tell it which menu item/tab you used for it in your view.

Refer to the video Defining Menu Badges with Views in Drupal (from the module maintainer) for more details. It shows a scenario that might be close to what you'd want to implement also.
PS: I'm assuming this question is about D7 ...


If you have Drupal console installed, you could try config:diff


Getting specific property from node_load

Something like that should actually work.

The only issue might be that you are looking for the string '127' but want the integer 127, so remove the '. But I'm not 100% sure right now how PHP handles that.

Also note that you can use isset() instead of array_key_exists() here, so just

if (isset($this_node->taxonomy[137])) {
}

should work too. The difference between isset and array_key_exists() is that isset() returns FALSE if they key exists but the value of it is NULL, while array_key_exists() returns TRUE in that case.


Show the pager on the top and in the bottom of the page (generated by Views)

Copy views-view.tpl.php template file from theme subdirectory of Views module to your theme folder, edit it and duplicate fragment of code responsible for printing the pager:

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

to where you want it.


t() and {% trans %} show no effect although rest of site is translated

If the strings in your custom module are in English but the site's default language is in German, you will need to translate the strings in the admin UI:

/admin/config/regional/translate

If you search for the string on this page but don't see it, you will need to first visit the page/path on the site that causes the string to be displayed so that the string will be created for translation purposes.  Then you can return to the translation page and translate the string.

To translate strings in a twig template, do it like this:

{{ 'This is a string to translate.'|trans }}


Disabling reply link for comments not working

You can use hook_comment_links_alter() rather than THEME_preprocess_comment() .Where as hook_comment_links_alter() will render all the comments links before build:

function YOURMODULE_comment_links_alter(array &$links, Drupal\comment\CommentInterface $entity, array &$context) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($links['comment']['#links']['comment-reply']);
  }
}


How do I add jQuery to specific node form?

Install the JS injector module. Then go to admin/config/development/js-injector. Add a new rule. Fill the JS code field with your script.
In the Pages fieldset select the Pages on which this PHP code returns TRUE (experts only) option and enter the following code:
<?php
if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'content_type') {
 return true;
}
return false;
?>

Replace content_type with your content type name.
This is a theme independent solution. Another way is adding your script in hook_preprocess_page in template.php file of your theme.


Allow anonymous user to search custom account field

This can be covered by the Views module in a few steps.

Make sure anonymous users have the Access User Profiles permission.
Create a user view with a page display in the Views UI.
Add a exposed filter on your view for your license number field. Set the Operator  to Is equal to if you want a search by full account number only, or set it to Contains if you want a partial/full account number search.
Adjust the display how you see fit. The display can contain links to the user profile page.
Save the View.

From this point you should now have a page from which to search for user profiles with your custom account number field.


Allow shipping that is calculated using a base rate plus a rate per item?

Programmatically create your own custom shipping method in a custom module.
Example, custom module called "mymodule":
/modules/custom/mymodule/src/Plugin/Commerce/ShippingMethod/CustomRate.php
<?php

namespace Drupal\mymodule\Plugin\Commerce\ShippingMethod;

use Drupal\commerce_shipping\Plugin\Commerce\ShippingMethod\ShippingMethodBase;
use Drupal\commerce_price\Price;
use Drupal\commerce_shipping\Entity\ShipmentInterface;
use Drupal\commerce_shipping\PackageTypeManagerInterface;
use Drupal\commerce_shipping\ShippingRate;
use Drupal\commerce_shipping\ShippingService;
use Drupal\Core\Form\FormStateInterface;
use Drupal\state_machine\WorkflowManagerInterface;

/**
 * Provides the FlatRatePerItem shipping method.
 *
 * @CommerceShippingMethod(
 *   id = "custom_rate",
 *   label = @Translation("Custom Rate"),
 * )
 */
class CustomRate extends ShippingMethodBase {

  /**
   * Constructs a new FlatRate object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\commerce_shipping\PackageTypeManagerInterface $package_type_manager
   *   The package type manager.
   * @param \Drupal\state_machine\WorkflowManagerInterface $workflow_manager
   *   The workflow manager.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, PackageTypeManagerInterface $package_type_manager, WorkflowManagerInterface $workflow_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $package_type_manager, $workflow_manager);

    $this->services['default'] = new ShippingService('default', $this->configuration['rate_label']);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
        'rate_label' => '',
        'rate_description' => '',
        'rate_amount' => NULL,
        'services' => ['default'],
      ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    $amount = $this->configuration['rate_amount'];
    // A bug in the plugin_select form element causes $amount to be incomplete.
    if (isset($amount) && !isset($amount['number'], $amount['currency_code'])) {
      $amount = NULL;
    }
    // A bug in the plugin_select form element causes $base_amount to be undefined.
    if (!empty($this->configuration['base_amount'])) {
      $base_amount = $this->configuration['base_amount'];
    }
    else {
      $base_amount = null;
    }

    $form['rate_label'] = [
      '#type' => 'textfield',
      '#title' => t('Rate label'),
      '#description' => t('Shown to customers when selecting the rate.'),
      '#default_value' => $this->configuration['rate_label'],
      '#required' => TRUE,
    ];
    $form['rate_description'] = [
      '#type' => 'textfield',
      '#title' => t('Rate description'),
      '#description' => t('Provides additional details about the rate to the customer.'),
      '#default_value' => $this->configuration['rate_description'],
    ];
    $form['base_amount'] = [
      '#type' => 'commerce_price',
      '#title' => t('Base amount'),
      '#default_value' => $base_amount,
      '#required' => TRUE,
      '#description' => t('Charged once.'),
    ];
    $form['rate_amount'] = [
      '#type' => 'commerce_price',
      '#title' => t('Rate amount'),
      '#default_value' => $amount,
      '#required' => TRUE,
      '#description' => t('Charged for each quantity of each shipment item.'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    if (!$form_state->getErrors()) {
      $values = $form_state->getValue($form['#parents']);
      $this->configuration['rate_label'] = $values['rate_label'];
      $this->configuration['rate_description'] = $values['rate_description'];
      $this->configuration['base_amount'] = $values['base_amount'];
      $this->configuration['rate_amount'] = $values['rate_amount'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function calculateRates(ShipmentInterface $shipment) {
    $base_amount = Price::fromArray($this->configuration['base_amount']); // create base price
    $amount = Price::fromArray($this->configuration['rate_amount']);
    $quantity = $shipment->getTotalQuantity();
    $ship_price = $amount->multiply($quantity);
    $ship_price = $ship_price->add($base_amount); // add base
    $rates = [];
    $rates[] = new ShippingRate([
      'shipping_method_id' => $this->parentEntity->id(),
      'service' => $this->services['default'],
      'amount' => $ship_price,
    ]);

    return $rates;
  }

}

Result


Unable to programmatically render webform with supplied default values

Did you try using the Webform render element documented at the bottom of https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-embed-a-webform.

return [
  '#type' => 'webform',
  '#webform' => 'your_form_id',
  '#default_data' => ['name' => 'Custom Name'],
];


Work around to getting Backup and Migrate to work with Acquia Dev Cloud?

The best is enable your access to the command line to their server.

For this you need to store your public ssh_key in your profile on their platform.

Then to find the exact server and username to connect do :

Sign in to the Acquia Cloud interface.
Select your application and
environment.
In the menu to the left, click Users and Keys, to see your exact command :

What follows is using drush ... but wait ... you can automate the use of drush : I explain.

Once logged, you can use drush from the command line, like this :

cd dev/livedev/docroot

drush ard

Since you have access to the command line, you can also use scp to transfer your backup.

By the way you won't have the possibility to access crontab -e there, however, you can write a script and execute from your computer to connect via ssh, do the backup, and get it using scp.

Once this script is written, you can use the cron from your computer to execute it every hour if you want.

That script would look like :

cd ~/dev/livedev/docroot
drush ard
cd drush-backups/archive-dump/
cd `ls -Art | tail -n 1`
mv `ls -Art | tail -n 1` ~/last_backup.tgz

You can store it remotely as ~/backup.sh locally in your cron you put

ssh -t -t yourlogin@youraddress '~/backup.sh && exit' && scp yourlogin@youraddress:~/last_backup.tgz /home/yourself

For an explanation of the -t -t, see https://serverfault.com/questions/224307/ssh-fails-to-execute-remote-command-when-run-from-cron-bash-script-works-from

If any other issue, with ssh from cron, please watch also : https://serverfault.com/questions/186448/crontab-to-run-bash-script-ssh-command-in-it-not-working

Another solution is to use the scheduled job from their interface, as explained there : https://docs.acquia.com/acquia-cloud/manage/cron

If any other problem please comment.


Set up a Git version control repository that integrates with OpenAtrium

Check out the "What theme and modules does Drupal.org use?" page.

Specifically for Git repository management, you'll want to use this set of modules:

http://drupal.org/project/versioncontrol
http://drupal.org/project/versioncontrol_git

And if you want a project release / issue tracking section like drupal.org, see:

http://drupal.org/project/project
http://drupal.org/project/project_issue
http://drupal.org/project/versioncontrol_project


Restrict language content for a given role

A way to achieve it can be this.  Note I am assuming you are using the standard node-based translations, and not entity-based translations.

Suppose the content is a node-type one and the content-type is called Page_en_es.  Give permissions at /admin/people/permissions:

View own unpublished content, Page_en_es: Edit any content etc to translator users
View published content to anonymous users.

Then, whenever a translator edits or creates the Spanish content, s/he will set it (=node) to be not published.  And the Spanish version won't be seen by anonymous users.


You may implement this: hook_privatemsg_message_presave_alter.

  Change the message before it is stored.

The $message variable contains the message's body (as well as much more parameters) ready to be edited. Note that you can include html tags in your message. Here is a code sample:

/**
 * Implements hook_privatemsg_message_presave_alter().
 * Change the message before it is stored.
 */
function my_module_privatemsg_message_presave_alter(&$message) {
  // dsm($message); print out the $message contents
  $name = $message->recipients['user_1']->name; // use foreach for many recipients
  $message->body = "Dear $user,\n you rock!";
}


How to deal with deleted posts: Returning 410 status and preventing path re-use

Pathauto will not duplicate paths. If your Pathauto URL pattern results in the path 'oct/job1' and that path already exists, Pathauto will add an integer to the end of the alias, incrementing it for every new 'identical' path. IE, you'll end up with these paths:

oct/job1
oct/job1-0
oct/job1-1
oct/job1-2
oct/job1-3

... etc.

So what you need to do is:

Implement hook_menu() to create a custom page callback that will map to a function which will return the 410 HTTP code.
Create the callback function for the path you created in hook_menu()
Implement hook_node_delete() and look at the type of the node being deleted; if the type matches the content type you're working with, run a query to update the url_alias database table, changing the 'source' of the records relating to your node from the 'node/##' value to the menu callback you created in step 1. This will prevent Pathauto from deleting the aliases, and will instead map them to your function which will return the 410 HTTP code.

One thing to keep in mind is that the module in which you implement this custom functionality needs to fire before Pathauto, so you may need to alter your module's 'weight' value in the system database table.


Installing with Composer causes unit tests to fail

Drupal with Composer uses the drupal-scaffold script which you mentioned. It seems that it does not include the composer.json and composer.lock files by default.

But the files are there: http://cgit.drupalcode.org/drupal/plain/

Looking at the plugin documentation on github in the Configuration section reveals that the composer.json and composer.lock files are not on the list to be included by default.

But the plugin is configurable, and you can actually specify the name of the files that should be additionally included.

So adding this in the extra section of your composer.json:

"drupal-scaffold" : {
    "includes" : [
        "composer.json",
        "composer.lock"
    ]
}

followed by running composer drupal-scaffold OR removing web/core directory and running composer install should get you the required files and make the tests pass.x


Download a node (and its associated files as a zip archive)

I put together a proof of concept module real quick, which exports files based on assumptions about field_type (image, file and media).

To test it out, put the following code in a custom module, then go to /export-entity/node/nid to export a node.

<?php

/**
 * Implements hook_menu().
 */
function export_entity_menu() {
  $items['export-entity/%/%entity_object'] = array(
    'page callback' => 'export_entity_page_callback',
    'page arguments' => array(2, 1),
    'load arguments' => array(1),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

/**
 * Export entity page callback.
 *
 * @param object $entity
 * @param string $entity_type
 *
 * @throws EntityMalformedException
 * @throws EntityMetadataWrapperException
 * @throws Exception
 */
function export_entity_page_callback($entity, $entity_type) {

  $wrapper = entity_metadata_wrapper($entity_type, $entity);
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);

  $file_fields = field_read_fields(array(
    'entity_type' => $entity_type,
    'bundle' => $bundle,
    'type' => array('image', 'file', 'media'),
  ));

  $field_files = array();
  foreach ($file_fields as $field_name => $field_config) {
    $files = $wrapper->{$field_name}->value();
    if ((int) $field_config['cardinality'] === 1) {
      $files = array($files);
    }
    foreach ($files as $file) {
      $field_files[$file['fid']][] = $field_name;
    }
  }

  $export_filename = drupal_tempnam(file_directory_temp(), 'entityexport_');

  $zip = new ZipArchive();
  if (!($zip->open($export_filename, ZipArchive::CREATE))) {
    throw new Exception(t('Unable to create zip archive'));
  }

  $entity_data = entity_var_json_export($wrapper->raw());
  $zip->addFromString(sprintf('%s_%d.json', $entity_type, $id), entity_var_json_export($entity_data));

  // Load and attach all files/file entities
  $files = file_load_multiple(array_keys($field_files));
  foreach ($files as $file) {
    $folder = reset($field_files[$file->fid]);
    $file_path = drupal_realpath($file->uri);
    $zip->addFile($file_path, $folder . '/' . $file->filename);
    $zip->addFromString($folder . '/' . $file->filename . '_entity.json', entity_var_json_export($file));
  }
  $zip->close();

  // Copy archive to public storage and redirect to its URL.
  $public_uri = file_default_scheme() . '://entity-export/' . $entity_type;
  file_prepare_directory($public_uri, FILE_CREATE_DIRECTORY);
  $public_uri .= '/' . basename($export_filename) . '.zip';

  $public_path = file_unmanaged_move($export_filename, $public_uri);
  $public_url = file_create_url($public_path);

  drupal_goto($public_url);
}

Note that this should be done using a batch callback and/or a cron-job, especially if you expect to get alot of data - which may cause the script to time out and/or run out of memory (although it really shouldn't).


If you use CCK ver 3.x you get the multigroup submοdule. This allows you to create a group of fields like in you case company and price and then create multiple instances of this group.

UPDATE

CCK ver 3.x is alpha. However I have used it in production without problems. You could look into the issue queue for bugs in the 3.x version before you use it.

If you are creating a new site I would suggest going with drupal 7. CCK has moved to core in drupal 7 but the functionality of multigroup does not exist.
However you can achieve a similar result using the Field Collection module. Looking at this http://oliverdavies.co.uk/blog/2011/08/create-multigroups-drupal-7-using-field-collections or this http://mostrey.be/creating-multigroup-widgets-drupal-7 will find out how.


How do i change the apachesolr index environment based on node values?

I do not know if it is possible to shard Drupal nodes into different Solr indexes based on arbitrary field values, I do however know it is possible at a node type level.

From the API documentation:

/**
 * This is invoked for each entity that is being inspected to be added to the
 * index. if any module returns TRUE, the entity is skipped for indexing.
 *
 * @param integer $entity_id
 * @param string $entity_type
 * @param integer $row
 *   A complete set of data from the indexing table.
 * @param string $env_id
 * @return boolean
 */
function hook_apachesolr_exclude($entity_id, $entity_type, $row, $env_id) {
  // Never index media entities to core_1.
  if ($entity_type == 'media' && $env_id == 'core_1') {
    return TRUE;
  }
  // Never index news entities to core_2.
  if ($entity_type == 'news' && $env_id == 'core_2') {
    return TRUE;
  }
  // Default to allow.
  return FALSE;
}

So all you would need to do is allow some node types to be indexed by one core, and allow some other node types to be indexed by another core.


There are two problems.
/admin/structure/types/manage/article/fields/node.article.body is the path of a field setting. To trigger the hook you need to visit /admin/structure/types/manage/article/display.
The plugin ID is wrong, too. text_textarea_with_summary is the plugin ID of a widget. What you are looking for is probably the formatter text_summary_or_trimmed.
If this is neither formatter nor widget, but the content type specific field definition, then use a normal form alter hook, because there is no specific hook to add third party settings:
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_form_alter().
 */
function my_module_form_field_config_edit_form_alter(array &$form, FormStateInterface $form_state) {
  /** @var \Drupal\Core\Field\FieldConfigInterface $field */
  $field = $form_state->getFormObject()->getEntity();
  if ($field->getType() == 'text_with_summary') {
    $form['third_party_settings']['my_module']['my_setting'] = [
      '#type' => 'checkbox',
      '#title' => t('test'),
      '#default_value' => $field->getThirdPartySetting('my_module', 'my_setting'),
    ];
  }
}

Edit: The form keys $form['third_party_settings']['my_module']['my_setting'] are important. They are used to submit the third party settings.


Avoid new user notification on user_save

I can't find a way to do that. user_save doesn't take such an argument. I believe you have two options.

Emulate the user_register_submit() call by passing your data in as a form instead, this is preferably done with drupal_form_submit(). It just so happens that the example deals with user-registration.
Just kill outgoing e-mails while you import your users.


Including multiple authors in Authoring information for a Drupal 7 node

I accomplished this by the following steps:

Download and enable the Rules module and the Entity Reference module.
Add a field called "Foo" to your content type. Field type: Entity Reference. Target type: user.
Create a new Rule.

Add event: "Before saving content"
Add condition: Data comparison. Parameter: Data to compare: [node:type], Data value: bar (Where "bar" = your content type's name)
Add action: Add an item to a list. List: [node:field-foo], Item to add: [site:current-user]

Now every time content is saved, the user who saved it will be added to the list of editors of that page.


Query fieldCondition for custom content type

Assuming you're using the Email field module, the column name is email, rather than value.

If that's the case, just change that line to:

->fieldCondition('field_email_address', 'email', $email_address, '=')

You may need to make a similar change for the password field, depending on what type it is. The easiest way to check for valid column names is in the .install file of the module that provides it, within its implementation of hook_field_schema().


Template file not loading for block view

I seem to remember, in drupal 6 at least, that you need to have block.tpl.php there, even if you don't modify it at all, in order for the specific block templates to be seen.

ADD:  If it's in there, you might try a preprocess_block() hook with something like:

$variables['template_files'][] = 'block--mens-header';

stuck in it.  This should point it to block--mens-header.tpl.php in your theme directory.  Obviously, wrap that in some logic so it's only set for the block in question.


Why is my theme table row array not being displayed?

Try looking at it this way.  From looking at your $header, you are looking for 3 columns?

foreach ($obj_response as $response) {
if ($str_current_country == $response->country) {
  $rows[] = array($str_current_country, $response->wider_dissemination, $response->response);
}

EDIT

// Test Output
$header = array(t('Country'), t('Wider Dissemination'), t('Responses'));
$rows = array();
$rows[] = array('US', 'Extremely Wide', 'Response');
print theme('table', array('header' => $header, 'rows' => $rows));

The test works for me.  Maybe something in your response value is messing with it?


A start:

1) Yes.

Note: If I really want to know what is going over the line, I use fiddler (Windows).

2) See function drupal_build_css_cache() in common.inc (line 3603). You cannot influence the level but you can influence whether it compresses or not with variable 'css_gzip_compression', see default.settings.php line 432.

BTW: You do not want to influence the compression level: for compress once, use many cases, maximum compression is always the best. Transfer time and decompressing time at the client is linear with compressed document size. So a 1-time slightly increased performance hit will save a lot of network activity and client side processing in the future.

3) -

4) -

5) Compression will be better as it will be done only once and it will be done better versus mod_deflate that will compress on each request and therefore will use a lower compression level. I don't know much about mod_deflate, but I guess that if there is already a  Content-Encoding header that tells the content is compressed, mod_deflate should not touch it. But I have had cases where I got a backup file that was compressed twice, so mod_deflate might not be that smart and should  explicitly be told to do so.

6) There is no point, but there might be for other requests, especially dynamic ones, i.e. non cacheable pages. Note that only aggregated css and js and cached pages (variable 'page_compression') are compressed by Drupal. Non cacheable pages are not compressed by Drupal.


hierarchical select does support this feature. Just to conform you have created the field with term reference and set a proper vocabulary which has parent and child relation. and while creating the field you have selected widget as hierarchical select. Please follow this approach.


How to add google analytics code for onclick functions in drupal 6

What you're looking for is the GA Event Tracking module. It allows your custom module to select web page elements (via CSS selectors), bind them to jQuery events (e.g. clicks, mouseover, etc.), and send them out to the GA Event Tracking API.


How to reference identical files on multiple nodes?

One way to do this is to use the Media suite which provides a media browser from which you can select existing files. Media also allows to add fields to your files to add additional meta data to them. The current UI in Media 7.x-1.x is unfortunately not what you could be, there are e.g. no filters in the media browser.

An alternative, as suggested in the comments, is to create a content type with just the uploaded file and then reference that node instead of the file. I'd say this is more the 6.x-like way to do this, but it does work as well...


How to add a conditional billing field based in Country in "Commerce Kickstart"?

I don't think you can use conditional fields because of the internal structure of the addressfield module, you need to use some custom code here, using the #states property and checking against the value of the country.
Using hook_form_alter, you can edit that form, here's an example of #states coming from the examples module:

  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),
    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );


How to save node form data in form_values using drupal_execute

If I understand right you basically want to clone a node later? If this is the case than you can just:

$nid = $the_nid_of_the_old_node;  //get the $nid of the old node
$new_node = node_load($nid);      //load the old node object
$new_node->nid = NULL;            //unset nid to tell node_save that this is a new node
// do what ever you need to the new node
node_save($new_node);             //save the new node

That should do it.


Is there a way to get multiple image sizes from a single image?

By default, any file you upload via the file field goes into the public files directory /sites/default/files. And you can choose to apply any image style to the same image and configure it separately per display.

E.g. Let's say you upload an image with name my_beatiful_cat.jpg from a file field on a node page.

The image by default will stay at sites/default/files/my_beatiful_cat.jpg.
From manage display of the content type, in the default view, let's say you choose the image style to be medium and save.
When you view the node, a new image will be created from the uploaded image at sites/default/files/styles/medium/public. So, you will have a file sites/default/files/styles/medium/public/my_beatiful_cat.jpg which will have the dimensions as per the image style applied.
This is true for any other image style that you apply for any other display.

So, you only upload an image once. Image styles are responsible for generating images with respective sizes as per the configuration and the appropriate image file is rendered.


This is how i sort my entityListBuilder :

i use the method load() :

  public function load() {

    $entity_query = \Drupal::service('entity.query')->get('produits_entity');
    $header = $this->buildHeader();

    $entity_query->pager(50);
    $entity_query->tableSort($header);

    $uids = $entity_query->execute();

    return $this->storage->loadMultiple($uids);
  }

Then i build my header like this :

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {

    $header = array(
        'id' => array(
            'data' => $this->t('N° produit'),
            'field' => 'id',
            'specifier' => 'id',
            'class' => array(RESPONSIVE_PRIORITY_LOW),
        ),
        'nom' => array(
            'data' => $this->t('Nom'),
            'field' => 'name',
            'specifier' => 'name',
        ),

        'prixHT' => array(
            'data' => $this->t('Prix HT'),
            'field' => 'prixHT',
            'specifier' => 'prixHT',
        ),

        'statut' => array(
            'data' => $this->t('Actif'),
            'field' => 'actif',
            'specifier' => 'actif',
        ),

    );

    return $header + parent::buildHeader();
  }

you need to add in your buildHeader() 2 param for each field you want sort :

  name of field and specifier


Drupal 8 - "Implement menu links as plugins", trying to build a menu tree

You may need to render it as below:

  // Build the main menu links tree.
  if (!empty($vars['main_menu'])) {
    // Build links.
    $config = Drupal::config('menu_ui.settings');
    $menu_enabled = Drupal::moduleHandler()->moduleExists('menu_ui');
    // When menu module is not enabled, we need hardcoded default values.
    $main_links_source = $menu_enabled ? $config->get('main_links') : 'main';
    // Allowed max depth.
    // @see MenuTreeStorage::MAX_DEPTH
    $level = 9;
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($main_links_source);
    $parameters->setMaxDepth($level);
    $tree = $menu_tree->load($main_links_source, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);
    $vars['main_menu'] = $menu_tree->build($tree);
    $vars['main_menu']['#attributes']['id'] = 'main-menu-links';
    $vars['main_menu']['#attributes']['class'] = array('links', 'clearfix');
    $vars['main_menu']['#theme_wrappers'] = array('menu_tree__primary');
  }

P.S: Make sure you clear cache after update, as it looks like the cache-tag is aggressive and doesn't show same menu in all page at the first run.


Unpublished content is displaying in entity referenced fields

While adding entity reference field to the content type,

In Field Setting--> Entity selection-->Mode -->Select Views and create a view by filtering only Published content, and assign the same to "View used to select the entities *"

Hope this will help you in building views link


How to implement georeferencing in Drupal?

If you want to use an existing module - something like GMap is probably the easiest place to start.

That being said, the Google Map API is fairly easy to use, so nothing preventing you from writing a module that does exactly what you want.


Is there an installation package builder for Drupal?

You could make your own easily with the Drush Make module; the Profiler Builder module will tell you what to include in your make file.

This requires you have some knowledge of using drush.


how to find that there is a "Promoted to front page" node and load it in page.tpl.php?

You mean a custom function?

I did a lot of this for a current project where we needed short little lists of nodes with different criterion all over.  I found Views bulky and overkill in some places, so I added small functions to template.php.  They're really just simple SQL SELECT statements.

For example:

function home_channel_list($title, $tids, $limit){

    $query = "SELECT t1.nid, MAX(t1.vid), t1.title, UNIX_TIMESTAMP(t2.field_pubdate_value) AS pubdate
                FROM {node} t1
                    JOIN field_revision_field_pubdate t2 ON t1.nid = t2.entity_id AND t1.vid = t2.revision_id
                    JOIN field_revision_field_channel t3 ON t1.nid = t3.entity_id AND t1.vid = t3.revision_id
                WHERE t3.field_channel_tid IN(".$tids.")
                    GROUP BY t1.nid ORDER BY pubdate DESC LIMIT ".$limit."";

        $result = db_query($query);

        // Container div and title
        print '

'.$title.'
';

        // Article list
        foreach ($result as $record) {
            $mypubdate = format_date($record->pubdate, 'custom', 'F j, Y, g:iA');
            print '
nid.'">'.$record->title.'
';
            print '
'.$mypubdate.'
';
        }

        // Clear and close the container div
        print '

';
}


how to have block show up on specific pages AND specific content types

The Context module makes advanced block placement very easy in the ui. In your case you would:

Download Context and enable Context and Context UI,
go to admin/structure/context,
click add,
give your context a Name in machine name format (no spaces, use lowercase and underscores) ie. my_context
Under "Conditions" add a condition of "Node Type"
Select your Content Types
Add another condition, of "Path"
Enter the specific paths that you would like the block to appear on, one path per line
Add a "Reaction" of type Block
Check your block or blocks off to the right and click the "+ Add" button in the region that you would like to place the block.


If end date is empty show "Now" or "Current" or something else

Have a look at Custom Formatters module.

"The Custom Formatters module allows users to easily create custom CCK/Field Formatters without the need to write a custom module."


How to make field label as node reference link?

I propose to do so (if you have a module Display Suite):

Go to ../admin/structure/ds/view_modes

Add a view mode: name is "label" and entities: "Node"

Then go to ../admin/structure/types/manage/your-content-type/display and on "Custom display settings" tab check the "Label" mode

Now go to ../admin/structure/types/manage/your-content-type/display/label select "Reset" (ds_reset) Layout, then make visible only the "Read more" and customise it: "Link text" - "See details" for example...

Then on referenced content type select "Rendered entity", and "View mode" - "Label"

Done!


error when trying to clear the cache in drupal

If the on option is grey, it means the module is required by another one. Deleting it will cause other modules to break. The correct thing to do would be to disable the depending modules, then disable the main modules and then go to the 'uninstall' tab and uninstall the module.

But for now try running update.php (drush updb) first and see if it helps. If not. Uninstall the modules properly, install the previous versions, disable and uninstall the previous versions and then install new versions again.

This works in most cases.


Webform2pdf and CiviCRM fields: pdf empty

In a Webform, CiviCRM fields are webform fields. There is no difference as far as Drupal is concerned. The only exception is CiviCRM credit card fields (which you really don't want to store in the webform submission).
The "existing contact" field is another special case, but although it gets processed a bit differently it is still a "real" webform field and ought to work fine.
So aside from the above I can think of no reason why any CiviCRM-related fields would not appear on a PDF.


Node token in rules (Events: When an order is first paid in full)

You can have a node token for that action, but you must load one manually using Fetch entity by id.


How can I dynamically set the site URL (in Drush9+)?

I don't see how you can easily reproduce that (nice) configuration setup since the yaml files are indeed static.
The only solution I see is to write a little wrapper script that always calls drush with the --uri option, like:
drush --uri $MY_SITE_URL_VAR $@

Recommended solution
A much simpler solution is to use the shell variable DRUSH_OPTIONS_URI.
export DRUSH_OPTIONS_URI=http://example.com

I wasn't able to find any documentation for this, but it seems to work.


Facing trouble in insertion of data in to table after creating table by using hook_update_N function

If you're using drupal_write_record, be aware of this warning in the documentation

  Do not use drupal_write_record() within hook_update_N() functions, since the database schema cannot be relied upon when a user is running a series of updates. Instead, use db_insert() or db_update() to save the record.

You should be using db_insert or db_update instead.


How do I programmatically validate reCaptcha?

I figured out myself. The only thing i had to do is to add in #limit_validation_errors element another array with captcha_response.
So the right syntax is

$form['actions']['continue_button']['#limit_validation_errors'] = array(array('name'),array('captcha_response'));


Now you can use ShareThis with both Google+ and Facebook Like.
Go to Menu>Configuration>Web Services>ShareThis

Go to Choose services to pick Google Plus One or Facebook

or

Go to Extra services to pick Google Plus One or Facebook Like

You can also see details how to set this up directly in the html code here.


You can use [node:field_calendar_date:custom:l, Fd, gia], if [node:field_calendar_date] is a date token. In that case, [node:field_calendar_date:custom] returns the date in the custom format listed after the following colon. The format string is the one accepted by date().

If you want to use the format set as short/medium/long format set in the Drupal date settings, then you can use the following tokens:

[node:field_calendar_date:short]
[node:field_calendar_date:medium]
[node:field_calendar_date:long]


Changing the field date type from 'datetime' to 'unix timestamp' without losing data

The strtotime() php function will be helpful for converting date to unix timestamp


How do I programmatically change contextual filters?

Args should be concatenated with , or +.

This work:

  $term = Term::load($tid);
  $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')
    ->loadTree($term->getVocabularyId(), $tid);

  foreach($terms as $child_term) {
    $args[0]  .= ',' . $child_term->tid;
  }


Drupal::request()->request->all() returns an empty array

Try this:

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

Sidenote: Using a Controller you shouldn't use "\Drupal::..." static request call. Instead, you always have in your controller's enter point function a "Request $request" object as a last argument.


Video Embed Field: Check All My Videos on existance?

the quickest solution is to query the DB and export all youtube video IDs.
After you can write a custom PHP script to check if the video exists.
Here is an example of the code you could use: https://stackoverflow.com/a/21069917

A more Drupalistic approach is to write a custom module which do the same thing. For example it could implement a drupal cron task or a batch procedure to verify each Youtube field content using the code suggested before.

I hope this suggestion will be helpful.


Passing values in view block to contextual filter on Panelized Node

There is a patch that may add this functonality: How to manually pass an argument to a views block through interface.


How to find out whether or not a page is cached?

Whether a page is cached

You can enable logging and use varnishlog, varnishstat, etc. See Debugging Varnish for a bit more information. There's also a lot of information on Pantheon's Working with Varnish, I'd highly recommend reading that.

Why it is not cached

That's a much bigger, harder question to answer. It's entirely down to your server/application logic. Your server's VCL files, in conjunction with response headers sent from your Drupal application, will determine whether or not a page is cached.

There may be other environmental factors affecting things, but again those would be specific to your server and your sysadmin (or whoever installed/set up the server) should be able to tell you about them.

There's a pretty decent tutorial available that walks through setting up Varnish with Drupal, I'd recommend reading through that and comparing your own set up to that known-to-be-working one.


Is there any way to show a progress bar during loop iteration in a rules?

I found the solution.

At first I must appreciate Eyal who gave me key point .

I used module named "rules_batch" in https://www.drupal.org/project/rules_batch and it solved my problem.


Reset Drupal 7 Site: NIDs, Revision VIDs, Taxonomy Term and Categories, etc

Delete all module does what you want :)

  This module is used to delete all content and/or users from a site.
  This is mainly a developer tool, which can come in handy in several
  cases, listed below.


How do I translate British English strings into US English?

First, I'm not sure about what this means "I cannot see any of the strings from my custom module." ... so my answer here may not be useful.  but here goes:

Machines don't care about what the similarities are, variations of english might as well be chinese and spanish.. which works in our favour here!

Assuming (US) english is your primary/default language,  translate only the strings you want in to the Queen's English:  admin/config/regional/translate/translate

You may have to do some interesting stuff to make detection/selection work,  but I think that's a new question.


How to get a same result of Views with Random Sort Criteria

if its in the same context, you can assign a variable and print it twice

$output = views_embed_view("library","block_0",$term->tid);

print $output;
print $output;

if that is not the idea, you could simply do what views_embed_view() does manually by loading the view first which gives you access to the content, and then calling the preview - here's the code from the function:

function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}


How to use Rules to restrict the edit and delete options if a field has value "approved"?

Under permissions give the role ability to update only their own content. Then set a rule when node is published, author of role is set to another site user? That would be a quick implementation.


In Drupal 7, it was straight forward possible by implementing hook_custom_theme() in your custom module.

As for Drupal 8, you will need to create a ThemeNegotiator. Link to the respective change record : 'theme callback' and hook_custom_theme() replaced by theme negotiators.

In the applies() function of the class you can apply your logic and return the theme you wish to have in the determineActiveTheme() function.

Note that, you might have to create multiple ThemeNegotiators for multiple conditions.


node_save() casing 500 Internal Server Error - 48s when using with AJAX

Sorry, I don't have enough reputation points to comment so I should post this as an answer.
Obviously your 500 error comes from the script. The node_save($node); does not cause your error, it's just the trigger.
If you want to follow the best coding practices, you should use try and catch blocks to catch your errors before you try to modify your database.
If the "dblog" module is activated you could follow the error stack to debug your script or else you could comment out all of the lines that are assigning new values to your variables and start re-executing your script by uncommenting one line at the time utill the error is reproduced.
I hope that this helps a bit. We have all been there. Cheers.


Changing video content type (mime type) in CDN

Found the Answer :

1)  "A MIME-TYPE is a server side setting. You can ask your hosting provider to add the MP4 MIME-TYPE for you.

Or, you can add a .htaccess file to the directory where you uploads are stored".

A sample .htaccess file that adds the MP4 MIME-TYPE is:

<IfModule mod_rewrite.c>
  AddType video/mp4 .mp4
</IfModule>"

Source : Need to Change Video Content Type to video/mp4 so it plays in IE

But this did not work for me for some reason

2) I did the change in my core class file which i was using in drupal module for CDN upload
I had made a change in my class.s3.php file -> in mime_type[] array and also, cross checked with putObject() function.

**

  Setting of mime type is always done in coding side and not in AWS S3
  bucket, We need to use AWS PHP Class file or sdk to do the
  manipulation in mime type or make the necessary changes in core class
  file (eg. class.s3.php )

**
 For details check here find-mime-type-of-file-or-url-using-php-for-all-file-format

Second Answer has worked for me :)


How to retrieve last MySQL INSERT ID from db_merge()

While there is RETURN_INSERT_ID which can be used with db_query(), I could not find a way to use with db_merge().

<?php
  $query = "INSERT INTO {table_name} (col1, col2) VALUES (:arg1, :arg2)";
  $args = array(':arg1' => $val1, ':arg2' => $val2);
  $last_id = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));
?

I think you will have to retrieve the last ID with another query, but you would need to check with MergeQuery::STATUS_INSERT.

$status = db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->execute()

if( $status == MergeQuery::STATUS_INSERT ) {
      $last_id = db_query("SELECT LAST_INSERT_ID()")->fetchField();
}


Customization of Facebook style Statues module

I think you want Facebook-style Micropublisher this allows you to have a image present if the URL your connecting to allows it.


Add more than 2 profile in Civicrm contribution page

There's no way of doing this through the user interface.

An alternative approach would be to use a Drupal webform integrated with CiviCRM. You'll need the Webform module, the webform_civicrm integration module, and various dependencies.

Depending on the payment processor you are using to process the membership payment, if indeed you are using any, you can then build a form that will include all the CiviCRM fields you need without needing to create profiles.

If you are using a payment processor and accepting online payments for you memberships, IPN-based processors, such as Paypal standard, aren't supported by this approach, but you can get around that by having the user taken from the webform through to a basic CiviCRM contribution page and they can make their payment there.


Drupal 8 css and images relative to root

Core actually did exactly that change just a few days ago, it will be like that in 8.0.3.

That said, your set up looks problematic to me, that's not going to be the only thing that somehow relies on the domain name. Usually the same domain is used?


Ultimate Cron installation Table 'db_name.ultimate_cron_log' doesn't exist

I ran the following to fix the issue.  Manually create tables.
CREATE TABLE 'ultimate_cron_log' (
  `lid` varchar(176) NOT NULL COMMENT 'Lock ID',
  `name` varchar(166) NOT NULL COMMENT 'Name',
  `log_type` int(11) NOT NULL DEFAULT '0' COMMENT 'Log type',
  `start_time` double NOT NULL DEFAULT '0' COMMENT 'Timestamp of execution start',
  `end_time` double NOT NULL DEFAULT '0' COMMENT 'Timestamp of execution end',
  `uid` int(11) NOT NULL DEFAULT '0' COMMENT 'User ID',
  `init_message` text COMMENT 'Initial message',
  `message` text COMMENT 'Message',
  `severity` int(11) DEFAULT '-1' COMMENT 'Max severity level of the execution',
  PRIMARY KEY (`lid`),
  KEY `idx_last` (`name`(80),`start_time`,`end_time`,`log_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Logs';
CREATE TABLE 'ultimate_cron_lock' (
  `lid` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'Lock ID',
  `name` varchar(166) NOT NULL COMMENT 'Name',
  `current` bigint(20) NOT NULL DEFAULT '0' COMMENT 'Current lock',
  `expire` double NOT NULL DEFAULT '0' COMMENT 'Expiration time of lock',
  PRIMARY KEY (`lid`),
  UNIQUE KEY `idx_name` (`name`,`current`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Locks';
CREATE TABLE 'ultimate_cron_signal' (
  `job_name` varchar(166) NOT NULL COMMENT 'Name of job',
  `signal_name` varchar(166) NOT NULL COMMENT 'Name of signal',
  `claimed` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Is signal claimed',
  PRIMARY KEY (`job_name`,`signal_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Signals';


`Drupal\DrupalExtension` extension file or class could not be located

The Drupal Extension requires no modules, only composer installation.
Execute:
composer require drupal/drupal-extension='~3.0'
See the docs for other setup information: https://github.com/jhedstrom/drupalextension/blob/master/README.md
Update
to install the latest version just use
composer require drupal/drupal-extension

[version 3 is kind of outdated and in this time latest version is 4.1]


Custom webform validation handler not getting called using Event subscriber

You should use a custom webform plugin handler for that.

More information here: https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-add-custom-validation-to-a-webform-element


Generate PDF with Print PDF and send in email

Try this modules:

Views PDF

  With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.

https://drupal.org/project/views_pdf

Views PDF Mime Mail

  This module provides the integration of Views PDF and Mime Mail.
  This allows the user to send a View as a PDF to a customer by Rules.

https://drupal.org/project/views_pdf_mimemail


Print full node url escaping special characters?

The proper way to generate a URL is with the url() function, and the absolute option:

$absolute_url = url('node/123', array('absolute' => TRUE));

You then need to encode it:

$encoded_url = rawurlencode($absolute_url);

This work should be done in a preprocess function, and the variable added to $variables, and not done in the .tpl.php file directly:

function MYTHEME_preprocess_node(&$variables) {
  $absolute_url = url('node/123', array('absolute' => TRUE));
  $encoded_url = rawurlencode($absolute_url);

  $variables['encoded_url'] = $encoded_url;
}

and then printed in the template.

<?php print $encoded_url ?>

However, you more than likely want to use the query option or drupal_http_build_query  for whatever you are trying to use this for.  What you are describing typically isn't needed directly.  Giving the proper advice, though, is a little hard without more context.


How can I add background music to an existing Drupal 7 website?

I'm looking at doing the same thing for a band's website where the music can keep playing even when switching pages. AJAX is definitely the way to go here.

Check out the pjax for Drupal module.

  pjax is a jQuery plugin that loads new content into the current page without a full page load. This is usually quicker and smoother than a full page reload, because Drupal only has to deliver the main page content and not the full page – and the browser only has to redraw a smaller amount of markup.

  In addition to this, pjax updates the page URL with the proper page path using HTML5 pushState – not with #url-fragments that are commonly used with ajax-loaded content. It also updates the page title with the title of the loaded page. In other words, it has all of the benefits of standard page loads (permalinks, SEO), while taking advantage of partial page loads in the browser.


Here is the method I used. It covered all of the functionality I needed, and we ended up with a very robust website, using popular well maintained modules, and getting the exact results we needed.

Modules used

Commerce
Commerce_agree_terms
Commerce_autosku
Commerce_cart_expiration
Commerce_event_ticket (For PDF creation)
Commerce_stock
Date API
Inline Entity Form
Rules
Views

These were the main ones. There are also modules these rely on, and others I used for other purposes. But I am trying to keep this to the ticket functionality only, rather than explain how to build an entire site.

Method

Enable all modules.
Create a commerce product called "Ticket" (Or re-name the default enabled product).
Manage the fields on the "Ticket" content type, and add a date field called "booking window". This should collect a start and end date, and will allow an admin to define when these tickets are available for sale.
Enable Commerce Stock on the Ticket Product to allow an admin to define the amount of tickets available for each ticket.
Create a content type called "Event".
Add an In-line Entity field allowing the user to create new products (Tickets). Allow unlimited values on this field if you wish (This allows a user to add an Early Bird Ticket, Standard, VIP etc.). We also disable "Allow a user to add existing products" as we want unique products to be created for every event. This is where the autosku module comes in handy for auto generation.
Add a date field for the event date.

Once that is done, you have the basic functionality. You can create an "Event" node, add a ticket or multiple tickets (defining price, stock and booking window), add your event date and click save.

Next Steps

Next you will need to manage the display for the content type "Event" and hide the display of the tickets field.
Create a new view Block Display called "Ticket Display" for products. Add a field to show products (Tickets) as an add to cart form.
Add a contextual filter "nid" and set the default value as "get content ID from URL".
Add a filter to the view for the product (Tickets) booking window start date and use relative date "now" to only show products with a start date less than "now" and another filter with end date greater than "now".
Go to structure > blocks, find your view block display, and restrict the block to only show on "event" content types. This will now mean the tickets only show on their referenced nodes, and only if the booking window is open. They will also be disabled if out of stock.

Adding a ticket holders names

Manage the fields of the line items. Store > Configuration > Line item types > Product (Ticket) > Manage fields. Add a field for "Ticket holders name".
On the "Ticket holders name" field settings, make sure you select "Include this field on Add to Cart forms for line items of this type".

Sending tickets to customers

After enabling the commerce event ticket module, follow the modules instructions to generate a PDF for every ticket product.

For a full working demo of this, look here.. http://www.dev.thelhp.co.uk/ Please note this site is in development for now, but will try and charge you when it goes live!


Creating a node programmatically for a user who doesn't have the permission to create nodes of that content type

If the code calls node_save() passing to the function a node object that is associated to user Y (i.e., the value of node->uid is the user ID of user Y), the function will save  the node without checking if a node of that content type can be created from the user. It is the code that calls node_save() that eventually checks if the user has the permission of creating that content type, or it's the code that shows the link to the form for creating a node of a content type that makes the link visible only to users who has the permission to create nodes of that content type.

node_save() allows you to save a node that is associated to a user who don't have the permission to create a node of the content type Y; the problem is eventually when the user X doesn't have the permission to update nodes of the content type Y, which would not allow the user to update the node that has been created for him.


Bootstrap site, not mobile friendly anymore

In your page's <head>, somehow the viewport got removed.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Without this, Bootstrap in general and @media in bootstrap.css don't know what width the screen is initially.

This should generally be auto-generated or put into html.tpl.php.


Use custom form submit function inside class

To understand why your code is not working, you need to understand how the form API works:

The form definition is called
Any form alter hooks are executed, altering the form
The render array is cached
The form is rendered as HTML and sent to the browser
The user submits the form
Drupal checks that the submitted values match the cached form. If values do not match, the values are rejected by Drupal's security system

When you call this code:

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

The caching mentioned in step 3 above has already happened. So when you do this after that line of code:

$form['actions']['submit']['#submit'][] = '::_custom_submit_form';

The submit handler is never called, since the form was cached before this line of code, and therefore your submit handler does not make it into the cache.

To add a submit handler to a form, you need to implement hook_form_alter() (or a variation), which will add the handler before the caching happens. Or, you can extend the form class you are working with, add your own ::submitForm() handler, then call the parent submit from that.


Webform live calculations in table/matrix

Refer to Filter form submission data by a field value with Views, Webform for a tutorial to display the data collected by Webform in a filterable, tabular format, using the Webform module (of course), and the Views module.

After you created an appropriate view, you could consider either of these approaches:

Add the "Views Calc" module to add the "live sums" that you're looking for. Here is an excerpt from its project page:

  This module adds simple calculations to a views table. Requires the Views module.

  You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

And this is a typical screenprint using the Views Calc module:

Refer to my answer to "Total count of two different content types in one View?" for more details about how to use the Views Calc module.

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
Use the Views Summarize module. Here is an excerpt from its project page:

  Enables an extra display style which displays summaries of a column on the last row.

There isn't a lot (any?) documentation available about actually using this module, but the "clue" is like so: Click on the "settings" icon for the display style, then enable a summarizer on one of the columns.

Refer to the project's home page for a screenprint of a view using this module.
Addd the calculation via custom logic in views templates, as explained in one of the answers to the question about "How can I add a summary row to a Drupal View?". Here is a quote from that answer:

  ... Create a views-view.tpl.php for your view, and then edit it calculate and print out the summary.

  Another option is to create another display for the same view, and then create a views-view-unformatted.tpl.php and calculate and print out the summary w/o doing a print $row; to avoid calling the fields template. Then add use view display where needed.

Note: the extra clarification (requirement?) about "live" only got added after I wrote most of my answer. I.e. via a comment like "... something client side that updates as the user fills in the form without submitting it first". So far I'm not aware of any module that ALSO supports that. Not sure if there is a way to do that using the "Views templates" approach described above (if there is such way, please add another answer related to that also).


Form ajax add more button added via another ajax callback not working

@NabajitRoy my idea is

Never use drupal_render() manual calls (return $form array as-is)
Move all the form generation code into form constructor( create_report_form() ), AJAX
callback should not create new elements for form but only
create_report_form() should
AJAX callbacks should only return element form (not generate them)
e.g. return $form['attributes']['submit'] and may be
$form_state['rebuild'] = true; if needed.
To know in create_report_form() if it was called by AJAX request
button check the $form_state['triggering_element'] in it.
I feel that using '#type' => 'submit' instead of '#type' => 'button'
is better

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


Moving content fields to different theme regions with display suite

Try the cck_blocks module.
Once installed, you can enable field blocks per field via the field settings page.

Then in the display settings, hide the field in the default/full view and show it in the cck blocks view mode.


Creating simple user groups with a term in Drupal 7

Since users are field able you can now attach a taxonomy term reference field to users.
Create a view that list all users where the tid of the term reference is a select value. You could also get the value from a url arg.
The view itself should show the user data you want to display, maybe as a list or whatever fits you better.
In the views header you could display the info about taxonomy term. Right now this will require some views knowledge and some custom code, as you need to create what views calls an area handler, to display the info. You could also do this in a preprocess function instead.


Multisite isn't really meant for situations where you want to share content.  This is what Domain Access module does.  Essentially, it allows you to have different behaviors for a site with subdomains, but running from the same database.  This is different from multisite, which uses a different database for each site.  I would try starting with that before you go down the road of multisite.


Is there a way to display current "event" or "show" in date/calendar modules?

Basically, you want to tell views to display nodes with starDate <= *NOW* AND endData >= *NOW*. i.e. if now is 11:50, a program from 11 - 12 should be displayed.
This could be done fairly easy via views, following are two screenshots of the two filters you're gonna add to the view:

Hope this helps.


How can I have links to anchors in menus?

Add/edit a menu link
Enter  /test#anchor in the "Link" field
Save the link
You're done, make tea :)

Point being - fragments are accepted as part of the link in Drupal 8.

One exception seems to be the home page; it doesn't work with the <front> token, nor /#anchor. The fragment isn't rendered in either case.


CKeditor adding an extra  tag when a  tag is encountered

As it turns out, disabling the option: Convert line breaks into HTML (i.e. <br> and <p>) in the text format does make a difference. I needed to flush the cache to see the results. Hopefully this will help other people who experience this problem.


You should read Drupal 7's new multilingual systems compilation. There's even a full book about that matter: Drupal 7 Multilingual Sites.

When using a single Drupal instance to create a multilingual site, there are two different approaches: Content Translation and Entity Translation (Read: Node translation vs. Entity (field) translation). You may want a multi-site setup (With Domain Access or without it), especially if you require independent content to appear (not only translations). And the Internationalization suite of modules is a must, it provides the following modules:

Path Translation
String Translation
Taxonomy Translation
Block Translation
Variable Translation


Config for using PUT with Services Module

There is no configuration needed in drupal to accept put requests the web server may be refusing PUT requests and requires some configuration see why-does-my-web-server-software-disallow-put-and-delete-requests for more information about this issue.

Try curl and see response example below

  curl -X PUT  the request

The advanced rest client s chrome extension I prefer to use over others.


Have the '@domain.com' part of the email fixed

You can achieve this using the hook_form_alter API. Alter the email field with something like $form['field_email']['#default_value'] = '' . '@company.com';

That will always append the @company.com to each email entered.


After a long research I got the answer how to do this.

/**
 * Implements hook_theme().
 */
function mymodule_theme() {

return array(
'my_field' => array(
  'render element' => 'element',
  //  'template' => 'field--field-progress',
  //  'variables' => array('element' => NULL, 'field' => NULL),
   ),
  );
 }

Than render the field as below_

function theme_progressbar_field($vars){
  $element = $vars['element'];
  $output = '';
  $output .= '
';
  $output .=' ';
  $output .='
';
  $output .=''.$element['myfield']['#value'].'%     ';
  $output .='
';
  $output .='
';
  $output .='

';
  $output .='
';
  $output .='' ;
  $output .= '
';
  return $output;
}


Uncheck the Display links and add the below line in your node.tpl.php present under your themes folder sites/all/themes/yourtheme

<a href='<?php print $node_url; ?>'>read more..


Drupal Commerce age gate on Add to Basket?

First you can add a popup callback for certain products in the add to cart form alter.

e.g.

function my_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
    // if this is the alcohol
    $form['submit']['#ajax'] = array('event' => 'click', 'wrapper' => 'age_check_popup', 'callback' => 'my_module_age_check');
}

function my_module_age_check($form, &$form_state) {
    ctools_include('modal');
    ctools_modal_add_js();
    $commands = array();
    $commands[] = ctools_modal_command_display('title', theme('my_module_age_block'));
    print ajax_render($commands);
    drupal_exit();
}

Then you'll need to handle the clicks in the popup to either add the product or cancel (just close the popup).

You could do this via hook_menu() callbacks or by rendering a form with buttons in the popup.

Edit:

Implement hook_theme() to create a new template file for your popup content.

e.g.

function my_module_theme($existing, $type, $theme, $path) {
    return array(
       'my_module_age_block' => array(
          'template' => 'my_module_age_block'
        ),
     );
 }

Then add a template file my_module_age_block.tpl.php and put your HTML content in here.


Obtaining the node type being added with php

If you are changing the form used to create a node, then you could use the following code.

function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    // The node is being created.
    // Use $node->type to get the content type of the node.
  }
}

The reason is that node_add(), the page callback for the node creation form, contains the following code.

  $types = node_type_get_types();
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE,
  );
  drupal_set_title(t('Create @name', array('@name' => $types[$type]->name)), PASS_THROUGH);
  $output = drupal_get_form($type . '_node_form', $node);

This means that the form used when creating a node is the node edit form.

As alternative, if you need to change the node creating form when the content type is, for example, article, you can use the following code.

function mymodule_form_article_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    // The node is being created.
  }
}

As in this case the form is altered only when article is the content type of the node, you don't actually need to check the content type.

If you need that information in other cases, then you can only get it from the URL.


Change the amount of content displayed per page in Content Management -> Content

Use Views to generate a list of all your contents, create a new view of type node, add fields what you like, then use Views Bonus Pack to export content list as CSV.


I could write a massive answer here, but I'm just gonna post this link: Never hack core!

The main reason I guess is that if you hack core to do something you need, and then update it...BANG!  Your changes are gone. Lost. You could then try and roll back the code from your VCS, but seeing as you can't roll back database upgrades from Drupal core - you're looking at restoring all code from VCS, and then restoring databases from your backups. All the time you're trying to roll back your code, you'll probably then notice that your last pre-update database backup failed, and you'll swear more than you've ever sworn before.

Also - most importantly - if you hack core, then Dries and Webchick both kill a kitten :-o


How do I get line breaks when using Plain Text format?

This seems like a Drupal 7.x bug.
Changing the order of filters doesn't work in my case.

My short term solution was to throw this inside my theme's template.php (ref):

<?php
/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$vars, $hook) {
  // Add line breaks to plain text textareas.
  if (
    // Make sure this is a text_long field type.
    $vars['element']['#field_type'] == 'text_long'
    // Check that the field's format is set to null, which equates to plain_text.
    && $vars['element']['#items'][0]['format'] == null
  ) {
    $vars['items'][0]['#markup'] = nl2br($vars['items'][0]['#markup']);
  }
}
?>

For fields in views, it's needed to set this option separately in the "Rewrite Results" section of the field settings.


Cache tags for all entities of a certain type

You could use the module handy_cache_tags, then you would have this type of tags:

handy_cache_tags:[entity_type]
handy_cache_tags:[entity_type]:[entity_bundle]


How to get the values from a formatted field in inc file

How do I get the value without that , basic html part?

$node->field_name->value; should do the trick.

  I can resolve this in the twig file by getting this as {{fieldname|raw}}.

Using | raw filter in twig is bad security practice, see How do I get the raw field value in a twig template? for a safe solution.


Disable autofill username & password on drupal

Auto-completion of common fields (text, password, select, textarea, date-related, time-related, numeric, email, and uri controls) is a browser feature but you can tell browsers to turn off auto-completion on form fields by using the autocomplete attribute.

You can use hook_form_alter or hook_form_FORM_ID_alter to add this attribute to your fields.

Example:

/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'YOUR_FORM_ID') {
    $form['YOUR_FIELD']['#attributes']['autocomplete'] = 'off';
  }
}

Example altering the log-in forms:

function example_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'user_login_block': // Log-in block form.
    case 'user_login': // Log-in form.
      // Username
      $form['name']['#attributes']['autocomplete'] = 'off';

      // Password
      $form['pass']['#attributes']['autocomplete'] = 'off';
      break;
  }
}

You can check out these posts for more info on module development - Module Developer's Guide and Creating Drupal 7.x modules. You can also download the excellent Examples module for reference.


After some more research, I found a post by nicholasThompson who was having the same problem and found out the solution:

  Ahh you have to place the "Content field" block and configure it!

This solved my issue.


How to provide free tagging ability when saving nodes using services

In D7, a taxonomy term reference field with the autocomplete widget uses JSON like this:
"field_tags":{"und":"Foo,Bar"}"
When it is an autocomplete, the term name needs to be used instead of the term id for free tagging it will simply create the term.


If you would be okay with having a parameter in the url control your view mode then you can add this code to your custom module using hook_entity_view_mode_alter().

For example:

http://www.yoursite.com?view_mode=Full

http://www.yoursite.com?view_mode=Teaser

.....

/**
 * Implements hook_entity_view_mode_alter().
 */
function my_module_entity_view_mode_alter(&$view_mode, $context) {
  // If there is a view_mode parameter in the url change the view mode to it.
  if (isset($_GET['view_mode'])) {
    $view_mode = $_GET['view_mode'];
  }
}