How do I add a menu item to the main navigation from a custom module in Drupal 8?

You are missing the "menu_name" key as said on : https://www.drupal.org/node/2122241

this example should work :

demo.demo:
  title: Demo Link
  description: 'This is a demo link'
  parent: main
  route_name: demo.demo
  menu_name: main


Multipart Form Fields - Taxonomy Included

You can use Field collection module

Tutorial:
Using Field Collection In Drupal 7


Seperate /user/register fields and admin/people/create

Probably hook_form_FORM_ID_alter on user_register_form then some logic like

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

  // Is logged in user admin.
  if (user_access('administer users')) {

    // Hide myfield.
    $form['myfield']['#access'] = FALSE;
  }
}


How do I theme the "The website encountered an unexpected error" page?

The errors in Drupal 7 handled by includes/errors.inc file, and the The website encountered an unexpected error. Please try again later. error use the maintenance_page theme see from includes/errors.inc

print theme('maintenance_page', array(
        'content' => t('The website encountered an unexpected error. Please try again later.'),
      ));
      exit;

So if you want to theme the error page, you theme the maintenance_page to do so take a look at Theming the Drupal maintenance page.


The body is not cached on its own, but as part of cached nodes for logged in users or of cached pages for anonymous users. This is what you have already disabled with the code.

You can check this in the cache metadata. Render elements with cache keys get cached. If there is no cache key, then the cache tags, contexts and max-age are bubbled up and merged until they reach an element that has cache keys. This element is then cached including all merged cache metadata that is nested inside.

That means, that cache metadata you set in the body will have no effect on the body to be cached or not, but change, how elements on higher levels like the node or page are cached. For example a cache tag in the body will be included in the tags of the node and the page and if the tag gets invalidated, the cached node and page will both be invalidated.


How to change transition to fade on Boostrap Carousel module?

you could do that with CSS transitions so it can be done easily without any Javascript.

The CSS:

.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}

I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.

Very smooth.


Naming Structure for Create Node Page template?


To pass variables to the zone template, you need to preprocess the zone, not the node

function mymodule_preprocess_zone(&$vars) {
  $vars['node_type'] = 'some_type';
}


Date Popup does not translate date format

Salve!
You only need to configure this in the field's settings, under MORE SETTINGS AND VALUES.

Here is a screenshot that shows that the option you are looking for is available in the drop down list:

Hope this helps.


How to adjust prices depending on quantity and attributes using Drupal Commerce?

Module comparison

I'm not familiar with any other such pricing related modules. It seems to me that you will have to decide between these options:

A stable module (aka the price "table" module).
A module that's on the horizon (aka the price "list" module).

Whenever I have to decide between multiple modules, I often use the (23) criteria that I ever documented in "maintenance scorecards" (within the Community documentation). Those scorecards are actually "applied" to charting modules, but the same criteria can be used, I think, to mostly any type of module comparisons.

I'd be happy to provide some more details (via a next iteration of my answer), but if I was to decide I would definitely go for the stable, commonly used price "table" module. The major "red flag" (= no go) for the newer "list" module is criterium nr 26 (downloads vs reported installs ratio). Correct me if I'm wrong, but only like 10 % of downloads seem to have resulted in sites that continue using it.

Rules is your friend

I would definitely also consider the Rules module, using some custom Rules, something like so:

Events = Calculate Sell Price of Product.
Actions = calculate the price, and set the price to the calculated value.

Not sure (yet) if you'd need some extra 'Conditions' added to this.

Refer to Drupal commerce and rules: changing the product price dynamically for an example of dynamically changing product prices.

Create your own custom Rule

If for some reason you can't get it to work with the Rules module, then I'd consider writing my own custom Rule(s), similar to what is described in Drupal custom Rules how to write your own events conditions, actions and custom object.

The main steps that are detailed in this tutorial are further described below (with the code included below quoted from that link).

Part 1: Defining the Event, Condition and Action

Define the Rules Event

/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_package_bought' => array(
      'label' => t('A package was bought'),
      'module' => 'your_module',
      'arguments' => array(
        'acting_user' => array('type' => 'user', 'label' => t('The user who bought the package.')),
        'package' => array('type' => 'package', 'label' => t('The purchased package.')),
      ),
    ),
  );
}

Define the Rules Condition

/**
 * implementation of hook_rules_condition_info()
 */
function your_module_rules_condition_info() {
  return array(
    'your_module_condition_package_type' => array(
      'label' => t('Type of the package'),
      'arguments' => array(
        'package_id' => array('type' => 'value', 'label' => t('The type of the purchased package.')),
        'package_type' => array('type' => 'string', 'label' => t('The type of the purchased package is')),
      ),
      'module' => 'your_module',
    ),
  );
}

Define the Rules Action

/**
 * Implementation of hook_rules_action_info().
 */
function packages_rules_action_info() {
  return array(
    'your_module_action_change_order_status' => array(
      'label' => t('Change the order status'),
      'arguments' => array(
        'order' => array('type' => 'value', 'label' => t('The order object.')),
      ),
      'module' => 'your_module',
    ),
  );
}

Part 2: Coding the custom Event, Condition and Action

Event:

Somewhere in your custom module, you need to include logic to trigger the event, with something similar to this example (note the your_module_package_bought in it):

  //here the code for buying a package will be located
  //when that code returns that a package was bought trigger the rule
  $order = order_load($oid);//$oid will be the id of the order made
  $package = package_load($pid);//pid will be the id of the bought package
  global $user;
  rules_invoke_event('your_module_package_bought', $user, $package, $order);

Condition:

To evaluate the Rules condition (to check if it is TRUE or FALSE), the function your_module_condition_package_type is executed using the arguments provided. Here is an example of how such function could look like:

function your_module_condition_package_type($pid, $type) {
  $package = package_load($pid);
  return ($package->type == $type) ? true : false;
}

Action:

Somewhere in your custom module, you need to include logic to perform the actual action, in this example it should be done within the function named your_module_action_change_order_status.


Large parts of the question doesn't actually make sense to me, but...

If you want to pass an arbitrary part of the URL as a string to a View, just assign that variable part to a string in the argument settings, and then set that argument, %url_from_string, as the argument to the View.

The better solution though, would be to create a new context type called 'content type', because I don't think a context like that is available out of the box, and then assign the argument to that instead. That allows you to do validation of the incoming context and gracefully handle an argument that's not valid.

A third solution, though mostly a workaround, is to tell the View to pull it's arguments directly from the URL. This setting is available for all content pane displays under their argument settings.


Warning message and URLs not found on menu items

The warning looks like a PHP incompatibility. So either fix the code that's been triggering it (and at best provide a patch for it on drupal.org) or change MAMP's PHP version. Probably to something lower as it is now.

The URL not found error looks like as if you misconfigured your .htaccess file. Ensure this file exists and maybe uncomment the following line.

RewriteBase /


Trying to keep facets visible even when the terms restrict facets

How do I keep facets visible in Apache Solr even when there are 0 results?

As I know, it's not possible. You can make separate query for display facets, but they cannot be displayed if solr return no data.


How to make an uploaded video visible on the node page in drupal 7

Have you tried using the Video module. You can create field type video insted of type file and then upload and render with the player you have configured.


How to determine the priority of css files in info file for a theme?

The CSS files are processed in order, so if your .info file looks like this:

stylesheets[all][] = css/foo.css
stylesheets[all][] = css/bar.css

Then the styles from foo.css will be included before those from bar.css. The same applies whether each CSS file is included separately, or whether they're aggregated.

If you're still unsure which rule will be applied at that point, you need to read up on CSS specificity, as Drupal doesn't affect it.


Contextual filters with Entity reference

The contextual filter should be "content:nid"

The options should be set as follows...

  The Relationship should be your "Entity Reference: Referenced Entity"
  relationship

  Under "When the filter value is NOT available" check "provide default
  value" and select "Content ID from URL"

  Apply changes and save view.

I think this is the same thing Renee was saying, just in other words.

Hope this helps - I recently lost a weekend to figuring this out ; )


How I'm doing this now

Create a new content type, Landing Page.
Add two fields, an entity reference to Places and an entity reference to Main keywords.
Use Views blocks/Layout Builder to rewrite the HTML of the content type to show the text you want with the relevant keywords substituted in.
When you add a new term to either vocabulary, you have to create all the possible combinations manually by adding Landing Page content.


Just tried it out myself and for me it didn't work using your malformatted #attributes array. After I fixed it the following did work. class must provide another array.

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $build['mybutton'] = [
    '#type'       => 'button',
    '#name'       => 'mybutton_name',
    '#value'      => t('Click Here'),
    '#attributes' => ['class' => ['button', 'button--primary']],
    '#weight'     => -11,
  ];
}


Import/export configuration and translations

The translations are not part of the configuration.

You can configure and export the source of translation files. One option is to have the local filesystem as the source. The translation files are stored locally in the sites/default/files/translations directory, but can change this directory on the File system configuration page.

What you could also configure and export how frequently you want to check for new interface translations for your currently installed modules and themes. At
/admin/config/regional/translate/settings

Check for updates

Never (manually, this is the default)
Weekly
Monthly

You can manually download the translations at:
/admin/reports/translations/check?destination=/admin/reports/translations


How to avoid _0 _1 when editing a media entity and changing the file?

Use the Media Entity File Replace module.  This is the exact use case it was created for.


Loading in JavaScript that requires custom vars

If the settings are global and don't vary per use, I'd implement hook_library_info_alter() and dynamically set the path there. JW Player does something like that: http://cgit.drupalcode.org/jw_player/tree/jw_player.module?h=8.x-1.x#n206

Remember to clear the cache when the settings are changed, so this is updated.

If it's something completely dynamic, or per user or so, you have to either write JS to load it or embed the js tag yourself, e..g with html_head.


First of all try to take a look at the buildForm method in the UserPasswordResetForm class, it takes some parameters.
So you must call getForm like this:
\Drupal::formBuilder()->getForm('Drupal\user\Form\UserPasswordResetForm::class', $user, $expiration_date, $timestamp, $hash);

This is the function docs,

$user = User requesting reset.
$expiration_date = Formatted expiration date for the login link, or NULL if the link does not expire.
$timestamp = The current timestamp.
$hash = Login link hash.

So when those parameters are added the form should render perfectly.


What is the best way to submit form values and output on an unthemed page?

If you want to break out of the theming system and display your own markup for a page you can do so.

Simply print whatever you want in your callback and rather than returning the content do an exit;

It isn't very elegant but it will do the job.


Concatenate fields in a view with comma when values may be empty

I would actually suggest doing the reverse of the answered question that you linked to for just the scenario you are describing.

Add Field B and Exclude it from the display.
In the Rewrite results area of Field B, enable Rewrite the output of this field.
On Field B, add a comma and the token for the raw value: ', [field-b]'
Under 'No Results Behavior' for Field B, make sure that 'Hide if empty' and 'Hide rewriting if empty' are checked.
Then rewrite your Field A to include Field B: '[field-a][field-b]'. Make sure there is no space, so that the comma will immediately follow Field A if Field B has a value.


Load the node as EntityInterface not NodeInterface

Node has EntityBase in its hierarchy. EntityBase implements EntityInterface. This means you can pass a Node to a function that expects EntityInterface, since Node extends a class that implements that interface. This is how OOP works, and why classes are type hinted with interfaces (eg. EntityInterface) rather than a specific class (eg. EntityBase).


You can do it by using this

function yourtheme_preprocess_page(&$vars) {
  if(drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/your-front-script.js');
  }
}


How can I get newly created node of a certain type?

The equivalent of hook_nodeapi('insert') in Drupal 7 is hook_node_insert().

function hook_node_insert($node) {
  db_insert('mytable')
    ->fields(array(
    'nid' => $node->nid,
    'extra' => $node->extra,
  ))
    ->execute();
}


If you've enabled the search bar component on Admin menu you can search your way to it.

Enable the Search Bar component on the configuration page (/admin/config/administration/admin_menu).
Type "flu.." or enough characters to list only the "Flush all caches" menu item.
Press the tab key to highlight and the enter key to trigger the "Flush all caches" menu item.


adding panel to select field in content type

As mentioned in one of the comments I used the hook_form_alter but instead of pulling in the panel I just created another function to get the information and used that as the options for my select.

  function gacms_magecp_content_type_edit_form($form, &$form_state) {

   $conf = $form_state['conf'];
   $categories = gacms_magecp_categories();

    $form['magecp'] = array(
     '#type' => 'select',
     '#options' => $categories,
     '#title' => t('Mage Category Product'),
     '#default_value' => isset($conf['magecp'])?$conf['magecp']:'',
     '#format' => isset($conf['format'])?$conf['format']:'full_html',
    );

    return $form;
  }

   function gacms_magecp_categories(){
    db_set_active('magento');

    $result = db_query("SELECT entity_id, name FROM catalog_category_flat_store_1");
        while ($row = $result->fetchAssoc()) {
           $content[$row['entity_id']]= $row['name'];
        }
        db_set_active();
        return $content;
    }


CRUD operations on site from external application

I use a custom module to do this very thing in D7. It works like this:

The internal applications write to a transaction log (a database table) reflecting changes that will need to be added/edited/deleted on the site.
A simple API app exposes this transaction log over the Internet, with API keys.
The Drupal site reads new transaction log entries (it remembers the last log entry it synchronized) from the API then queues and makes the node changes when cron runs.

You could do something similar in D8. Or, considering Drupal 8 has a RESTful API, you could instrument your internal application to make synchronous changes to the Drupal site.


States visibility in type select and radio in drupal 7

Try this code

$form['basic']['legal_form'] = array(
  '#type' => 'select',
  '#options' => array(
    'option1' => 'option1',
    'option2' => 'option2',
    'option3' => 'option3',
  ),
  '#title' => 'My Dropdown',
  '#attributes' => array('id' => 'selection_id'),
);

//radio button to show if selected option3
$form['basic']['bearer_shares'] = array(
  '#type' => 'radios',
  '#title' => 'Radio Button to show',
  '#options' => array(1 => t('yes'), 2 => t('no')),
  '#states'           => array(
    'visible' => array(
      'select[id="selection_id"]' => array('value' => 'option3')
    )
  )
);


How to call helper function from my_module.admin.inc file in drush command?

The module_load_include() function can be invoked from Drush; it sounds to me as if some other parts of your Drush setup might not be working properly.

Here's a sample Drush implementation, similar to what you want to do:

/**
 * Implements hook_drush_command().
 */
function YOUR_MODULE_drush_command() {
  $items['your-full-command'] = array(
    'callback' => 'YOUR_MODULE_hello_command',
    'description' => dt('Description of your Drush command.'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'aliases' => array('your-alias1', 'your-alias2'),
  );

  return $items;
}

/**
 * Command to download the Chosen plugin.
 */
function YOUR_MODULE_hello_command() {
  // Include your file.
  module_load_include('inc', 'YOUR_MODULE', 'includes/YOUR_MODULE.admin');
  // Invoke your function.
  _helper_func();
  // Show a message to the screen.
  drush_log(dt('Custom command executed.'), 'success');
}

You can see a working example in my custom module boilerplate.


The git command is git clone. You would type:

git clone <repository-url> path/to/modules/module_name


How to sql-sync prefixed multi-site installations within the same database with drush?

sql-sync does not support prefixed database tables.  There is work going on in the issue queue to support removal of cache tables via wildcard expressions. Perhaps this code could be adapted to support prefixed tables as well, if a motivated contributor would write and submit a patch.


simplenews-newsletter-body.tpl.php won't be overridden

The file may need to go in the admin theme folder, if you're using admin theme/sections, and not in the regular theme folder. Worth a shot.


a way to do that :

create customcron.php in the drupal root with the content :

<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

// Load cron service and run cron.
\Drupal::service('cron')->run();

$kernel->terminate($request, $response);

then run :

php customcron.php

i would not let the file customcron.php in the root because anybody could then execute it from the browser.

A simple way to avoid that is moving the file customcron.php to drupal root only for the time you execute it or maybe have an unguessable file name instead of customcron.php


How do I show login form to anonymous user when accessing particular form

Logintoboggan will allow you display a login form when a user hits an access denied page:

  Provide a login form on Access Denied pages for non-logged-in (anonymous) users.


How to change the length of field settings?

Dylan Tack solution is the easiest, but personally I enjoy exploring the inner wards of Drupal's database to seen how things are managed down there.
So, assuming you have a text field which machine name is field_text of 10 characters you want to grow to 25:

data will be stored in two tables: field_data_field_text and field_revision_field_text
definition is stored in field_config for the storage data, and field_config_instance for each instance of this field (stuff like label).

Now let's do a little heart surgery.

Alter the data tables columns definitions:
ALTER TABLE `field_data_field_text`
CHANGE `field_text_value` `field_text_value` VARCHAR( 25 )
CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;

ALTER TABLE `field_revision_field_text`
CHANGE `field_text_value` `field_text_value` VARCHAR( 25 )
CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;

Change the definition column, this one is very tricky because it's stored in a BLOB, but that's not something that will stop you for doing this.

Dissect the guts of this BLOB thing:

SELECT CAST(`data` AS CHAR(10000) CHARACTER SET utf8)
FROM `field_config` WHERE field_name = 'field_text';

This will give you something like:

a:7:{s:12:"translatable";s:1:"1";s:12:"entity_types";a:0:{}s:8:"settings";a:2:
    {s:10:"max_length";s:2:"10";s:17:"field_permissions";a:5:
    //a lot more stuff...

This is a PHP serialized array, the interesting part is s:10:"max_length";s:2:"10";, this mean this array has a property named max_length (which name is a 10 characters string - hence the "s") which value is 10 (which is a 2 characters long string). It's pretty easy, isn't it?

Changing its value is as easy as replacing the s:2:"10" part by s:2:"25". Be careful: if your new value is longer in character length, you have to adapt the "s" part accordingly. For example putting 100 will be s:3:"100" as 100 length is 3 characters.

Let's put this new value back in the DB, don't forget to keep the whole string.

UPDATE `field_config`
SET data = 'a:7:{...a:2:{s:10:"max_length";s:2:"25";...}'
WHERE `field_name` = 'field_text'

Flush your caches.

???

PROFIT!

By the way, PhpMyAdmin has some setting to allow direct modification of BLOB columns, but why go the easy way?
PS: This can also save your life when putting some PHP code in views and getting a WSOD because of an error in your code.


Get view result with sorting option programmattically

You could check this sample code. It contains additional methods in Views that you could use like in the line:

//Here we can alter the order
//$view->set_item('default', 'sort', 'random', NULL);
if(isset($alter['node_created_order'])){
  $view->add_item('default', 'sort', 'node', 'created',array('order' => $alter['node_created_order']));
}


Where is the file selection widget in Drupal code?

The code to generate a field upload form element is in theme_file(). The code is very simple because all it does is to output an HTML file select form element. As explained in other answers, the files browsing dialog is provided by the web browser and, most of the time, re-uses the operating system native one.


Javascript Not Functioning At All on Drupal 7

Check that in html jquery.js and drupal.js correctly open - just click on links in firefox html source view, it's should open js files.
Check your jquery.js and drupal.js in misc folder, if files exists, compare with drupal archive.
Check how many jquery-VERSIONS.js files attached in html, possibly conflicts can be there.
Check your html source for embedded js scripts (viruses like it).


In a View, does the order of pages/blocks/attachments matter? & Why isn't my block showing up?

You likely arent providing the argument to the view in any fashion it can use it. Try not hiding the view but echoing the args to the view title or header and see what you are getting. Please consider using panels module or providing default arguments to your view instead. This works if the arguments are simple like node/user/term id.

If you post more specifics about your actual conditions i can help.


create a webform node with multi lingual language

You can use Internationalization module to achieve this functionality.

  This is a collection of modules to extend Drupal core multilingual
  capabilities and be able to build real life multilingual sites. Some
  features:

  Taxonomy translation (both, per language terms and translatable    terms) Multilingual variables
  Multilingual blocks (control visibility per language and translate    title and content)
  Language selection (when you switch the site language you'll see only    the content for that language)

Edit:

You need to set up translate of each node. If you create node/2 as defualt language French, then you edit the node and click on translate tab in top of page and set up translate node in spanish language.

If you view node/2 and select spanish language, then it will display the trasnlated node of node/2 in spanish language.

Setting language:

Go to the Languages page (Administration > Settings > Language in
Drupal 6, or Administration > Configuration > Regional and language >
Languages in Drupal 7) and add and enable desired languages.

Setting Multilingual for content type.

Go to the Content types administration page (Administration >
Content > Types in Drupal 6, or Administration > Structure > Content
types in Drupal 7).
Select a content type you want translated, and select "edit", then
"Workflow settings" for Drupal 6 or "Publishing options" for Drupal
At the "Multilingual support" section, select "Enabled, with
translation". Be sure to save each content type after enabling
multilingual support.


search block form not accepting special characters in drupal 7

The error has nothing to do with special characters (e.g. "$", "@"). It pertains to the length of your keywords. By default, Drupal core search restricts minimum keyword size to 3; any query less than 3 characters will trigger the error (e.g. "$9").

If you really need search to include 2/1 character queries, the search settings in /admin/config/search/settings under the Minimum word length to index option will allow you to do this.

Note: This will expand out the size of your search index (catching common words like "an" & "a"). If you have a large site with thousands of nodes you shouldn't do this.


List all groups where the profile owner is a member?

You should have a view that comes with OG called "OG User groups". If you clone that view and change the contextual filters to "Content ID from URL", or change your current view to reflect the provided one you should be good.

If you don't have access to the view these values should work:

Contextual filters
OG membership: Entity id

Relationships
OG membership: Group Node from OG membership


add a class to page depending on order total (Drupal Commerce)?

I came up with this piece of code, which seems to work:

function class_price_preprocess_html(&$variables){
  global $user;
  $order = commerce_cart_order_load($user->uid);
  if ($order) {
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $line_items = $wrapper->commerce_line_items;
    $total = commerce_line_items_total($line_items);
    if($total['amount']>5000){
        $variables['classes_array'][] = "class-pr";
    }
  }
}


Check if the user has permissions to use that node's input filter.

If that is OK, try rebuilding the content permissions.


Views has a field:

  Content: Published
  Whether or not the content is published.

You should be able to add that to your Field based View to show the published status.


Modifying page title with THEME_preprocess_page_title

I think you are looking in wrong place. As far as i remember, in Drupal 8 title is rendered trough block called page_title_block

function MODULE_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'page_title_block') {
    $color_title = str_ireplace('some text', 'Some TEXT', $variables['content']['#title']);
    $variables['content']['#title'] = $color_title;
  }
}


add css class to html element based on taxonomy?

You can do this by adding a preprocess function to your template file that detects if the current node has terms associated with it and if so, populates a variable for the page.tpl.php according to your logic, ex:

function YOURTHEME_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $node = $variables['node'];
    if (!empty($node->field_tags)) {

      #your taxonomy logic here, if term matches your case then assign it to variable
      $variables["custom_taxonomy_page_class"];

    }
}

Then, in your page.tpl.php file in your theme, you just need to add the above variable where you want it in the HTML tag.

<html xmlns="http://www.w3.org/1999/xhtml" class="$custom_taxonomy_page_class">

If the variable is empty, no class will be output.


Profile2 regpath move account email field, into profile2 form and handle submit

Found solution here: move fields in the user profile form in fieldsets

But I also needed to add the submitted $form_state mail value, back to the location it would have originally existed.

function si_student_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  // remove fieldgroups and tabs for anonymous users, e.g. /student/register
  if($user->uid == 0) {

    // move email field from account to below profile2 name fields
    $email = $form['account']['mail'];
    unset($form['account']['mail']);
    // add email to profile
    $form['profile_student']['mail'] = $email;
    // change weights
    $form['profile_student']['mail']['#weight'] = 3;

    // replace original validation handler
    $form['#validate'][0] = '_si_student_register_anonymous_validate';
  }
}

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

  // add field back to account
  $form['account']['mail'] = $form['profile_student']['mail'];
  // add submitted value from profile2 submission handler into default mail value location
  $form_state['values']['mail'] = $form_state['values']['profile_student']['mail'];
  // call validation function with update field
  user_account_form_validate($form, $form_state);

}


hierarcical select not apply parent restriction

eventually i found  this is a bug in hierarcical select module, and the
patch in here

i hope this  be useful.


You can do this using an <iframe> element within a custom formatter for a file field.

Field formatters control the output of a field: it's what lets you choose whether to display a generic link, the file name, etc. What you can do is create one that displays the PDF within an <iframe> element.

To do this, you need to (at a minimum) implement two hooks: hook_field_formatter_info() and hook_field_formatter_view():

/**
 * Implements hook_field_formatter_info().
 */
function sandbox_field_formatter_info() {
  $info = array();
  $info['sandbox_formatter'] = array(
    'label' => t('Inline file'),
    'description' => t('Display the file within an iframe.'),
    'field types' => array('file'),
  );
  return $info;
}

/**
 * Implements hook_field_formatter_view().
 */
function sandbox_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  // Create the proper markup for each item within the field instance
  foreach ($items as $delta => $item) {
    $path = file_create_url($item['uri']);
    $element[$delta] = array(
      '#markup' => '<iframe src="' . $path . '"></iframe>',
    );
  }
  return $element;
}

Then you can create a file field, set it to only allow PDF, and choose Inline file as the display format. When you view a node with a PDF, you'll see the PDF within an <iframe> element.

The above is a very basic, minimal example: for an intermediate example that shows how to implement formatter settings, check out Dan Linn's tutorial. Also be sure to check out the relevant API pages, which includes sample implementations even more advanced than Linn's:

File Types API
hook_field_formatter_info()
hook_field_formatter_view()
hook_field_formatter_settings_form()
hook_field_formatter_settings_summary()

As an aside, it should be noted that there are a couple of related modules:

Iframe: creates an <iframe> element formatter, but it hasn't been ported to Drupal 7 yet.
Custom formatters: claims to allow the creation of custom formatters without needing to create a custom module


Add HTML5 required attribute to webform fields set as required

You will need to create a module for this.
Note that, this answer assumes you need to set required attribute on all form elements which are required in web form settings.
you will need to implement a different hook and/or add conditions to make this strict.

Create a file named webform_formalters.info and put following to it.

name = webform form alters
description = a collection of custom form alters for webforms.
core = 7.x
package = Custom
dependencies[] = webform

Create another file named 'webform_formalters.module' and put following in it.

<?php
/*
 * implements hook_form_BASE_FORM_ID_alter.
 */
function webform_formalters_form_webform_client_form_alter(&$form){
  //dsm($form);
  foreach ($form['submitted'] as &$field){
   if (is_array($field) && isset($field[#required]) && $field['#required'] == 1){
     //dsm($field);
     $field['#attributes']['required'] = 'required';
   }
  }
}

Put both files to a folder named webform_formalters and upload to your site's module folder and enable the module. See if it works.

Unlike other forms, web forms' fields are stored in $form['submitted'] array. So we go through each item (which should be an array of form definitions) and check if the element has marked as required.
if so, we add or merge required attribute. We are altering an existing form, so we are not going to pop out existing attributes.

Good luck!


what are the different ways to use the variable in many functions within a module?

variable_set

  sets a persistent variable.

  Case-sensitivity of the variable_* functions depends on the database
  collation used. To avoid problems, always use lower case for
  persistent variable names.

variable_get

  Returns a persistent variable.

  Case-sensitivity of the variable_* functions depends on the database
  collation used. To avoid problems, always use lower case for
  persistent variable names.

variable_del

  Unsets a persistent variable.

  Case-sensitivity of the variable_* functions depends on the database
  collation used. To avoid problems, always use lower case for
  persistent variable names.


How to invalidate cache when a config entity is added/deleted?

List fields support an allowed_values_callback setting, if you use that, then you don't need to worry about cache invalidation.

See https://api.drupal.org/api/drupal/core!modules!options!options.api.php/function/callback_allowed_values_function/8.2.x and


It looks like what's happening is your text format settings are stripping the JS out of the page. You can edit the formats by going to /admin/config/content/formats, or you may just need to select a different format for the node in question (under the body field when you edit the node).

If you need the JS available on several pages, have a look at: https://www.drupal.org/node/304255.


you might want to serialize that array or json decode it, than it can easily be passed as a string.


How to create a family tree structure of nodes?

I'm assuming you've tried to use the Views tree module (there doesn't seem to be a "trees views" module ...). To my knowledge, that module cannot create a graphical visualisation of a tree structure.

I'd recommend to create such tree structure using Graphviz diagrams, and use the Graphviz Filter module. Some more details about this module (from its project page):

  ... a little filter that treats input text as DOT syntax for Graphviz, converts it using Graphviz tools to the requested format(s) and renders it in HTML. It's useful to quickly create graphs dynamically from within Drupal nodes.

For more information, refer to the Community Documentation about Graphing Modules, which has a list of modules for creating either Static or Dynamic Graph Diagrams.


How to perform action after a file is deleted?

I believe you can use FileField; this module is now part of Drupal 7 core, and provides additions to the API, such as hook_file_delete().


How do I add an additional “Cancel account” operation link?

It can be achieved by rewriting operation links field in views:

edit
cancel


If I understand your use-case properly, as far as I know everybody uses Pathalogic for this.


create panel page for taxonomy term page

I was able to get this to work with the latest dev versions of Panels and Page Manager. Here are the key pieces:

Disable the Taxonomy term view.
Set the path on the panels page to /taxonomy/term/%.
Clear cache.
View page at taxonomy/term/{tid}.
I verified that this also works with URL aliases.

One thing to keep in mind: If you use selection conditions (e.g. by Vocabulary), terms that don't satisfy the selection conditions return a 404 (which may or may not be what you want). There is an issue on Drupal.org for providing a default fallback.


Creating two entities at once using entity metadata wrappers

Without saving the first entity i dont think its possible.

This is KO :

  // Create the first entity.
  $page = entity_create('node', array('type'=>'page'));
  $entity_page = entity_metadata_wrapper('node', $page);
  $entity_page->title = 'page test!';
  //$entity_page->save();

  // Create the second entity.
  $article = entity_create('node', array('type'=>'article'));
  $entity= entity_metadata_wrapper('node', $article);
  $entity->title = 'article without reference KO';
  $entity->field_paage = $paage;
  $entity->save();

This is OK :

  // Create the first entity.
  $page = entity_create('node', array('type'=>'page'));
  $entity_page = entity_metadata_wrapper('node', $page);
  $entity_page->title = 'page test!';
  $entity_page->save();

  // Create the second entity.
  $article = entity_create('node', array('type'=>'article'));
  $entity= entity_metadata_wrapper('node', $article);
  $entity->title = 'article with reference OK';
  $entity->field_paage = $paage;
  $entity->save();

with the second code you have 2 entity (article and page) with the first node page is a reference for the content article.

What you need is save in the first time your file object.

To Update some fields (tested) :

  $wrapper = entity_metadata_wrapper('user', $user);
  $wrapper->mail->set('sepp@example.com');
  $wrapper->field_first_name->set('First name');
  $wrapper->save();


Show various nodes in different ways on home page in drupal7?

Welcome to Drupal StackExchange !

You can build various views of same content using Views module in Drupal. You can follow this link to know more about the views module and also Views Documentation in the project page.


Code to output individual fields in a Theme view

OK,
I sorted this out. I didn't quite understand that I need to make layout changes in the appropriately named views-view-fields--viewname.tpl.php. I was hoping to just add some php to the page.tpl.php theme file I have developed for my views.

It's quite a learning curve with Drupal!


"The value in Date is not a valid date" error

The latest dev version of clientside validation contains a fix to support more formats, so you can give it a try


How to change the style of the pages title in a view?

Open firebug to see what are the ancestors of the h1, there should be a name that contains the content type or view, you can easily set:

.WRAPPER-OF-CONTENT-TYPE h1{
    //here is your css style
}


Ubercart particular item has extra shipping fee domestic vs international

You can try UC Multiprice

  This module allows you to set a different product pricing for each
  enabled country in Ubercart. It also got support for roles, currencies
  and i18n

Its only in dev version use at your own risk.


There are two different fields:

Group visibility. It only exists for Groups. It controls whether all group content is visible to non-members by default.
Group content access. It only exists for Group content. It controls whether a particular node in the group is visible or invisible to non-members, or whether it should leave that decision to the default setting of the group.

Check whether your group has a group visibility field and whether you have the permissions to edit it, and if not, add that field via /admin/config/group/fields and grant the right permissions to edit it.


It looks like a barcode is just a piece of encoded text from the .module file:

/**
 * Implements hook_field_info().
 */
function barcode_field_info() {
  return array(
    'barcode_field' => array(
      'label' => t('Barcode'),
      'description' => t('This field stores a barcode in the database.'),
      'default_widget' => 'barcode_textfield',
      'enable_tokens' => 1,
      'default_formatter' => 'barcode_default',
    ),
  );
}

So what you likely want to do is creating link fields that upon form submission pass their values onto the barcode field(s) as well. Then, you will show the barcode field(s) on any pages you want and hide the raw link field from the users view (unless their editing the entry).

You could look at the Rules module to automate this for you if you don't want to write a module (for example, when a new piece of content of type Foo, if field link is blah, copy field value to field my_barcode value). Look into the Form API to hide (with #access)the field_barcode values in the edit form (as they are dynamic end-user stuff).

The only thing that the Link field gives you over putting the raw url link in the bar_code field itself is extra form validation for free (for example, check it is a valid URL).


How do I create a link to add a new entity form from the referenced entity

The entity_connect module will do that for you.


Calendar Prev/Next buttons linking to wrong dates

drush dl date --select
Choose one of the available releases for date:
 [0]  :  Cancel
 [1]  :  7.x-2.x-dev  -  2015-Jun-16  -  Development
 [2]  :  7.x-2.9-rc1  -  2015-Mar-27  -  Supported
 [3]  :  7.x-2.8      -  2014-Jul-29  -  Recommended, Security
 [4]  :  7.x-1.x-dev  -  2013-Sep-30  -  Development

So if I have 7.x-2.8 - It's okay.   7.x-2.9-rc1 or  7.x-2.x-dev  both jump ahead by two months.drush dl date --select

Of the ones available, dev and rc1 have an issue with the next button. 2.8 is fine but it defaults the calendar name to include the first day of the month. So you must choose between a bad title format or a bad next button.

My solution: I moved back to Date 7.x-2.8 and then overrode date-views-pager.tpl.php in my theme with the following:

<div class="date-nav-wrapper clearfix<?php if (!empty($extra_classes)) print $extra_classes; ?>">

<?php
        print date("F", strtotime($nav_title))
            . ' '
            . date("Y", strtotime($nav_title));
        ?>


How to display the user picture on the search page?

Copy the file YOUR_SITE/modules/search/search-result.tpl.php to your theme and modify the code inside with this:

<?php
//obtaining the username
$username = explode('(', $title);
$username = trim($username[0]);
//getting the user object
$user = user_load_by_name($username);
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>

  <?php
  /*
   * The following line will print the user picture
   */
  print theme('user_picture', array('account' =>$user));
  ?>

  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

  <?php print render($title_suffix); ?>

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>
    <?php if ($info): ?>

<?php print $info; ?>

    <?php endif; ?>

This will be the output:

EDIT: If you want follow another way you can read this: How to access to the user info on the search page?


Custom Drush command and Settigns::get(), Config::get()

Get is not a static method, so it should not be called statically (using ::). Use Drupal's service container and get the config service using \Drupal::service('config'), then get your config from that.


How do I change the text of the "View" and "Edit" links on the user account page?

As I know you can't do it in your theme, but it is possible to do in your module.

/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  // Change title for user profile's tabs.
  foreach ($data['tabs'] as &$tabs) {
    foreach ($tabs as &$tab) {
      $route_name = $tab['#link']['url']->getRouteName();
      if ($route_name == 'entity.user.canonical') {
        $tab['#link']['title'] = t('View profile');
      }
      elseif ($route_name == 'entity.user.edit_form') {
        $tab['#link']['title'] = t('Edit profile');
      }
    }
  }
}


Need to migrate large, complex Drupal 6 site to Drupal 8. Suggestions for a good way to tackle this if the core Migrate Upgrade doesn't work for me?

I guess it depends on what your Drupal 6 does and contains. It's not the same if your complex site has lots of content but little functionality (a large blog, for example), or if it has some or lots of content AND complex functionality (news site publishing workflow with rules, complex permissions, etc). Every case is different.

If what you have is lots of content, this could apply: I recently moved lots of content (around 26k items that became nodes) from a Frankenstein WordPress-based app, and found the following approach useful:

Do exhaustive pre-production:

Make an inventory of everything you have in your old site. Mark what is valuable and what is not.
Based on that inventory, design the entities, fields, taxonomy and relationships that will contain them in your D8 instance.
Make a detailed migration map that makes it explicit how each fragment will map to its new location, and what will be left behind / lost.

Then implement your migration tools:

Export your content (the things you decided are worth migrating) to XML, JSON, or whatever format you feel more comfortable with.
Instead of messing with migration modules, I wrote several drush scripts that read from the old app's db, extract items and save them into entities.
The scripts had reset, migrate_all and type-specific migration routines that helped me test again and again and again, until everything was just right.
Automate everything and make it easy to clear and repeat. There are lots of things that can go wrong, but it's not a problem if you can simply ./reset.drush; ./migrate_all.drush.

Hope this helps.


How to change form_set_error() message in captcha module

Check out String Overrides module. It allows you to override any translatable string (anything that uses t()) and is very convenient for overriding some text that is shipped with other modules.

If you want to do it without installing new modules - uncomment and edit this in the settings.php file (line ~458):

# $conf['locale_custom_strings_en'][''] = array(
#   'forum'      => 'Discussion board',
#   '@count min' => '@count minutes',
# );


How to alter my query in hook_views_query_alter to use the right where expression?

I'm not 100% sure, but I think to add the "IS NULL" part, you may need spaces around "IS" such as:

$query->add_where('fee_schedule_payments', 'fee_schedule_payments.pid', 'NULL', ' IS ');

OR...maybe something using add_where_expression...

$query->add_where_expression(0, 'fee_schedule_payments.pid IS NULL');


You could use hook_mail_alter to alter the email message before sending it out. you could change or alter the email body, sender, attachments....etc as you wish


customize destination for user_login with modal_forms link?

You can checkout the following for ctools modal_form issues https://drupal.org/node/1329040 there is some code there that should allow you to set the redirect url using PHP to where you need it to go.

You should also double check that your modules are both up to date, there did not seem to be any open issues about computability between the two modules.


You could use the Rules module and the Webform Rules integration module to redirect to a generated URL.

You could create a rule that loops over the results building a custom URL string pointing to your processor script, and then redirect to that URL.

As long as the string is less than about 2000 characters you should be in good shape.

You may want to look into the Form API as this would be much cleaner and possibly simpler with a custom submit handler.

Form API Quick Start Guide
Form API Reference Sheet

If I misunderstood your question I would be happy to try again if you'll clarify.


How to create independent sections, which consits of menu and more pages automatically

Try with field collection module and divide groups of fields in sections as explained in field collection module documentation. You will get what you want!


Mocking Settings (settings.php) within Unit tests

At first glance Settings appears to be read-only, however the constructor is quite forgiving in its parameters. We can construct a fake settings structure like so:
$site_settings = [
  'http_services_api' => [
    'auth_services' => [
      'title' => 'Auth Services',
      'config' => [
        'base_uri' => 'https://demo.api-platform.com/auth'
      ],
    ],
    'resource_services' => [
      'title' => 'Resource Services',
      'config' => [
        'base_uri' => 'https://demo.api-platform.com/books'
      ],
    ],
  ],
];

new Settings($site_settings);

This is alluded too here but never fully described.
Edit: I have added an example to the docs linked.


Use Privatemsg admin form in theme (Missing functions!)

Though I suspect that this is an improper workaround, the solution was to hook a custom module's hook_init() function, watch for a system/ajax path and include the file if needed:

function MYMODULE_init(){
    if($_GET['q'] == 'system/ajax'){
        if ( preg_match('/privatemsg_list/', $_POST['form_id'])) {
            include('/great/big/system/path/web/sites/all/modules/privatemsg/privatemsg.pages.inc');
        }
    }
}

UPDATE: Answer is available at https://drupal.org/node/1961776! In short: use form_load_include() instead of module_load_include().


I managed to find a method for the webform entity class called getSubmissionForm. I found it in the webform module code in src/Entity/Webform.php

I invoked it like so

$webform = \Drupal::entityTypeManager()->getStorage('webform')->load('my_webform');
$webform = $webform->getSubmissionForm();

return $webform;

Which returned the specified webform rendered.


You didn't mention whether you are using ctools modal forms or a custom modal form.

For general form API submissions, the submit handler will only be executed when the form validation has passed, including the regular CSRF checks.

Suppose you have a form like this:

<?php
function my_form() {
  if (!empty($_COOKIE['Drupal_visitor_downloadbypass'])) {
    drupal_goto('download/able/file.here'); // rest of the page will not execute because drupal_goto ends the request.
  }
  $form['example'] = ...;// your form building goes here
  ..
  ..

  return $form;
}

function my_form_submit($form, &$form_state) {
  // $form_state['values']['example'] contains the submitted value of 'example' element.
  user_cookie_save(array('downloadbypass' => 1));
  $form_state['redirect'] = 'download/able/file.here';
}

If you are using a ctools modals, you can check the $form_state in your ctools form builder to do the same cookie check and redirect above.

Your ctools form builder can be as follows. Note the $form_state check.

<?php
function my_ctools_form_wrapper($js = NULL) {
  ctools_include('ajax');
  ctools_include('modal');
  $form_state = array(
    'ajax' => TRUE,
    'title' => t('My Ajax Form'),
  );

  $output = ctools_modal_form_wrapper('my_form', $form_state);

  if (!empty($form_state['executed'])) { // is the form submitted ?

    // Add the responder javascript, required by ctools
    ctools_add_js('ajax-responder');

    // Create ajax command array, dismiss the modal window.
    $output = array();
    $output[] = ctools_modal_command_dismiss();
    $output[] = ctools_ajax_command_reload();
  }

  print ajax_render($output);
  exit();
}


Basically this involves moving a region to html.tpl.php

So first you need to create a region to go in html.tpl.php which will hold your menu (unless you're using an existing region). Then create a preprocess in your template.php file:

function THEMENAME_preprocess_html(&$variables) {
  if ($blocks = block_get_blocks_by_region('REGION_MACHINE_NAME')) {
    $variables['REGION_MACHINE_NAME'] = $blocks;
    $variables['REGION_MACHINE_NAME']['#theme_wrappers'] = array('region');
    $variables['REGION_MACHINE_NAME']['#region'] = 'REGION_MACHINE_NAME';
  }
}

You need to replace THEMENAME with the name of your theme. Also replace all instances of REGION_MACHINE_NAME with the machine name of your region. The machine name can be found in your theme's .info file. Then all you need to do is put:

print render($REGION_MACHINE_NAME);

in your html.tpl.php (of course replace $REGION_MACHINE_NAME with the name of your region, I've only caps'd it to make it visible, it should all be lowercase otherwise)


Yes, you are on a right path. The Views module, and content types can be used to build a simple gallery for a user.

Create a content type called Image Gallery.
Add a image field to above content type.
Create a view called user gallery.
Filter by Content Type Image Gallery.
Filter by Node author: Logged in user, if you want to show logged in users Gallery.
Add the contextual filter Author UID, if you want to dynamically pass the user ID from the URL and filter the Gallery Images.
For above your view page path should be user-gallery/% where % will be user id.


Recurring events - retrieving/displaying the dates for the current "instance" of the event

I spoke briefly about this to a Drupal expert I know, and he suggested moving to using Views and the Fields view type as apparently the integration between the Date module and Views is very good.

At present, I'm using a View but also using Viewmodes and the preprocess field.  His point was that all of this could instead be accomplished by just using my existing content type, not using a custom viewmode but using the Fields view type.  And that this should be less buggy.


The revision table has been set up to track the revisions of a node.  Like Triskelion noted, there already is a thread up on D.O. Furthermore the reason the table is populated is for denormalization purposes, per The aforementioned issue.  Inevitably. this has some drawbacks.  The first of which is bloat.  Write speed is also affected, especially under a load.  The community has seemed to coalesce around using contrib to deal with this issue e.g. Field SQL norevisions.  At some point it would be nice to have this in core, but a rock solid contrib module is the next best thing.


Drupal commerce WPS , if user not go back to the site after paypal payment?

I was experiencing a similar problem - no confirmation emails etc.

Apparently what was causing the problem for me was that I had created a custom Rule that fired "When an ordered is first paid in full"  and updated the order status to "Completed." This custom Rule triggered after the user used PayPal WPS to complete payment. I did this to avoid the confusion of having the default status "Pending" after the the PayPal payment was successful.

For some reason, having this custom Rule there prevented all the Rules that use the trigger "Completing the checkout process" to trigger (these default rules include all the notification emails among other things).

See this posting here for a few cases of other people who ran into this problem: https://drupalcommerce.org/discussions/1150/resolved-completing-checkout-process-not-firing

This issue was resolved (in my case) by just getting rid of the custom Rule.

I'm wondering if this is causing the problem for you too.


Exposed view filtering on a related node's value

When adding a new relationship, ensure that you select 'Require this relationship'. Also, when adding a filter, ensure that you select the relevant relationship from the list where necessary.


How to customize the url of a field in views?

The problem was the way that Content: All taxonomy terms required a rewrite to [term_node_tid-tid]. Otherwise it would display the term name instead of the tid.


Permissions based on multiple OG groups?

It's not possible out-of-the-box.  Organic groups access control basically says if a user is in one group they can see the content in that group.

However you could write your own hook_node_access that evaluates the logic you described.


how to optimize setting theme suggestion for different languages?

Check the example in hook_theme_suggestions_alter() for language (second one below)
You can add more specific suggestions by appending the content type.


Node routes are declared using what is known as a route provider.
The node route provider class is \Drupal\node\Entity\NodeRouteProvider and it is declared in the annotation of the node class:

/*
 * @ContentEntityType(
 *   id = "node",
 *   label = @Translation("Content"),
 *   bundle_label = @Translation("Content type"),
 *   handlers = {
 *     ...
 *     "route_provider" = {
 *       "html" = "Drupal\node\Entity\NodeRouteProvider",
 *     },
 *     ...
 */
class Node extends ContentEntityBase implements NodeInterface {
//  ...
}


How to use hook_menu to create wildcard aliases to a normal node page

fwiw, I now did this different. I won't accept this as an answer, because it isnt. But this works as well in my case

function kitchen_url_inbound_alter(&$path, $original_path, $path_language) {
    if (preg_match('|^your/recepies(/\w+)?|', $path, $matches)) {
        $path = 'your/recepies';
    }
}


Node empty fields behave badly when created with Entity Metadata Wrapper

When an #empty_option is defined, it will be added as a label for the empty option in a select list. The value can be defined as well, it is keyed as #empty_value. See the documentation for form_process_select for more details. You will see that for required fields, the default #empty_value is an empty string.

That value is filtered out in _form_validate. I think it is being unset, and then when you call $ewrapper->field_area->set() you are actually passing FALSE, NULL or something else that PHP lovingly converts to an empty string.

I think you could solve it like this:

if (!empty($form_state['values']['field_area'])) {
  $ewrapper->field_area->set($form_state['values']['field_area']);
}

Or if you manually set the #empty_value to '_EMPTY':

if ($form_state['values']['field_area'] !== '_EMPTY') {
  $ewrapper->field_area->set($form_state['values']['field_area']);
}


How to get alter value of a views field programmatically

This is how I went about getting the "alter" value for my project:

if ($this->displayHandler->getHandler('field', $field)->options['alter']['alter_text'] == 1) {
  $value = $this->displayHandler->getHandler('field', $field)->options['alter']['text'];
}
else {
  $value = $values->_entity->get($field)->value;
}


I sometimes get the following error message "Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 8 bytes)

If you work in localhost, change memory_limit in your {php_installation_dir}/php.ini to a higher one.
Otherwise ask your web hosting service to increase the memory limit of the server.
(You can check your PHP memory limit in your Drupal site too: /admin/reports/status)


Creating a periodic report in Drupal 7 or 8

Below is a possible approach that may help to address the "reporting" part of your question (not how to pre-populate the webforms, which should really be a separate question I think). It's using "State" names (like Florida, Illinois, etc.) instead of "John, Mary, etc" and "Cities" instead of "A, B, etc". With "City attributes" instead of "pcs".
If I was to implement this in a Drupal site, I'd use either of these "displays":

Option 1 - Master detail with nested blocks
Have a look at this example, which shows 1 "block" for each "State", and within each "block" it shows the "Cities" (and one of its attributes) in that "State".

Option 2 - Report that filters based on some lookup
Have a look at this example, which shows only the data about a specific "State", together with all the "Cities" (and one of its attributes) in that "State". To switch to another state, select the desired state from the Parameter form near the top ("IL" is used as the default in this example).

If you wonder "How did you do that?!?!" ... then this is the answer: that's really a piece of cake using the Forena module. And (without programming" (unless you would want that instead ...), only using WYSIWYG editing features to either select the data (to build the SQLs) or to create the report that fits your needs to display those data. It also supports creating charts from these data.
Checkout the Community Documentation for details, and/or the documentation that comes with the module. The above 2 examples are actually delivered with the module (out-of-the-forena-box), though you probably don't notice that it is even not a typical "Drupal database". It could be such database instead (about data contained in your Webforms), but in this case it's an SQLite (sample) database (it could also have been Oracle, MS SQL, Postgress or any PDO compliant database).
Disclosure: I'm a co-maintainer of Forena.


How to redirect to l() function link after login?

You can add a additional destination parameter to the function.

<?php
print l(t('Title'), 'url', array('query' => array('destination' => 'destination_url')))
?>

This will create :

Title

Hope it helps.


Views Relationship/Contextual Filter for sibling nodes

There are two ways to do this that come to mind:

Option One

You could create a node template for nodes of type property and use an Entity Field Query in a manner roughly following this pseudo-code:

  $park = $node->field_park['value'];
  $query = new EntityFieldQuery();
  $query
     ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'property')
    ->propertyCondition('status', 1)
    ->propertyOrderBy('created', 'DESC')
    ->fieldCondition('field_park', $park)
    ->range(0,10);
$result = $query->execute();

This will load a list the NIDs of all nodes that have field_park matching the value of $node->field_park['value'] (or wherever the node object stores your actual field value). To get more info than just the NID, you will want to do some kind of foreach($result) that does a node_load($nid) on each NID returned by the EFQ.

Option Two

Option two is no-code: you could create a View and embed it on your node with something like Insert View. You would create the view with the following steps:

Add a contextual filter that takes the node ID. This is so you can pass it a value so you get a view specific to each node you want it to appear on. Exactly how to do this is out of the scope of this question.
Add a field for the node title. You can remove this later but it will keep you from getting confused while making the view. Give it a label if you want, make it grouping field number one, and exclude it from the view.
Add a relationship. Choose "Entity Reference" for the relationship type, and then select "entity that is referenced via field_park" or whatever your node reference field is called.
Add another content: title field. Under relationship, choose the relationship you just created. Set it to group by that field, create a label called "park:", and set it to exclude from display.
Add another relationship. Choose type "Entity Reference" and this time choose "referencing entity": "entity that is referencing Content via field_park"
Add another field for node: title and this time select the relationship you just created. Give it a label like, "sister property:" if you want.

Violá. Now you have a view that will allow you to pass an NID and will tell you the title of that property, its park, and all sister properties.


You could try using hook_block_access to restrict access to block operations.

  Control access to a block instance.

  Modules may implement this hook if they want to have a say in whether
  or not a given user has access to perform a given operation on a block
  instance.

  string $operation: The operation to be performed; for instance,
  'view', 'create', 'delete', or 'update'.


How to sell credits as products, using commerce module?

Have a look at the Commerce Userpoints* project. It allows to buy things using userpoints and there is also a feature that allows to buy userpoints that is based on a custom product type and rules, so fully customizable.

It most likely doesn't everything that you need, but it might be a start.

There is also Commerce credits and more similar projects, but I haven't tried them out, no idea what exactly they do and how well they work.

*Disclaimer: I am the maintainer of the Userpoints project and I was also involved in that project and still have some code lying around to re-work the UI and improve it.


How can I display the values returned from an external API under a form?

It's not much different from what done with Drupal 7; the difference is the involved classes (which weren't implemented in Drupal 7) and the used methods.

The submission handler stores the values obtained from the external API and sets the form to be rebuilt
The form builder verifies the values set by the submission handler are set and shows them

In the case of a class extending the FormBase class this means:

submitForm() calls $form_state->setValue() to set the value obtained from the external API
submitForm() calls $form_state->setRebuild() to tell Drupal the form needs to be rebuilt
buildForm() uses $form_state->hasValue() to check the value has been set and $form_state->getValue() to get that value

As for showing the returned value, it's sufficient to use a form element similar to the following one.
$form['api_value'] = [
  '#type' => 'markup',
  '#markup' => $api_result,
];

As side note, the $key value passed to $form_state->setValue() should not be a value already used for a form element. Differently, $form_state->setValue() would set the value submitted for that form element.


To include your custom css say demo_global.css in your theme write following line in theme_name.info file of your theme folder-

      stylesheets[all][] = css/demo_global.css

Note: You must clear the cache to see the changes.
For more information please refer https://drupal.org/node/171209


Adding a button or text link to a content's view (Drupal 7)

I was able to do this in hook_node_view.


Why has not Pressflow been upgraded to 6.24?

I'm a developer at Four Kitchens.

Drupal 6.24 introduced changes to the bootstrap process, and those created a merge conflict with Pressflow. See David Strauss' comments here on Github.

The forks of Pressflow on Github may have the latest 6.24 but these changes have not been reviewed by Pressflow maintainers and no pull requests have been sent.

The forks also include patches from the Drupal issue queue to fix some serious issues that appeared in 6.24, and they are not the most recent patches in the actual issue nodes:

drupal.org/node/1425868
drupal.org/node/1425260

So beware: Using a fork means you're using Pressflow upgraded to 6.x-dev essentially, except it's not even -dev as these issues are not yet adequately resolved; at least, not sufficiently enough to be accepted into Drupal 6.x-dev.

We're working on getting a full 6.24 stable version of Pressflow out. In the meantime, Pressflow 6.23 contains the security fix and was available when Drupal 6.23 was released.

You can also follow Pressflow at https://twitter.com/#!/pressflow.


Attempt to create a field body that does not exist on entity type node

You attempted to create a field using configuration without creating the field storage configuration.

In the field configuration YAML you can see a field_storage property. That is the id of the field storage configuration that needs to also be imported.


Email not to admin, When user create an account

Download, install & Enable Rules module.
Goto

Admin -> Configuration -> Rules

-> Click on Component tab -> Add Component

-> Select Action set -> In Component Plugin ->

Name: Send email to inactive user

Datatype: User,

Label:active_user,

Machine_name: active_user

Usage: Parameter

-> Add action -> data selector: active_user

-> Enter the subject & body & save

-> Go back & Add new rule

-> React on Event : After Saving a new new user a/c

-> Add Action  -> Select Schedule Component Evaluation

-> Value : Choose your component

-> Identifier : [account:uid]

-> Data selector : account

If you have any doubt then you may CLICK


How to override "active configuration" when the theme is installing?

You cannot. You can provide only configuration for your module or create new configuration entities. You can "override" the default configuration only by profile, not module or theme.

But you can use hook_install to programmatically override whatever you want.

When it comes to themes, the only configuration that you should provide is block instances and your theme's settings. Of course if you have some advanced blocks you can also provide block types and field storage and instances for them.


Feedback module block doesn't follow visibility rules

Wow.  It's pretty snarky, for no better word, and does the following...

/**
 * Implementation of hook_footer().
 */
function feedback_footer($main = 0) {
  if (user_access('access feedback form') && $_GET['q'] != 'admin/reports/feedback') {
    $block = (object)module_invoke('feedback', 'block', 'view', 'form');
    $block->module = 'feedback';
    $block->delta = 'form';
    $block->region = 'footer';
    return theme('block', $block);
  }
}

...which basically puts it on every page except admin/reports/feedback by stuffing the form into page.tpl's $closure variable.

So, yes, it does appear to ignore standard block visibility rules somewhat on purpose.


Remove check from  "Output the field as a link" and then in rewritten the result
put this

        [field_about_us_read_more]

or if not work try something like this  (I mean in output use  tag )

 [field_about_us_read_more]


How can one add inline JavaScript in the validation function for the Form API?

See the docs @https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

  drupal_add_js() example:

drupal_add_js(
  'jQuery(document).ready(function () { alert("Hello!"); });',
  array(
    'type' => 'inline',
    'scope' => 'footer',
    'group' => JS_THEME,
    'weight' => 5,
  )
);

  #attached example:

$element['#attached']['js'][] = array(
  'type' => 'inline',
  'data' => 'jQuery(document).ready(function () { alert("Hello!"); });',
  'scope' => 'footer',
  'group' => JS_THEME,
  'weight' => 5,
);

Just replace $element by $form.

Original source: https://web.archive.org/web/20160502205421/http://www.failover.co/snippets/drupal-7-attaching-css-and-javascript-forms-or-form-elements


How do I find "where-used" / many-to-one related entities?

If you want a quick solution in code, you can use the same way as in drupal 7:

Add a field (configurable in view modes):

hook_entity_extra_field_info

Put the code for the field in here:

hook_ENTITY_TYPE_view

Use this code:

How to check if an article is referenced from a collection?


Drupal 7 Theming: Generate styles to a file instead of inline

If you change the content of the CSS file every time the template file is invoked, then you could use code similar to the following one. The code is longer than it should be because I am using a custom function whenever the equivalent Drupal function would output a message error.

function mytheme_data_save($data, $destination, $replace = FILE_EXISTS_RENAME) {
  if (!file_valid_uri($destination)) {
    watchdog('file', 'The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', array('%destination' => $destination));
    return FALSE;
  }

  if ($uri = mytheme_unmanaged_data_save($data, $destination, $replace)) {
    // Create a file object.
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = drupal_basename($uri);
    $file->filemime = file_get_mimetype($file->uri);
    $file->uid      = $user->uid;
    $file->status   = FILE_STATUS_PERMANENT;
    // If we are replacing an existing file re-use its database record.
    if ($replace == FILE_EXISTS_REPLACE) {
      $existing_files = file_load_multiple(array(), array('uri' => $uri));
      if (count($existing_files)) {
        $existing = reset($existing_files);
        $file->fid = $existing->fid;
        $file->filename = $existing->filename;
      }
    }
    // If we are renaming around an existing file (rather than a directory),
    // use its basename for the filename.
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
      $file->filename = drupal_basename($destination);
    }

    return file_save($file);
  }

  return FALSE;
}

function mytheme_unmanaged_data_save($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  // Write the data to a temporary file.
  $temp_name = drupal_tempnam('temporary://', 'file');
  if (file_put_contents($temp_name, $data) === FALSE) {
    return FALSE;
  }

  // Move the file to its final destination.
  return mytheme_unmanaged_file_move($temp_name, $destination, $replace);
}

function mytheme_unmanaged_file_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  $filepath = mytheme_unmanaged_file_copy($source, $destination, $replace);
  if ($filepath == FALSE || file_unmanaged_delete($source) == FALSE) {
    return FALSE;
  }
  return $filepath;
}

function mytheme_unmanaged_file_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  $original_source = $source;
  $original_destination = $destination;

  // Assert that the source file actually exists.
  if (!file_exists($source)) {
    if (($realpath = drupal_realpath($original_source)) !== FALSE) {
      watchdog('file', 'File %file (%realpath) could not be copied because it does not exist.', array('%file' => $original_source, '%realpath' => $realpath));
    }
    else {
      watchdog('file', 'File %file could not be copied because it does not exist.', array('%file' => $original_source));
    }
    return FALSE;
  }

  // Build a destination URI if necessary.
  if (!isset($destination)) {
    $destination = file_build_uri(drupal_basename($source));
  }

  // Prepare the destination directory.
  if (file_prepare_directory($destination)) {
    // The destination is already a directory, so append the source basename.
    $destination = file_stream_wrapper_uri_normalize($destination . '/' . drupal_basename($source));
  }
  else {
    // Perhaps $destination is a dir/file?
    $dirname = drupal_dirname($destination);
    if (!file_prepare_directory($dirname)) {
      // The destination is not valid.
      watchdog('file', 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array('%file' => $original_source, '%destination' => $dirname));
      return FALSE;
    }
  }

  // Determine whether we can perform this operation based on overwrite rules.
  $destination = file_destination($destination, $replace);
  if ($destination === FALSE) {
    watchdog('file', 'File %file could not be copied because a file by that name already exists in the destination directory (%directory)', array('%file' => $original_source, '%destination' => $destination));
    return FALSE;
  }

  // Assert that the source and destination filenames are not the same.
  $real_source = drupal_realpath($source);
  $real_destination = drupal_realpath($destination);
  if ($source == $destination || ($real_source !== FALSE) && ($real_source == $real_destination)) {
    watchdog('file', 'File %file could not be copied because it would overwrite itself.', array('%file' => $source));
    return FALSE;
  }
  // Make sure the .htaccess files are present.
  file_ensure_htaccess();
  // Perform the copy operation.
  if (!@copy($source, $destination)) {
    // If the copy failed and realpaths exist, retry the operation using them
    // instead.
    if ($real_source === FALSE || $real_destination === FALSE || !@copy($real_source, $real_destination)) {
      watchdog('file', 'The specified file %file could not be copied to %destination.', array('%file' => $source, '%destination' => $destination), WATCHDOG_ERROR);
      return FALSE;
    }
  }

  // Set the permissions on the new file.
  drupal_chmod($destination);

  return $destination;
}

This is how you should use the code.

if (($file = mytheme_data_save($data, 'public://mytheme_css') !== FALSE) {
  if ($instance = file_stream_wrapper_get_instance_by_uri($file->uri)) {
    $url = $instance->getExternalUrl();
    drupal_add_css($url, array('type' => 'external'));
  }
}

With the code I am using, the file used to contain the CSS styles is deleted the first time the cron tasks are executed, if the file has been created 6 hours earlier.


Checking if user is logged in and inputting their username

First make sure only users with a specific role can access this form. You can use the #access property to restrict the access to a specific form.
The LoginToboggan module can redirect the user to the login page if they get an access denied.
In the submit hanlder of your form you can access the current user by adding global $user at the top of your method.


Node View Permissions module prohibits list of nodes in Views module

The problem was the 'Node View Permissions' module not playing well with the 'Views' module (or the other way around). I removed the 'Node View Permissions' module and replaced it with the 'Restrict Node Page View' module. Did not work right away...had to rebuild permissions for the site. Problem fixed!


Entity Validation API: Retrieve parent field entity while validating

By using FieldItemList::getEntity like in this core validator:

Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator:

class UniqueFieldValueValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    if (!$item = $items->first()) {
      return;
    }
    $field_name = $items->getFieldDefinition()->getName();
    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $items->getEntity();

The first argument of a validate method is of mixed type. For the Drupal Entity Validation API this can be a field value, a field item list or an entity, depending on where you add the constraint.


Node id can be accessed by arg(2) function call on node page view. It would even work if you have defined a url alias using path/auto_path modules.

On the view, where you manage argument options, Try with Provide default argument option as Node ID from URL


What I came up with, fully documented.

/**
* @file
* Provides special token to use with pathauto.
*
* @see http://drupal.org/node/1308488
*/

/**
* Provide information about our custom placeholder/token.
*
* @see http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_token_info/7
* @see http://api.lullabot.com/token_example_token_info/7
* @return array
*   An associative array of available tokens and token types.
*/
function MODULE_NAME_token_info() {
  $info['tokens']['node']['pathauto'] = array(
    'name' => t('Pathauto'),
    'description' => t('Title ready for use with pathauto.'),
  );
  return $info;
}

/**
* Provide replacement values for placeholder tokens.
*
* @see http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_tokens/7
* @see http://api.lullabot.com/token_example_tokens/7
* @param string $type
*   The machine-readable name of the type (group) of token being replaced, such
*   as 'node', 'user', or another type defined by a hook_token_info()
*   implementation.
* @param array $tokens
*   An array of tokens to be replaced. The keys are the machine-readable token
*   names, and the values are the raw [type:token] strings that appeared in the
*   original text.
* @param array $data (optional)
*   An associative array of data objects to be used when generating replacement
*   values, as supplied in the $data parameter to token_replace().
* @param array $options (optional)
*   An associative array of options for token replacement; see token_replace()
*   for possible values.
* @return array
*   An associative array of replacement values, keyed by the raw [type:token]
*   strings from the original text.
*/
function MODULE_NAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'pathauto':
          $replacements[$original] = str_replace('&amp;', '&'), 'and',
            $sanitize ? filter_xss($node->title) : $node->title);
          break;
      }
    }
  }

  return $replacements;
}
?>


Unsupported operand types error when creating new Webform handler

When I look at line 263 in \Drupal\webform\Plugin\WebformHandlerBase there is the below code...

$this->configuration = $configuration['settings'] + $this->defaultConfiguration();

Your Unsupported operand types error message indicates that one of those variables/properties is not an array.

My best guess is that \Drupal\webform\Plugin\WebformHandlerBase::defaultConfiguration is not returning an array() because your $configuration['settings'] is set to an empty array.


How to add jQuery to the user profile page only?

The code you should use is the following one:

(function ($) {
  $(function ($) {
    $(".moreLess").hide();

    $(".moreLessSwitch").toggle(function() {
        $(this).html("Less");
        $(this).prevAll(".moreLess").slideDown();
    }, function() {
        $(this).html("More...");
        $(this).prevAll(".moreLess").slideUp();
    }
  );
})(jQuery);

In Drupal 7, JavaScript using jQuery should be wrapped between (function ($) { and })(jQuery);. You should also use Drupal behaviors, similarly to what done in the batch.js file used from Drupal.

(function ($) {

/**
 * Attaches the batch behavior to progress bars.
 */
Drupal.behaviors.batch = {
  attach: function (context, settings) {
    $('#progress', context).once('batch', function () {
      var holder = $(this);

      // Success: redirect to the summary.
      var updateCallback = function (progress, status, pb) {
        if (progress == 100) {
          pb.stopMonitoring();
          window.location = settings.batch.uri + '&op=finished';
        }
      };

      var errorCallback = function (pb) {
        holder.prepend($('

').html(settings.batch.errorMessage));
        $('#wait').hide();
      };

      var progress = new Drupal.progressBar('updateprogress', updateCallback, 'POST', errorCallback);
      progress.setProgress(-1, settings.batch.initMessage);
      holder.append(progress.element);
      progress.startMonitoring(settings.batch.uri + '&op=do', 10);
    });
  }
};

})(jQuery);

The code in the JSFiddle works fine for me. It just be only a problem of wrapping the code correctly.


With a module, creating a form and using the drupal ajax function to switch the input field on/off might be a solution.

check out this example from deckfifty: form api using ajax example

partial code:

function deckfifty_example_form($form, &$form_state) {
  $form['fox_color'] = array(
    '#title' => t('Specify the color of the fox:'),
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('', 'brown', 'black', 'white')),
    '#ajax' => array(
     'callback' => 'deckfifty_fox_ajax_callback',
     'wrapper' => 'deckfifty_fox_ajax_wrapper',
   ),
 );
 $form['fox_wrapper'] = array(
    '#type' => 'markup',
     '#prefix' => '
',
    '#suffix' => '
',
 );

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

 return $form;
}


How to change default file system path in D8?

You can't change the public file system path globally to include a nodeID because there are things that can store files that do not have a nodeID (such as non-node entities).

Instead, you can change where files are stored per file storage field (examples: File fields and Image fields).

To do so, go to Structure -> Content Types -> My Content Type -> Manage Fields and then choose Edit for the relevant field.

Then, in File directory, you can use tokens to set up the path however you like.  For example:

myfiles/[date:custom:Y]-[date:custom:m]-[date:custom:d]

There is a link below Help text that you can click to see a list of available tokens.


Create a view with base table "Commerce product. "

Add necessary fields. Title, Price, Add to cart form, etc will be essential.
Add Relationship "Commerce Product: Referencing Node".
Add Contextual filter "Content: Nid". This view will list the products referenced by a product display node.

Install module Viewfield.
Add a view field to the product display content type, and set the view created in the first step as default value. Give [node:nid] as argument.
Configure the node display as you please.


Different bar colors for each poll choice?

jQuery can help you in this regard if you not going to edit templates.

(function(){
   var i=0;
   jQuery('div.poll .bar .foreground').each(function(){
        i++;
        switch(i){
            case 1:
                $(this).css('background-color', '#color')
            break;
             ...
         }

    });
})();


Users have access to add Commerce Products into the Store and publish it. How to display to user only allowed firms in the product addition form?

It is possible using hook_alter_form but hook_form_FORM_ID_alter would be better so you only target the correct form.

You will need code to retrieve only the firms the user has from their profile field and then using array_diff to remove the others from the select options.


https - Works for the homepage but fails for all other pages

Check to make sure you are using the default .htaccess file. It sounds like your mod_rewrite settings are not working properly and/or not handling the https url.


Output Paragraph values instead of the Paragraph IDs in a View REST export?

I thought about using a custom field formatter, but that seems like a
  lot of work just to output JSON data

No Code Solution:

Install Views Field View

Create a new View, "User view" in this case (does not to be a REST view).

Add user fields you want to show.
Add Contextual filter of ID

When adding, scroll down to the "More" section. Checkmark allow multiple values.

Go to your Rest View

Add field of "View", select the view you added above.

For contextual filter, use the replacement pattern for your author's field.


Node export module imported node as another node numbers

You can't, and you shouldn't.

Node Export requires UUID for a reason, and that reason is decoupling database identifier of a node (nid) from it's logical identifier and address. These are supposed to be defined by UUID now, so if you are using UUID module and still have addresses like http://example.com/node/1 then your site is not using modules in a way they are designed to work.

Also, as Node Export project page says, if you need anything fancy on import, you should export in Feeds format, and use Feeds for import. I believe that updating existing nodes is a case where it would be recommended approach.


How to get list of installed/enabled modules ready for repopulating new site with drush module installation?

drush pm-list --status="enabled" --pipe

  --status="enabled" Filter by extension status. Choices: enabled, disabled and/or 'not installed'. You can use multiple comma separated values. (i.e. --status="disabled,not installed").
  --pipe Equivalent to --format=list.
  --format="list" Select output format. Available: table, csv, json, list, var_export, yaml. Default is table.


Creating nodes and sub-nodes from database table

One solution would be to create a new content-type, let's call it Question-Page and the install Entity Reference, which provides a field type that can reference other nodes. Then you could add three new fields for previous_id, next_positive_id and next_negative_id.

To import the data from your table I think you could use the Feeds module. First create one importer that will create the actual nodes. Second an importer that will update each node and set the node reference fields.

First importer that will only create all nodes.

Second importer, that will setup the reference fields.


Theming a custom user field on register form

Two possibilities.  You could alter the form element with hook_field_widget_form_alter, or you could override theme_checkbox.

More info: http://drupal.org/node/173880


How to call function in mail which is configured using Rules in drupal

You can alter the mail content using hook_mail_alter

  hook_mail_alter() allows modification of email messages created and
  sent with drupal_mail(). Usage examples include adding and/or changing
  message text, message fields, and message headers.


how to create a node slideshow with customized fields?

Use Views Slideshow module.
steps :

Enable view slideshow module.
Create a view using existing content type(ex-product).
View format: Slideshow
Add item for slideshow (such as the title, image etc).

Or you can use jCarousel module.


Commerce rule for total of product lines only (not shipping as well)

Using [site:current-cart-order:commerce-order-total:amount] seems to do the trick.


This is probably not the case for all pages? I think what you see is the rendered result of an entity field like for example this node field template:
field--node--title.html.twig:
<span{{ attributes }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</span>

In other cases when the title is not bubbled up from the rendered main content and it is taken from the route definition there shouldn't be a span tag unless there is a title callback placing such a tag.


Content Translation : Language filter not available in views

Between the filters you should see 'Content Translation: User's Current Language'. Also check out the Internationalization Views module for more translation options for views.

  Translate views using Internationalization. This is a work in progress and not all Views properties can be translated yet.

  This module has been moved from Internationalization package so we can have different branches compatible with each of the Views versions. Use the same branch of the Views version you are using (2.x. 3.x).


Allowed memory size of 134217728 bytes exhausted in system\image.gd.inc reported for styled images

128M is somewhat low for a Drupal install.  It may work well for front end pages, but I have found that it needs to be raised for admin pages.  I do not know where you get the recommendation that anything over 128M isn't recommendation.  That PHP variable is a holdover from custom PHP to prevent infinite loops from crashing a system.  And remember, it is a max value.  Page requests that use less will not get the full amount.

You are running into the problem because GD needs to load the image into memory to process it down to 800x400 before saving it to disk and serving it up for display.  The problem isn't as much the file size, as what it will decompress to and occupy in memory.  When you start doing the math on big images (multiple width x height x 4), you will see that, 128M is way too low.  When the style has already been made, PHP never gets involved.

I believe the ImageMagick library will end up using the CLI convert utility, which can save PHP memory, but I don't recall the last time I actually tested this to be sure.


You need to create a custom template for your view.

Go to /sites/all/themes/YourTheme/templates folder

create a file called views-view--[view-name]--[machine-name].tpl.php

  For example if you view name is "Hello World" and machine name is "block_1"

  It would be: views-view--hello-world--block-1.tpl.php

Inside your custom template file put:

<?php

/**
 * @file
 * Main view template.
 *
 * Variables available:
 * - $classes_array: An array of classes determined in
 *   template_preprocess_views_view(). Default classes are:
 *     .view
 *     .view-[css_name]
 *     .view-id-[view_name]
 *     .view-display-id-[display_name]
 *     .view-dom-id-[dom_id]
 * - $classes: A string version of $classes_array for use in the class attribute
 * - $css_name: A css-safe version of the view name.
 * - $css_class: The user-specified classes names, if any
 * - $header: The view header
 * - $footer: The view footer
 * - $rows: The results of the view query, if any
 * - $empty: The empty text to display if the view is empty
 * - $pager: The pager next/prev links to display, if any
 * - $exposed: Exposed widget form/info to display
 * - $feed_icon: Feed icon to display, if any
 * - $more: A link to view more, if any
 *
 * @ingroup views_templates
 */
?>
<div class="<?php print $classes; ?>">
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <?php print $title; ?>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <?php if ($header): ?>

      <?php print $header; ?>

  <?php endif; ?>

  <?php if ($exposed): ?>

      <?php print $exposed; ?>

  <?php endif; ?>

  HERE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

  <?php if ($attachment_before): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

  <?php if ($rows): ?>

      <?php print $rows; ?>

  <?php elseif ($empty): ?>

      <?php print $empty; ?>

  <?php endif; ?>

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

  <?php if ($attachment_after): ?>

      <?php print $attachment_after; ?>

  <?php endif; ?>

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

  <?php if ($footer): ?>

      <?php print $footer; ?>

  <?php endif; ?>

  <?php if ($feed_icon): ?>

      <?php print $feed_icon; ?>

  <?php endif; ?>

<?php /* class view */ ?>

  Note: The above code is an exact copy of views-view.tpl.php located in the /sites/all/modules/views/theme folder. I just added
  the HERE <<<<<<<<<<<<<<< part after the exposed filter php.

Don't forget to clear/flush the cache to see changes.


Programmatically create a new node from an existing NID

On entities, you can use is_new to signify a new entity to save, but you still need to unset nid (iirc), vid, and tnid manually. This saves unsetting log.

$new = clone $node;
$new->is_new = true;
unset($new->nid);
unset($new->vid);
unset($new->tnid);
node_save($new);

Interestingly, the node_clone module incorrectly sets the properties to null, which is significant for databases that support NULL and DEFAULT separately (e.g. PostgreSQL).


How to display the number of contents of a node?

could you add some details to your question that will tell us WHERE you want to see these counts?   Is it in a page template? A view? A block?  The answer will change depending.

In the meantime, please look at this:
Count of nodes by type


Feeds XPath parser - setting the created date of a node

You can try to use the hook_feeds_presave in a custom module :

function mymodule_feeds_presave(FeedsSource $source, $entity, $item, $entity_id) {
  $your_import_date = explode('/', $item['your_import_date']);
  $your_import_date_formated = $your_import_date[2] . '-' . $your_import_date[1] . '-' . $your_import_date[0] . ' 00:00:00';
  $item['your_import_date'] = strtotime($your_import_date_formated);
  $entity->created = $item['your_import_date'];
}


How to hide Article Fields which are displaying on the front end

Guessing there is no views implemented.

Go to manage display settings of article content type [ admin/structure/types/manage/article/display ]. In Label column select 'hidden' for body row.

You are done.


Google web font imports breaking with advagg

You'll want to follow this issue https://www.drupal.org/node/2396609 Inline critical css

I'm guessing you're using the "Inline CSS on specific pages" setting on the AdvAgg: Modifications page. If the imports and not working correctly when everything is inlined, please open up a bug report explaining this with a good way for me to reproduce the issue locally.

Also noted that you can use the Adjust CSS location and execution setting to load the css async without having to mess with the tpl file.


How do you run Drupal core-patches and is there a single, general way?

Drush make is a method to maintain patched releases of contrib and core. It is the only organized, non-custom, method I know of for patch management. The makefile is self-documenting. By "self-documenting", I mean that the makefile contains a list of modules, their versions, and URLs of applied patches.

Create a makefile of an existing Drupal site with:

drush generate-makefile mysite.make

Note, as far as I know drush generate-makefile will not detect applied patches. The example makefile demonstrates how to reference patches in your makefile.


How can I change the date format for user submitted data in confirmation emails

I have a work-around, but not a solution:

Go to /admin/structure/webform/config/elements
In the section "Element Formats" change "Date/Time" from "- default -" to "Default medium date (medium)"


How to treat users as Anonymous in Confidential Groups?

I would add a "anonymous" field in the user account: admin/config/people/accounts/fields

then, in node pre-processing, do a check to see if the author of the node is anonymous and re-write the author field accordingly.


Adding the video field to a content type

I was facing the same issue, then I realized that we were doing it the wrong way.

You have to select "file" drop down "Select a Field Type", then "Video" becomes available in the next drop down labelled "Form element to edit the data".