In your sub-theme's .info.yml file add the new region alongside the existing ones, e.g.

regions:
  header: Header
  content: Content
  sidebar_first: 'Sidebar first'
  footer: Footer
  custom_region: 'Custom region'

Then in your page.html.twig file render it like so:

{{ page.custom_region }}

Visit the Block layout admin page and assign some blocks to the region so it displays on the page.


Count how many times a node is referenced

Silly mistake. I had the relationship the wrong way round. Now it's working perfectly. These are the steps:
1.) Create a relationship: Content using field_classroom (not content referenced from field_classroom)
2.) Enable aggregation
3.) Add a field: field_classroom
4.) Use the relationship
5.) Set aggregation on the field to COUNT
And it works!


How to change the default images path and direct it to the external directory

Use Private File System, go to admin/config/media/file-system and provide the private file system path. After saving it, select  Private local files served by Drupal as Default download method. After that edit your image field and choose Private Files as Upload Destination

Note : It should be writable by Drupal and not accessible over the web.


Use form_alter to add placeholder text to a Views Exposed Filter min/max field

Found the solution!!! (here: https://www.drupal.org/node/2280069#comment-8844805)

  if (isset($form['field_listprice_value']['min'])) {
    $form['field_listprice_value']['min']['#attributes'] = array('placeholder' => array(t('Min Price')));
  }
  if (isset($form['field_listprice_value']['max'])) {
    $form['field_listprice_value']['max']['#attributes'] = array('placeholder' => array(t('Max Price')));
  }


Modifying superfish menus to gives extra block of data

I am not sure you can achieve this with Superfish without a major hack to the module. Try using OM Maximenu which can create menus with all other module blocks you want as attachments, modules like views, slideshow, menu, user, nice menus, quicktabs, and custom blocks with tables, lists, images, videos, etc.


How to override output of checkout page in Commerce

It looks like using hook_commerce_checkout_pane_info_alter(&$checkout_panes) or hook_commerce_checkout_page_info_alter(&$checkout_pages) would be the best options. There are also hooks that allow you to create your own checkout panes/pages from scratch if necessary (hook_commerce_checkout_pane_info() and hook_commerce_checkout_page_info()). I would suggest reading more about them here and checking out the specific examples (about page/pane info hook implementations) that you can find in the Drupal Commerce submodule (mostly Checkout) files.


Here is how I was able to do this using attributes...

'#attributes' => array('onchange' => 'this.form.submit();'),

So it was just simple ....

function MYMODULE_form($form, &$form_state) {
  $form['#method'] = 'get';
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
    '#default_value' => isset($params['cat']) ? $params['cat'] : '',
    '#attributes' => array('onchange' => 'this.form.submit();'),
  );
}

Now I am able to submit form when field is changed.


How to get an image URL from a field in a twig template

An image field stores the file id in target_id. You can access the file id with:

{{ node.field_main_image.target_id }}

There is a second property in the image field. It is for the referenced entity, in this case the file object. This is not visible in the debug output, because it is computed:

{{ node.field_main_image.entity }}

In the file object you find the field uri

{{ node.field_main_image.entity.uri.value }}

which you can use the get the url of the original image

{{ file_url(node.field_main_image.entity.uri.value) }}

or the url of an image style

{{ node.field_main_image.entity.uri.value | image_style('thumbnail') }}

The filter for the image style is part of this module which you have to install:

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


How can I disable Webform submit button after being clicked

You could try this module: https://www.drupal.org/project/hide_submit
Be aware that this module has an issue with Ajax forms and file uploads.


So, I just want to show one textfield for starting. If user not use
  that form, it doesn't show new form. But, if user input some value in
  that form, when user finish inputing that value (confirm by click
  enter button on keyboard for example), new textfield form showd up so
  user can fill new value, and so on.. – bandungeuy

I don't think there is a Drupal way to do that, but you can always do this with jQuery.

For example:

HTML

<form>

  First name:

  <input type="text" name="firstname" id="edit-first-name">

  Last name:

  <input type="text" name="last-name" id="edit-last-name">

</form>

jQuery

(function ($) {

   $('#edit-last-name-wrapper').hide();

   (function Forever(){

     var grabs = $('#edit-first-name').val();

     if (grabs != '') {
       $('#edit-last-name-wrapper').slideDown(1500);
     }
     // slides down and shows the last name field if the first name field is not empty
     else if (grabs == '') {
     // checks if the first name field is empty
       $('#edit-last-name').val('');
         // empties the last name field, since there is no first name
       $('#edit-last-name-wrapper').slideUp(1500);
         // slides up and hides the last name field

     }

   setTimeout(Forever, 1);

   })();

})(jQuery);

JS Fiddle DEMO


Open a pop-up/modal window after add/edit node to share

without coding, you could setup a message in rules and show it with Better Messages or similar (there is a link to a wiki on the project page) or you could acheive the popup with some coding and the hidden gems of ctools (see the examples in ctools)


How do I remove the header background image in Pixture Reloaded theme?

For Pixture Reloaded 3.x, I made a subtheme and I added this CSS:

#header, #header .header-inner {
    background: mycolor;
    background-color: mycolor; }


Sounds like you are using Drupal 6. The Admin menu module provides a nice menu on top of the page for all admin items the user has access to.

Screen shot of admin menu http://drupal.org/files/images/Administration-menu.preview.png


Define a specific page.tpl for a page create from a module

Page templates have overrides already available based on path.

If you see template_preprocess_page() it has this code:

// Populate the page template suggestions.
if ($suggestions = theme_get_suggestions(arg(), 'page')) {
  $variables['theme_hook_suggestions'] = $suggestions;
}

and you can see that theme_get_suggestions() looks at the path and generates the template suggestions.

This means that if you have hook_menu() generate the path "my-basket" then you will be able to override its page template in your theme by naming it page--my-basket.tpl.php without having to do anything else, like use hook_theme() or manually add a template suggestion in the preprocessor, or alter the theme registry.


Hooks aren't Symfony events. They are PHP functions with a specific name that Drupal calls in very specific cases.

For example, hook_cron() is invoked when Drupal cron tasks are executed, from Cron::invokeCronHandlers(), which uses the following code.

  // Iterate through the modules calling their cron handlers (if any):
  foreach ($this->moduleHandler
    ->getImplementations('cron') as $module) {
    if (!$module_previous) {
      $logger
        ->notice('Starting execution of @module_cron().', [
        '@module' => $module,
      ]);
    }
    else {
      $logger
        ->notice('Starting execution of @module_cron(), execution of @module_previous_cron() took @time.', [
        '@module' => $module,
        '@module_previous' => $module_previous,
        '@time' => Timer::read('cron_' . $module_previous) . 'ms',
      ]);
    }
    Timer::start('cron_' . $module);

    // Do not let an exception thrown by one module disturb another.
    try {
      $this->moduleHandler
        ->invoke($module, 'cron');
    } catch (\Exception $e) {
      watchdog_exception('cron', $e);
    }
    Timer::stop('cron_' . $module);
    $module_previous = $module;
  }

A module whose machine name is spam_checker could implement this hook adding the following function to its code.

function spam_checker_cron() {
  // Delete the nodes from the list of nodes to check after 96 hours are passed.
  Drupal::database()
    ->delete('spam_checker_list')
    ->condition('timestamp', REQUEST_TIME - 3600 * 96, '<')
    ->execute();
}


How to I add specific meta tags to panels pages?

There is now the Meta tags: Panels module.
Works fine for me.

  This module extends the Meta tags module by adding support for meta tags configuration for panels pages.


It's hard to say without actually running those queries but I think the problem is just because of a disparity in the names of your form elements.

In your form the element is defined as $form['date_weekend'] but in your callback you set an element called $form['booking_weekend'].

This would probably be fine except that $form['booking_weekend'] doesn't have the #prefix and #suffix that $form['date_weekend'] does. Drupal replaces the entire wrapper element when it does an AJAX replace so if the new element doesn't have a wrapper with the same ID around it the next AJAX call won't work (as no element would exist with the correct ID).

I'd recommend changing the element names to match as this should solve the problem, but if you really need it to be a different element just add the wrapper around the new element in your callback:

// The rest of delivery_date_weekends() comes before this as normal...

  $form['booking_weekend']['#markup'] = theme('table', array('header' => $headers, 'rows' => $rows, 'sticky' => FALSE));
} else {
    $form['booking_weekend']['#markup'] = 'No delivery weekends exist for this month. Please select another date.';
}

$form['booking_weekend']['#prefix'] = '
';
$form['booking_weekend']['#suffix'] = '
';

return $form['booking_weekend'];


How can I put a checklist button in a views table to run some code on selected rows?

It sounds like you want to use the views bulk operation module.


Get form element's label/value pairs from &$form or &$form_state

This might work.

function get_fields_this_step($form_state) {
    $fields = array();
    foreach($form_state['values'] as $key=>$value){
        $fields[$key] = $value;
    }
    unset($value);
    return $fields;
}


Lightbox2 doesn't open html content and links

This link works to get google search in the ligtbox:

Search

I got it from this post: How to show google.com in an iframe?


drupal 7 block to show if page has taxonomy term

The code posted by Triskelion did not work for me. Here is the code that I used and worked:

<?php
$term_id_to_trigger_show_block = 14; // show this block on nodes with this term id.
$taxonomy_to_search = "field_machinenameofvocab"; // The 'field_' + machine name of the vocabulary to search for the terms
$make_block_visible = FALSE;

// Show this block on nodes with the right term id
if (arg(0) == 'node' && arg(1) && is_numeric(arg(1))) {
  $node_obj = node_load(arg(1));
  $taxonomy = $node_obj->$taxonomy_to_search;
  foreach ($taxonomy['und'] as $term) {
    if ($term['tid'] == $term_id_to_trigger_show_block) {
      $make_block_visible = TRUE;
    }
  }
}

return $make_block_visible;
?>

Note that $taxonomy_to_search should be set equal to the machine name of the vocabulary prefixed with field_. So if my vocabulary machine name is animal_species that line would be $taxonomy_to_search = "field_animal_species";

UPDATE:
After using the above code on a site for quite some time I realized that it was giving me PHP errors in my logs. My solution was to give up on displaying a standard block and use views instead.

Create a new block view, set it to display fields. For your only field use "Global: Custom Text," entering your desired block content in the custom text field.

Under "Contextual Filters" add "Content: NID" and then "Provide default value" of "Content ID from URL."

Finally under "Filter Criteria" your only filter should be "Content: Has taxonomy term." Set it up to look for your term.


Teaser of full html pages without layout

Add the body field and trim it.

Now in your web directory, go to /sites/all/themes/yourtheme/ folder and in template.php add the following code:

function yourtheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    $vars['fields']['body']->content = strip_tags($vars['fields']['body']->content);
  }

}

replace yourtheme with the actual name of your theme
replace view_name with the name of your view.
replace block_1 with the machine name of your view. If yours happens to be block_1 then leave it the same.

In Drupal, clear/flush your cache to see the changes.

Then add the other fields you want on your view, title, post date? comment link? etc... basically you create your own teaser.

PS: You can add classes to your fields, if you need to use css on them.


CKEditor strips all inline CSS and some tokens

See

https://drupal.stackexchange.com/a/282373/79805
https://stackoverflow.com/a/60836391/9302793
https://drupal.stackexchange.com/a/215158/79805

for some further reference :)

You could try using custom CKEditor styles. For using custom styles you'll need a custom module.

MYMODULE/

/MYMODULE.module
/MYMODULE.libraries.yml
/css/style.css

MYMODULE/MYMODULE.module:

function MYMODULE_editor_js_settings_alter(array &$settings) {

  foreach ($settings['editor']['formats'] as $name => $value) {

    // You can check for specific editors.
    // if ($settings['editor']['formats'] == 'basic_html') {
    //
    // }

    // Otherwise, add our custom styles to all editors.
    $settings['editor']['formats'][$name]['editorSettings']['stylesSet'] = [

      [
        'name' => 'Custom Color Text',
        'element' => 'p',
        'attributes' => [
          'class' => "custom-color-text"
        ]
      ],
      [
        'name' => 'Custom Color Link',
        'element' => 'a',
        'attributes' => [
          'class' => "custom-color-link"
        ]
      ],
    ];
  }
}

function MYMODULE_preprocess_node(&$variables) {

  // Attach our styles library.
  $variables['#attached']['library'][] = 'MYMODULE/styles';
}

// Nice to haves:
function MYMODULE_ckeditor_css_alter(&$css, $editor) {

  // Add our ckeditor style sheet to ckeditor.

  // This adds our theme styles to the editor field.
  $css[] = drupal_get_path('theme', 'MYTHEME') . '/css/style.css';

  // This adds our styles from the module directory.
  $css[] = drupal_get_path('module', 'MYMODULE') . '/css/style.css';
}

MYMODULE/css/style.css:

.custom-color-text {
  color: #f00;
}

.custom-color-link {
  color: #00f;
}

MYMODULE/MYMODULE.libraries.yml:

styles:
  version: 1.x
  css:
    theme:
      css/style.css: {}

These will now be available in the "style" dropdown in the CKEditor field.


Some drupal database operations won't complete

Is everything working fine on the production server?  If so, try erasing the development database, and then copy the production database over it again.  Drush sql-sync does not delete the target database by default.

drush @dev sql-create
drush sql-sync @prod @dev


How do I check the access to every node?

There are several ways to do alter or hook into node access. You can find out more by reading the Node Access Rights page on api.drupal.org.

Briefly node access works like this (paraphrasing from the aforementioned documentation page):

Users with 'bypass node access' are granted access.
Invoke implementations of hook_node_access
Invoke implementations of hook_node_grants

Finally,

  To see how to write a node access module of your own, see node_access_example.module.


making correct return array of ControllerBase

The return type of a Controller can be either a Response or a render array.

A render array is an array that you see in your code, and this is generally the best thing to return for a visible page as it provides the theme layer with opportunity to render into a template.

Render array types (#type) are defined in the Render Arrays docs page. See also the API docs for the RenderElement plugin I linked below.

  The element type. If this array is an element, this will cause the
  default element properties to be loaded, so in many ways this is
  shorthand for a set of predefined properties which will have been
  arranged through a RenderElement plugin.

However the render array could also be defined to use a theme/template directly with (#theme), which is defined as

  A single theme function/template which will take full responsibility
  for rendering this array element, including its children. It has
  predetermined knowledge of the structure of the element.

So the render array return for a Controller will depend on how you wish to structure the content that is displayed in the main content area.


Set value on newly created node using Rules

In the Rules action you need to use the Set a data value action. This can be used to enter data in fields and properties. Make sure to set the value of your new 123-entity to refer to the xyz entity.

{ "rules_create_new_basic_page_after_saving_article" : {
    "LABEL" : "Create new basic page after saving article",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : "Basic page to go with [node:title]",
            "param_author" : [ "node:author" ]
          },
          "PROVIDE" : { "entity_created" : { "page_created" : "Created basic page" } }
        }
      },
      { "data_set" : {
          "data" : [ "page-created:field-reference-to-other-entity-" ],
          "value" : [ "node" ]
        }
      },
      { "entity_save" : { "data" : [ "page-created" ], "immediate" : "1" } }
    ]
  }
}


How to use field variable (a term) from node in field.html.twig for page title

In a field template the parent entity of the field is stored in element['#object'], so you can access the taxonomy field of the node like this:

{{ element['#object'].field_related.entity.label }}


Simple click alternative to Draggable views?

The standard ordering for lists of nodes or entities in Drupal is first by the "sticky" attribute and then by the created date. Many content modules have some facility to change this ordering, but only for their content type. The modules described in the Community documentation about Comparison of node ordering modules attempt to provide a more controllable ordering in a variety of ways.

Here is the list of modules mentioned in that documentation (quotes are from their project pages):

Outline Designer:

  ... is a user experience module that makes book management more intuitive. Essentially it overlays on the admin book outline page so that you can use AJAX to build and edit site outlines much faster then Drupal traditionally allows.

Weight:

  ... adds a weight option to enabled node types. Nodes with lower weight will float to the top of lists, while heavier items will sink.

Nodeorder:

  ... gives users an easy way to order nodes within their taxonomy terms.

  By default, the taxonomy module orders listings of nodes by stickiness and then by node creation date -- most recently posted nodes come first.

  The nodeorder module gives the user the ability to manually put nodes in any order they wish within each category that the node lives.

Nodequeue:

  ... allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:

  A block listing teasers for the five top news stories on a site
  A user’s favorite music albums
  A group of favorite from which one is randomly displayed

DraggableViews:

  Have you ever rearranged Blocks?, sorted Taxonomy terms? or reordered Menu items at the Drupal administration pages? All these pages use the tabledrag.js javascript that enables Drag'n Drop on HTML-tables.

  With DraggableViews you can apply this tabledrag.js to any Views-generated table.

Flag Weights:

  ... very simple module that adds a 'weight' field to the tables already used by the excellent Flag module.

  This weight can then be used to provide ordering of flagged items. This module also provides a Views field which can be used to sort flagged items. One interesting use of this ability is to integrate with Draggable Views to create a user-sortable list of flagged items.

Sortable Grid Views Plugin:

  ... provides a Views plugin for the user to be able to show a grid composed of draggable elements and save the displayed order of these element.

  The user may then create other displays to show the elements in the order defined above.

  This project is very similar in its goals to Draggable Views, yet a lot simpler as there is no hierarchy management. It doesn't depend on Draggable Views though.

  The added value resides in the presentation, a grid rather than a table list, and the therefore possible uses which Draggable Views doesn't permit.

JQGRID - View integration:

  ... provides views integration for the jqGRid jQuery plugin, which
  provides advanced interaction controls to HTML tables such as dynamic
  pagination, on-the-fly filtering, and column sorting.

  For full documentation and examples, visit the jqGRid jQuery plugin page

Nodeflow:

  ... gives a drag and drop interface for publishing nodes and positioning them in your desired order. This is useful for large publishing sites where editors can get a bird's eye view of all nodes currently on the frontpage and all nodes waiting to be published. A drag and drop interface helps to publish nodes quickly into desired positions.

Queues:

  Adds new Queues entity
  Revisionable
  Support multiple Bundles
  Support reference to any Entity/Bundle
  Full State Machine Support (Queues Workbench)
  Supports Revision Scheduler Module (Queues Workbench)
  Revision Revert Operation
  Revision Delete Operation
  Revision Publish Operation (Queues Workbenc integration)
  Revision Unpublish Operation (Queues Workbenc integration)


How to update core and all modules and themes from CLI?

Assuming you are using Composer to maintain your Drupal 8 installation, you can use the following command to update core and all modules (and dependencies).
composer update drupal/* --with-dependencies

If you started you project from "drupal-composer/drupal-project" the command becomes the following.
composer update drupal/* webflo/drupal-core-require-dev --with-dependencies

I recommend reading https://www.drupal.org/docs/8/update/update-core-via-composer and https://www.drupal.org/docs/8/update/update-modules.
Always after updating, don't forget to run database updates and rebuild the cache.
drush updatedb
drush cache:rebuild

If you started your Composer project from drupal/drupal as the user guide says, you are in trouble, since drupal/core isn't listed as installed. You could try to use Composerize Drupal to fix the problem.
If you started your project from a tar-ball, you also need use Composerize Drupal if you don't plan to do manual updates forever.
Drush 9 doesn't support updating core or modules. It will tell you to use Composer. Anyway, reading the Drush docs is very useful.


Configuration successful but never gets imported

Sounds like a known core bug: https://drupal.org/node/2666392


Is there a way to hand-code a reference to a block?, in a .tpl file?

I'm guessing the down vote to what probably should be the correct answer to this post is b/c the answer did not have any code.

The way to render a block is:

<?php
  //D7
    $block = module_invoke('module_name', 'block_view', 'block_delta');
    print render($block['content']);
?>

That can be placed in the template file that you want the block to show. See here for information on what the vars are in that snippet of code.


How to prevent edit or delete of some content by its author depending on an approval status field?

You can get this to work with the Rules module by using Event System > Drupal is initializing, combined with a Rules Condition related to the URL for the edit or delete operation.

Disallow edit

The rule you'd need for disallowing 'edit', is a variation of the rule I included (in export format) in my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle?

These are the changes to that rule to make it work this case also:

The paths containing node should be extended by adding /edit at the end (I'm assuming that's how the URL for your edit link looks like).
Add a (1st) Rules 'Condition' like "If Author id matches the uid".
Add a (2nd) Rules 'Condition' like "If Admin Status is Approved".
Change the "Message" (in the Rules 'Action' to something to indicate that the edit is not allowed because Admin Status is Approved.
Modify the Rules 'Action' to fit your own requirements, e.g. to issue a redirect to some 'help page' with more details about this.

Disallow delete

Should you also want to disallow 'delete' by the author for "Admin status" = 'Approved' (which is not what your question currently says however ...), then create another rule in which you use a similar approach as for 'edit' (as described above), just replace all 'edit' by 'delete'.

Combine both rules

It should be possible to consolidate the 2 suggested rules above, using "OR" within Rules. Know however that this is a very little harder to get it to work. So learn to walk (= get it to work with 2 separated rules) before you want to learn to fly ...

Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.

Note: your question does not say what should happen (what is allowed or not) when a user who is not the author tries to edit or delete something with 'Admin Status' = Approved. If such scenario is possible in your setup, then you might have to further enhance the Rules Condition I suggested accordingly ...


field_info_instances() returns an empty set in hook_uninstall but not in module file

I found out that this has been fixed in 7.8. #943772 by jpsoto, yched, catch, bojanz, pillarsdotnet, steinmb: Fixed field_delete_field() and others fail for inactive fields.


Why do I need to use .live() in Drupal Behaviors?

My understanding is that one of the advantages of using Behaviors is that it frees you from having to use .live() to bind event handlers to dynamically created elements.

Yes and no. It certainly can be used for that, but it will only work if Drupal has invoked the previous AJAX call. If you've just done a $.ajax(...), Drupal won't know about it, and attachBehaviors() won't be invoked.

I would guess that your attach() method is indeed only being invoked once, as it would explain perfectly why the click handler is assigned once (when the page is first loaded), but not again. The live() will always work no matter how many times your attach() method is called.

If that is the problem, to fix simply add this to your AJAX success callback:

Drupal.attachBehaviors();


customer commerce profile = user profile

You've got some ways to do this, I'd look first to Commerce Extra module which allows you to have an address in the user entity and prepopulate information in the commerce checkout with this.

If you want to actually duplicate the information and have a customer profile entity for each user registered, you can use Rules module for this (it is required by Commerce), you can then create a new rule, for instance in the "After saving a new user account" event that triggers an action "Create a new entity" of type commerce customer profile and then another action, "Save entity".
You can check Drupal commerce default rule "Create a new account for an anonymous order" for a similar concept.


Is there an option for radio buttons with Facet API + Search API (database)?

There is a patch for the Facet API Bonus module that adds a radio buttons widget.

The issue with the patch is https://drupal.org/node/2034777

With this patch you also need to use the Facet API module patch mentioned by RajeevK in the comments of your question, which can be found at https://drupal.org/node/1393928

If you try those patches and comment back in those issues with how it worked out for you it will also help progress those issues so that the patches can be committed and you no longer have to use patched modules - a win for all.


How to give link to edit in user profile page and node page?

Go to admin/config/system/tabtamer and enable tabs as you want.


Hide the display of a field conditionally

You can alter Add Project content form using hook_form_alter and check for #options in Editors field and if Current User ID exists in #options and then conditionally show/hide price field.

You can also check Conditional Fields module, to see if you get current logged in users details in it. Not sure if it does.

NOTE: You can get current logged in user details in global $user variable.


Conditional class on  element a la boilerplate

There isn't really a great way to do this: Drupal 7 modified drupal_add_css() to make adding conditional CSS possible outside the template file, but not for arbitrary HTML.  Drupal 6 doesn't have anything.

In Drupal 6, and for arbitrary conditional HTML, you either need to add the markup directly  to page.tpl.php, or you could create a variable in your theme's implementation of template_preprocess_page() that contains the relevant markup as a string:

Drupal 7

function foo_preprocess_html(&$variables) {
  $htmlvar = 'xmlns="http://www.w3.org/1999/xhtml" xml:lang="' .
    $variables['language']->language . '" lang="' .
    $variables['language']->language . '" dir="'. $language->dir .'"';

  $variables['conditional_html'] = '<!--[if lt IE 7 ]> <html class="ie6"' . $htmlvar . '> <![endif]-->';
  // Concactenate the rest of the conditional HTML here
}

Then add $condtional_html to the appropriate place in html.tpl.php.

Drupal 6

function foo_preprocess_page(&$variables) {
  $htmlvar = 'xmlns="http://www.w3.org/1999/xhtml" xml:lang="' .
    $variables['language']->language . '" lang="' .
    $variables['language']->language . '" dir="'. $language->dir .'"';

  $variables['conditional_html'] = '<!--[if lt IE 7 ]> <html class="ie6"' . $htmlvar . '> <![endif]-->';
  // Concactenate the rest of the conditional HTML here
}

Then add $condtional_html to the appropriate place in page.tpl.php.

If you're interested in Drupal 7's conditional CSS handling, you can see Bartik's implementation of template_preprocess_html() for an example:

function bartik_preprocess_html(&$variables) {
  // ...

  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/ie6.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'IE 6', '!IE' => FALSE), 'preprocess' => FALSE));
}


Can a theme name be started with a number?

oh, got it- "A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores."

php.net/manual/en/functions.user-defined.php

That answers that question. Don't start a theme name with a number because it can't be used as a function in template.php


I found this simple answer: How to use use Term:Name as a contextual filter


It will remove the rows, when you return FALSE:

if (arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2)) {
  $node = node_load(arg(1));
  $a1 = format_date($node->created, 'custom', 'm/d/Y');
  $a2 = date('m/d/Y',strtotime('-2 months',strtotime($a1)));
  $a3 = format_date($row->created, 'custom', 'm/d/Y');

  $b1 = new DateTime($a1);
  $b2 = new DateTime($a2);
  $b3 = new DateTime($a3);

  if ($b3 >= $b2 && $b3 <= $b1) {
    return FALSE;
  }
  else {
    return TRUE;
  }
}


How do I set some script in the  section on a page?

The function drupal_add_js can solve your probleme.
You can try this in custom module:

function my_module_init() {
     drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/my_file.js',
        array('type' => 'file', 'scope' => 'header', 'weight' => 1000)
      );
}

Look at this documention for use this function in diffrent way.


Is it possible to export arbitrary configurations?

For some of the configurations/settings that aren't picked up by the Features module, there is the Strongarm module.

Strongarm gives site builders a way to override the default variable values that Drupal core and contributed modules ship with. It is not an end user tool, but a developer and site builder tool which provides an API and a limited UI.
An example of such a variable is site_frontpage. In Drupal this defaults to node, which ensures that the front page gets content as soon as some exists, but for many Drupal sites this setting is simply wrong. Strongarm gives the site builder a place in the equation - an opportunity to set the site_frontpage to something that makes sense for their site.

At the time this answer has been posted, the Backup and Migrate module wasn't yet compatible with neither the Features module nor the Strongarm module. See Make backup profiles and schedules Features exportable, (closed as fixed on May 6, 2013) for what exactly the issue was and which branch fixed it. The bug report doesn't contain any patch: The code has been developed in a branch different from the branch for which the issue was opened.


Twig: How to access multiple values from node reference field with number_format

You can get it form the value. something like item.field_component_pages.0.value properly works for you

{% for item in content.field_notes | field_target_entity %}
   {% set field_component_pages = item.field_component_pages.0.value|number_format %}
{% endfor %}


How can I programmatically unselect "View published content" checkbox for anonymous users?

You have to insert this code in a hook_install() or hook_update() :

$role = \Drupal\user\Entity\Role::load('anonymous');
$role->revokePermission('your_permission');
$role->save();


how do i store fields in one table via the install file?

Short answer: You can't.

As consumer of the Field API you don't have any control on the SQL schema when using the default field storage. The Field API however, allow usage of different field storage on a per field basis. It seems that the Per-Bundle Storage module aims to provide the feature you want. But it has no release, only code in its repository. Another solution is to switch field storage for your content type to a separated MongoDB database.


Making taxonomy dropdown on the basis of previously selected dropdown of two different taxonomies?

I think you will have to go for some custom code if you want to use seperate taxonomy vocabularies.

An easier way would be to have all terms in the same hierarchical vocabulary and use Hierarchical Select to create the "populate dropdown"-feature.


Make sure your field output has the correct format in the view - select the 'Add to cart button' in the field formatter.


There are no products in your shopping cart

That issue might be a MySQL problem. I'm assuming here that you dump the live DB and load it in your test machine.

Please check the uid value for the anonymous user in "users" table. The anonymous user is the one with empty fields. The uid value should be 0.

With certain MySQL configurations when loading sql dumps, autoincremental fields cannot accept the 0 value, and gives an incremented value.


Can jPlayer be integrated with the Video module?

I hope I can help you

First of all.

The jplayer you have installed

here is a tutorial that will help get up and running with that Jplayer Tutorial

Second of all, the video module you have, Is for making a new filefield with a new content type, make a view that shows the filefield.
You should either choose one of the following options. and not both of them.

Hope this helps. I am currently myself working on something smiliar.

I would also like to help you by showing you this link

Its a Drupal distribution called Octopus : Octupus Drupal

Hope this helps :)


Can I print an image from a separate content type in my page--front.tpl.php?

You can embed a view inside your front page template, insert this code in propper region. You'll need an image view

// Get the embeded view and render it.
drupal_render(views_embed_view('VIEW_NAME', 'DISPLAY_ID'));

replace VIEW-NAME and DISPLAY_ID with your data, you can find those values in last column on your image view


How can I remove the tab "Subusers" in the profile?

The tabtamer module provides an easy way to remove tabs, both those generated by core as well as those generated by modules.


How can I remove username from title on profile page?

I discovered now that "Page Title" is in a block in Drupal 8. I set this block to not show on /user/*, which worked great.


How to make a sticky post on appear on top within a view

Just sort by sticky and after that sort by date.

As simple as that, it should do the trick for what you want to do.


your code is Ok.

just add the following namespace:

use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

delete in your code:

 user_login_finalize($user);

and

 exit(0);

A complete example would be.

use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

$uid=1;

if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
  $user_destination = \Drupal::destination()->get();
  $response = new RedirectResponse($user_destination);
  $response->send();
ksm($user);
}

if you have installed the

  devel

module and the

  Kint

submodule,
You can use the function

  ksm()

, to show the information of a variable.


To actually fix that error, see my answer to a stackoverflow question.

However, in that case, your code can be simplified a lot using menu_get_object():

$types = array('middle_content' => 1);
if ($node = menu_get_object()) {
  if (isset($types[$node->type])) {
    return TRUE;
  }
}

And anyway, you should avoid PHP in blocks etc (See What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?), check out Context. It allows you to configure your blocks (among other things) for conditions exactly like this without having to write code. It is also much faster.


hook_module_enable() should do the job unless I'm missing something from your question.

  Perform necessary actions after module is enabled.

  The hook is called every time the module is enabled. It should be
  implemented in the module's .install file. The implementation can rely
  on the .module file being loaded.


Override "Display select options" to see them in reversed alphabetical order

there seems to be a patch to change the sort order: http://drupal.org/node/466828#comment-4904174


You missed the position of the string operator . You can try the code mentioned below.

    global $language;
    switch ($language->language) {
    case "en":
    if ($page["sidebar_first"]):
    print "".print render($page['sidebar_first'])."";
    endif;
    if ($page["sidebar_second"]):
    print "".print render($page['sidebar_second'])."";
    endif;
    break;
    case "ar":
    if ($page["sidebar_second"]):
    print "".print render($page['sidebar_second'])."";
    endif;
    if ($page["sidebar_first"]):
    print "".print render($page['sidebar_first'])."";
    endif;
    break;
    }


How do I create a route that is specific for a subdomain?

If you want to set a controller for subdomain you just create a subdomain and handle it by DNS and web server, then set your subdomain path as root path for the subdomain on your web server, I mean both main domain and subdomain will be the same. As you said, you can create a route/controller for them (because the code and modules are the same, so routes will be available on both).

If you don't want the subdomains available on your main domain, on your handler check the domain name; if a request comes from the main domain, don't return the result for it. (Redirecting it to the homepage could be an idea.)

But the power of Symfony shows itself to us: Instead of manually handling the domain and subdomain filtering on the route, use host in the route definition.

   host: "dev.example.com"

Take a look at How to Match a Route Based on the Host for further help about using that directive.


How to import CSV feed into nodes with multiple taxonomy terms?

You just set Search taxonomy terms by: Term name in mapping at Node processor & uncheck Auto create.

Add explode plugin at Feed Tamper tab with string operator such as ||.

Provide multiple value separated by your set string operator and it will work. It works for me at several places.


A responsive thumbnail grid in Drupal 7 node

When you get to this level of customization you need to start considering creating your own page/node templates.

If I was doing this,  my pages for this content would get their own content type,  then I would create a corresponding page template.

These links may be helpful:
https://www.drupal.org/node/982122
https://api.drupal.org/api/drupal/modules!system!page.tpl.php/7

Inside that page template, I would then load the raw data for the node, using node_load  and then access the fields directly and put them inside the appropriate markup.


How to Change the Format of the Email Template Sent with Webforms

Go to: node/%nid/webform/emails/%mid and there is a fieldset (E-MAIL TEMPLATE) where you can define your own email template (per mail account) by using all available tokens and by writting pure html (like <p>, <strong> etc) within the text-area. Don't forget to select "Custom Template".

Read more


In Behaviors, behavior name don't need to be the same as module name. And it cannot be repeated, unless you want to disable earlier implementation.

If you separated your code, it means it's there to do different things. So just name them accordingly, like Drupal.behaviors.mymoduleDoSomething and Drupal.behaviors.mymoduleDoOtherThing.


OPTION 1

In your template file, you could find the set content_classes and add another class name to the list.

{%
  set content_classes = [
    'class-name',
    'class-name-other',
  ]
%}
<section{{ content_attributes.addClass(content_classes) }}>

OPTION 2

In your .theme file

function themename_preprocess_html(&$variables) {
  $variables['content_attributes']['class'][] = 'class-name-other';
}

Note: This preprocess is for the html.html.twig file, you need to use the correct preprocess depending on your template file name.

If it's the node.html.twig then use function themename_preprocess_node(&$variables)

If it's the page.html.twig then use function themename_preprocess_page(&$variables)


Managing different view modes for a single content type

One way to do it:

Set up the default view mode to be a simplified version
Enable display suite extras, then "View mode switcher" under "Other"
In the detailed and simplified view modes, add the "Switch view mode" field
Configure the Switch view mode in each instance to provide links to the other view mode

Your view then should link to your content type with the simplified view and give the user links to toggle the view back and forth between detailed and simplified.

Note that Display suite extras also has a feature called "Switch View Mode", which allows you to set the initial view mode on a node by node basis.

More info in this video: https://www.youtube.com/watch?v=tiUzobRKKco

Edit: I notice that if you enable "Switch View Mode" in DS extras, there is also the option to use view mode switching by URL, by appending ?v=viewmode to the URL. So, that's another option for linking to a specific view mode from your view. In that case, you'd need to use the Rewrite feature of views to build your own Title links that include the extra view mode parameter.


Linking content type nodes with each other

You can actually "link" nodes at any time, you just have to edit the node to add the reference.

If you want to add multiple references, you have to specify this when you set up the node reference field in your content type.  In the configuration page of the node reference field, choose how many references you want to allow (1-10, or unlimited).

For a user to add a reference that did not create the node, make sure the correct permissions are set in admin/user/permissions for the given user role. (ie "edit any EXAMPLE content")


Drupal Installation modules leftovers cleanup

While I personally keep and eye on module listing page and make list of modules to be uninstalled at the time of going live, usually the 'To Uninstall' list contains some UI wrapper modules like views_ui, devel, etc. But searching for any contrib module I came across unused_modules, I think it might be worth trying what this module gives out of the box.

How do you remove folders that are not needed anymore from the sites/all/modules folder?
https://www.drupal.org/project/unused_modules
How do you remove leftover database tables?

You can you schema module, which basically identifies tables and modules relation and also list down orphan tables, this can give you a list of tables which might be just left over tables.
Cleanup test data content.

delete_all module seems to allow to cleanup the test content with different variation via drush.


How to make the Rules module block flagged users from sending entityform submissions?

It seems pretty obvious to me that something in any of your Rules Conditions is not working as you'd expect/want them to work. Which would also explain your "I can't get the rule to not submit".

Basic debugging

You clearly have a combination of Rules Conditions that need some debugging.  Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my Keep-It-Super-Simple technique I often use is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

Also, since you have 3 Rules Conditions in a single rule, you should try to see what happens (if you get a "bingo") for each of the individual Rules Conditions. This by simply (temporary) removing 2 out of the 3 Rules Conditions you are using, and verify if they each result in the Rules Action you'd expect (also just a simple Bingo-message should be sufficient).

Advanced debugging

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

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your node:comments).

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


How can i debug why files are not being created when using migrate files to media module?

You have an an error in your yml file, should be:
# Map the field
field_media_image/title: title
field_media_image/target_id:
    plugin: media_file_copy
    move: FALSE
    reuse: TRUE
    path: 'public://grants/'
    source: file_path

langcode: langcode


Show user email from the user entity to anonymous users

Once you done creating views, go to permission tab and check Role

http://i.imgur.com/zrcSrua.png

in the settings check anonymous, now the user will see the view.


how to display the uploaded zip file content in drupal?

It will not be very hard to accomplish. Don't let anyone tell you otherwise :D

What you need to do (if you have some experience with PHP and creating a very simple Drupal module) is download the PCLzip module which basically integrates the pclzip library into Drupal. There is no submodule for listing zip contents at the moment but it is very simple to make one if you keep in mind that there is a specific method in the library, the ListContent method.

You can see examples of how the methods of the library are used at the related projects that do use the pclzip module like PCLzip Folder or PCLzip Content Files. If you study their code, you will be able to achieve your goal very easily (and hopefully contribute your code back to the community).

Don't listen to advice that say: "extract the contents of the zip file first" since:

There is no need to extract files out of the zip file, you just need to see them
It's never a good idea to add extra complexity and write custom code that will be useful to nobody but you (and after a while so much custom code will be useless to you too)

Keep it simple: use the work of other people and expand it.

Edit: Let me give you an example so that you can understand how easy it is. If you check the pclzip module you will find a function that looks like this:

function pclzip_build_archive($filename) {
  // get the temp file
  global $pclzip_temp_file;
  $pclzip_temp_file = tempnam(file_directory_temp(), $filename);
  // build the archive
  require_once('pclzip/pclzip.lib.php');
  return new PclZip($pclzip_temp_file);
}

The line:

return new PclZip($pclzip_temp_file);

is the one that uses the PclZip method to create a new archive. All you need to do is create a new function, similar to that one, in your custom module, that will use the listContent method to list the contents of the zip file. It's that simple.

Notice, that there is one extra step after retrieving the contents of the zip file, and this is: "displaying them". Since the method of the pclzip library gives you back an array, it should be simple enough to display it (you can choose how you want to do it).

I have tested the following:

Installed the pclzip module
Made sure that the library is in the appropriate directory (according to pclzip instructions)
Added the following code in the pclzip.module file:

function pclzip_nodeapi(&$node, $op) {

  $cckZip = $node->field_zipfile;
  $zipPath = $cckZip[0]['filepath'];
  $zipView = $cckZip[0]['view'];

  if (isset($zipPath)) {
    require_once('pclzip/pclzip.lib.php');
    $zip = new PclZip("$zipPath");

    if (($list = $zip->listContent()) == 0) {
      die("Error : ".$zip->errorInfo(true));
    }

    $zipView .= "
";

    for ($i=0; $i<sizeof($list); $i++) {
      $zipView .= $list[$i]['filename'] . "
";
    }

    $zipView .= "
";

    switch ($op) {
      case "view":
        $node->content['body']['#value'] .= $zipView;
    }
  }
}

Notice that:

field_zipfile is the name of the cck field that I used to upload the zip file
I have edited the pclzip module directly (which is not a very good idea). You should probably do the changes in your own module, but I just wanted to test the solution very quickly
You should decide where the filenames will be printed. I have just added them at the end of the node's content without any specific formatting. you can add classes and specific tags to the filenames in order to theme them if you want.


hook_form_alter setting select list #options key allow attributes per option

Based on theme_select which is the one that constructs and styles the Drupal Form API's select type. It uses the form_select_options function do create the <option> tags.

So you would need to override theme_select and replace the form_select_options function with your own.

Basically, copy the functions and it's content, rename them and do your modifications.


The option is displayed only after activating the "Locale" core module on the admin > modules page.


Problem installing Drush 7 due to missing ext-pcntl PHP extension - any workarounds?

Are such security concerns justified?

Given the description on extension's introduction page, yes:

  Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

Emphasis mine.

But also no, because, as greg_1_anderson stated in his answer, it can be enabled (or even compiled) into CLI only.

Then again, it might be yes. With functions like pcntl_fork it might be possible to make a fork bomb. Other bad things may also be possible. Personally, I wouldn't allow it on shared server.

Is there any workaround for installing Drush 7 without the ext-pcntl dependency?

Not really*, but if you can mount webserver's filesystem on your local machine and tunnel SQL port, you can install drush locally and still use it on remote website. From Drush's point of view there will be no difference.

* Correct me if I'm wrong here.


So it appears that Drupal core neither limits the size of cachetags table and not it provides a mechanism to limit it via a setting, like it offers for other cache bins.
Cachetags table is not cleared on cache reset, neither via web browser no via drush.
There is another issue noted in Drupal core that cachetags table can grow endlessly as has been the case that I have come across.
So a blunt method or periodically cleaning the cachetags need to be performed. Something like follows with drush or direct sql statement via mysql cli client or php-myadmin.
drush sqlq "TRUNCATE cachetags;" -l <uri> --no-interaction


How to print the url and the filename from image field in views-view-unformatted.tpl.php in Drupal 7?

The full file object isn't necessarily loaded into the node object, you could try loading it manually and grabbing the filename/URL that way:

$file = file_load($node->field_slider_image['und'][0]['fid']);

// Filename
print $file->filename;

// URI e.g. public://image.jpg
print $file->uri;

// URL e.g. /sites/default/files/image.jpg
print file_create_url($file->uri);


Upload multiple Standolane Media Entities (Images) without Reference Field

The Media Bulk Upload module will allow you to upload many images at once.

This is the Drupal 8 module to bulk upload files and create the media
entities automatically for them. It uses DropzoneJS
to quickly upload multiple files.

The bulk uploader will allow you to edit fields on the media item before saving. You'll want to set alt text for each image, and your Taxonomy Term reference.


In custom install profile How to delete the "Footer" menu that core provides by default?

Solved.

Following https://drupal.stackexchange.com/a/186322/8938  I added the code below to  my_profile_install() function inside my_profile.install file.

  \Drupal::configFactory()->getEditable('system.menu.footer')->delete();

Reinstalled and yes, footer menu is not around anymore :)


Subscribe/Unsubscribe link to a group's content type using Notifications & OG

OK, I eventually figured it out:-

notifications/subscribe/[uid]/grouptype/group,type/[gid],[type]


create an commerce order list view with payment method

As per the "... which causes duplicates ..." in your question: you may be able to prevent those by using the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

Consider an example like so (with the duplicates included):

order id1 with payment id1
order id2 with payment id2
order id2 with payment id3
order id3 with payment id4

For this example, to only show the last payment method, sort by payment id (but descending!), and on the order_id filter repeats. So that only the last row for every order_id will be shown.

The new Views results with these changes applied for the above example should now look like so (with no more the duplicates related to payment id2):

order id1 with payment id1
order id2 with payment id3
order id3 with payment id4


How to trigger rules action if cart is empty?

You could try adding a rule that looks at the total number of items in the cart. Just get the count of the line items list within rules.


Check the user account settings in page admin/user/settings, the option for changing user picture is "Picture support."


As i understand you could use something like this '#type' => 'file'

  $form['image_file']=array(
    '#type' => 'file',
   '#title' => t('Upload YourImage'),
    '#upload_validators' => array(
    'file_validate_extensions' => array('gif'),),

        );
return $form;


Drupal 7 - How do I parse JSON data from a website and import them as Nodes and have them update hourly?

I think you have a problem with the "context", and title query. I've tried this configuration and worked for me.

The context is the first query and in this case just selects all the nodes, the second one takes the value of the key "last" ant put it on the node title.

Then you can play with other querys, to create the nodes, but at least this one works.


You can use markup module to add html text as fields to the article content type.

If you want to show the html text only in edit page then you need to use hook form alter

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form' && arg(2) == "edit") {
    $form['contact_information'] = array(
      '#markup' => 'Your message goes here !',
    );
  }
}


The Clientside Validation module adds classes 'valid' and 'error' to all form elements. You could use the class 'valid' to add the green mark simply with some css.


How to update a views row class in real time clicking a Flag (ajax) link

Add a javascript file to your theme, or if you're using a theme that has a template, use that.  Omega 4 has a brilliant template file with explanations on how it works and a short example.  There is also a very good tutorial on using javascript and JQuery with Drupal on Drupal.org.

Basically I would set a click event on the flag checkbox and then use the .closest() method to find the row which the checkbox is inside and add or subtract classes accordingly.


How to disable a block on a certain view?

If the view path is /all-albums then try entering all-albums in the block under Show block on specific pages: All pages except those listed, not the full url or the machine name.


How can I pass a query string from the url to a hidden user form field?

You may be able to do a hook_form_alter() and call \Drupal::request()->query->all() (or \Drupal::request()->query->get('reg-id')) to access the query parameters to pass it to your hidden form field.

See https://api.drupal.org/api/drupal/vendor%21symfony%21http-foundation%21Request.php/property/Request%3A%3Aquery/8.2.x and https://www.drupal.org/node/2150267.

For example:

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, FormStateInterface $form_state) {
  // Get the query parameter with 'reg-id' if it exists.
  if ($custom_id = \Drupal::request()->query->get('reg-id')) {
    $form['hidden_field'] = // Do whatever you need here;
  }
}


How do I delete all book page nodes, book outline, and uninstall book module

It sounds like you have orphaned book content. You can go look for any nodes of type book page at /admin/content, and delete them all. Also, check your configuration of the book module to see if any other content types are enabled as book content. You may have to determine which nodes of those content types have been created as book pages but not assigned to an outline.


Restrict access to ECK full page, but allow embedded

It turns out that though the entities created by ECK are dynamic, they do have route definitions, so we can use this to restrict access, in a hook_preprocess_page placed in a custom module.  Also worth noting that the administrative list display at /admin/content/my_eck_entity is visible to anonymous users when you set the view my_eck_entity entities permission to anonymous users, so we must also look out for this route as well.

use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Prepares variables for page.html.twig.
 */
function mymodule_preprocess_page(&$variables) {
  $route_name = \Drupal::routeMatch()->getRouteName();

  // Restrict access to ECK canonical full page display and the entity
  // administration list screen to content authors. Restricting full page
  // display helps to avoid mistakenly indexing the content in search engines
  // because these entities are only ever going to be seen by anonymous users
  // when embedded into other pages via WYSIWYG embed or rendered entities
  // from entity reference fields on other node types.
  $user = \Drupal::currentUser();
  $restricted_eck_entities = [
    'my_eck_entity', // Replace this with real entity type machine name!
  ];
  foreach ($restricted_eck_entities as $eck_entity) {
    if (
      (
        $route_name === "entity.$eck_entity.canonical"
        || $route_name === "eck.entity.$eck_entity.list"
      )
      && !(
        $user->hasPermission("create $eck_entity entities")
        || $user->hasPermission("edit $eck_entity entities")
      )
    ) {
      throw new AccessDeniedHttpException();
    }
  }
}


You can also use the Relation module to implement this. It depends on how teachers are assigned. Are teachers assigned to students ? or lessons ? based on this you can create a relation using the UI and assign teachers. For displaying information relation module integrates well with views, rules, cck and is very easy to create one.

I also used the module in my project where communities can have objectives and goals. I use the relation module to create relations and use the views to display the connections from the community.

I would also recommend you to watch relation tutorial if you want to learn more about it.


how to send muliple emails in drupal in same time

If you want to send same mail to donor, charity and delivery service, then you can use CC feature of the mail.

$message['headers']['CC'] = "myemail@me.com";


How to use profile 2 to display user profile page with comments enabled?

Not sure what you mean by default comments, but I doubt you can use core comments with Profile2 entities. The comment module only works with nodes.

See this core issue for work being done in this area.

Check the Profile2 issue queue for potential workarounds for comments.


I used the hook THEME_image_formatter to accomplish this.  It would be fairly easy to create a module to do this I just haven't had the time.  Anyway here is what I did.

function THEME_image_formatter($variables) {
  $item = $variables['item'];
  $image = array(
    'path' => $item['uri'],
  );

  if (array_key_exists('alt', $item)) {
    $image['alt'] = $item['alt'];
  }

  if (isset($item['attributes'])) {
    $image['attributes'] = $item['attributes'];
  }

  if (isset($item['width']) && isset($item['height'])) {
    $image['width'] = $item['width'];
    $image['height'] = $item['height'];
  }

  // Do not output an empty 'title' attribute.
  if (isset($item['title']) && drupal_strlen($item['title']) > 0) {
    $image['title'] = $item['title'];
  }

  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = '';
    // I targeted the blog post image style to add to all blog photos.
    if($image['style_name'] == 'blog_post') {
      $output .= '
';

      $media = urlencode(file_create_url($item['uri']));
      $title = variable_get('site_name', '') .' - '. str_replace('+', '%2B', $variables['item']['title']);
      $path = $variables['item']['path'];

      $output .= '

';
      $output .= '';
      $output .= variable_get('site_name', '') .'
'. $variables['item']['title'];
      $output .= '

';
    }
    $output .= theme('image_style', $image);
    if($image['style_name'] == 'blog_post') {
      $output .= '
';
    }
  }
  else {
    $output = theme('image', $image);
  }

  // The link path and link options are both optional, but for the options to be
  // processed, the link path must at least be an empty string.
  if (isset($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = isset($variables['path']['options']) ? $variables['path']['options'] : array();
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
    $output = l($output, $path, $options);
  }

  return $output;
}

Just pay attention to the blog_post check and output that I created.  I have some javascript that shows and hides the button on hover but you can add that if you want.

Dont forget to add your pintrest JS to the head of your doc.

--Good Luck


How to grant access to specific nodes to anonymous users?

If you need content access to roles by content types, you can try using Content Access module.

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.


How to assign permissions to roles programmatically?

Features is pretty handy for stuff like this. However, if you do need to create roles and add permissions programmatically, you don't have to go digging through the database on your own.

When you create a new user role with user_role_save(), it will update the object you passed in with the new user role id that was assigned. You can see an example of this in the standard_install() function in the Standard installation profile.

$admin_role = new stdClass();
$admin_role->name = 'administrator';
...
user_role_save($admin_role);
user_role_grant_permissions($admin_role->rid, array_keys(module_invoke_all('permission')));

This example shows that you can create a new user role, then access its rid property, which was filled in by user_role_save(). It also shows how to add permissions to that role with user_role_grant_permissions(). In this case, it's granting the 'administrator' role all available permissions.

If you need to get the id of a user role created by someone else, you can use user_role_load_by_name() to get the object for that user role. Then you just grab the id with $role->rid.


how to add one form element into another form?

Probably you should do it programatically.

Use hook_form_alter to modify form A, load data of form B by drupal_retrieve_form inside this function and get fields from form B data which you want to add them to form A


ImageCache or different CCK image fields?

Imagecache can crop. Exact or relative dimensions.

And yes, you can choose the preset for an image field in views. It is very easy. And you can manipulate it with code, but that would be much more complex. I don't think you need this.

If you really need the publishers to manipulate the image on the node edit form, just use IMCE. It integrates with Imagecache, so they could use that.

But the more you can automatize the process, the better.

So try to allow your publishers to send images the way they like (only being bigger than the minimum size you will ever use), and then you use imagecache dynamically to crop and resize the images the way you want over all the places on your site.


How to change Omega subtheme's layout for a view

Wow wow, little bit syntax failure with the wrong function caused a disturbance in the force.

Here is how:

function mytheme_omega_layout_alter(&$layout) {
  if (arg(0) == 'node' && is_numeric(arg(1))
      && $node = node_load(arg(1)) && $node->type == 'article') {
    $layout = 'article';
  }
  else if (($view = views_get_page_view())
        && $view->name == 'term_content' && $view->current_display == 'term_page') {
    $layout = 'term_page';
  }
}

PS: This is going to the community wiki as the internets don't have an answer about it!


Configuration export/import doesn't work

Configuration management is exporting exactly what it was designed to do: Export the configuration settings. The actual taxonomy terms themselves are sitting in the taxonomy_term_field_data table in the database.


Add bootstrap row class on every n views rows

Use views bootstrap module, in views format style chose Bootstrap Grid it will solve your problem.


Seems now you know the answer :)

https://www.drupal.org/project/commerce_bulk/issues/3035971


Create database fields to an existing table when installing a module

There are a couple of inconsistencies with the question and code so I am not sure whether or not this can be accepted as an answer to the strict question "How do I create database fields to an existing table when installing a module".

"user_extra" is defined as a new content entity. What this means is that it is a fundamental new thing that is not related to a Drupal User entity nor the User entity's storage. This might be a similar use case to Profile2.
Modifying base field definition is probably a bit too heavy/complex for adding in the "user_office" and "user_extra_id" data that your site needs. The "Drupal Way" would be to add a "Bundle Field" to the entity.

This could be done as a site builder in the user interface (See Configuration > People), programmatically or providing YAML in config/install (Berdir). See field.storage.user.user_picture.yml.
Adding many fields to the User entity may have a performance impact, which could be solved by using a module such as Profile2 to only load that information on certain pages.


You can use hook_services_request_preprocess_alter() and hook_services_request_postprocess_alter() hooks of Services module.


How to assign default values for an edit form?

You need to check that value returned by _get_this_domain_id() function is in the array key used to create #options for form element ['field_genric_domains'] .

Example :

If _get_domaine_options() function returns array as :

array(1=>'India',2=>'USA');

Then _get_this_domain_id() should return key either 1 or 2 .That will set the default value depending on the array key .


How to edit and delete drupal 8 custom block content?

Visit your block library, there's a tab on blocks page.

Block library can be found here:
/admin/structure/block/block-content


I think there may be a solution using a RewriteRule in .htaccess.

Imagine I have the url /some-page

Now if I go to /someTESTpage

and I put this in .htacess:

RewriteEngine on
RewriteRule ^(.*)TEST(.*)$ /$1-$2 [L,R=301]

Then it redirects to:

/some‒test

Problems still to solve:

1) In the redirect URL that is an en-dash so is still the wrong url. Not sure how to get it to insert the correct character.

2) When I put a percentage sign in the string to be replace the whole thing stops working. Not sure how to escape a percentage sign in a RewriteRule.


A simple solution is to add image again as a field and Rewrite Results:

Now in your template:

... alt="{{ fields.field_image_1.content|striptags }}" ...


How to customize user edit page drupal 7?

It's a little different for Drupal 7... The structure of the file name would be page--user--edit.tpl.php (for D7) as opposed to page-user-edit.tpl.php (for D6).

Also, remember to clear the cache after you make any such changes so that they're recognized.

Hope that helps... :)


How can I add a extra feature to repeating date field?

Field Collection is exactly what you looking for. It allow you to create a group of fields, and then add this group of field as a field on your content-type (and made it repeatable as your date field).

In your case, you create a field collection constituted by a checkbox field, and a date field. Then add this field collection to your Tasks content-type and made it repeatable (Unlimited).


How to send user to the billing information page immediately after logging in?

Check out Login Destination module - it allows you to define destination rules for logging in/registering users and even use PHP snippets for custom conditions.


Handling shared content without multisite?

You could have a look at the Feeds module. You should set up one site as master (where news and events are entered) and use the Views module to publish an RSS feed of the content you want to share. Now on the other sites, you install the Feeds module and configure it to pull in the RSS feed and import the content from the master site.

Downsides to this approach:

There will be a delay between the publishing on the master site and the import on the other sites.
This especially works well when all content is entered on site. If you need content to be entered on all sites, things quickly get more complex.
Once the content is distributed from the master site to the other sites, it can be edited on all sites, but the changes will not be synchronized across all sites.


Form API Submit Button for Multiple Forms

Not really. Drupal form may try to redirect you after successful submit. If 3 forms try, which redirect should work? And that's only one example.

Create fourth form function. In it, call all 3 existing ones, clean up mess with submit functions, validators and redirects, and it should work. Or simply merge your forms into one, why you needed three?


How do I programmatically change the admin theme?

As the context module is still in alpha I would try a solution in custom code by extending the class AdminNegotiator:

src/Theme/CustomAdminNegotiator.php

<?php

namespace Drupal\mymodule\Theme;

use Drupal\user\Theme\AdminNegotiator;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAdminNegotiator extends AdminNegotiator {

  public function determineActiveTheme(RouteMatchInterface $route_match) {
    if (in_array('custom_role', $this->user->getRoles())) {
      return 'custom_admin_theme';
    }
  }

}

and register this service class in mymodule.services.yml tagged as theme negotiator with a priority higher than the default admin negotiator (-40):

services:
  theme.negotiator.admin_theme.custom:
    class: Drupal\mymodule\Theme\CustomAdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -39 }

The applies() method is kept the same as in AdminNegotiator, so that only users with the correct permission have access to this theme and this only applies for admin routes.


Which files should I delete after a Drupal installation?

You shouldn't really delete any files. If you really wanted to, you could delete the install file and various txt files, but that's about it. A better solution if you are afraid of security is to not let the files be accessed through the web server. Drupal only use the index.php file for serving content.


How to change the url the core search form submits to?

You can use hook_form_alter or hook_form_FORM_ID_alter to alter a form.
Core's search block form has a form id of search_block_form, so you could implement with hook_form_FORM_ID_alter() like:
use Drupal\Core\Form\FormStateInterface;

function mymodule_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['#action'] = '/my-custom-path';
}


Do you have change the taxonomy term name manually or the url alias?
If you only have change the name you must to check the field "Generate automatic URL alias" is checked to change the url automatically.

If is checked or you have change URL alias manually then clear cache in /admin/config/development/performance

I hope that helps.


500 (Service unavailable (with message)) on login or register

As you have access to the database through PhpMyAdmin, have a look in the watchdog table for any errors.

Disable anything causing an issue ;)


#autocomplete_path doesn't present a "spinny thing"

What you should do is change $item inside your menu() hook to be

$items['cao_contenttypes/user/autocomplete'] = array(
    'title'            => 'Autocomplete C&O users',
    'page callback'    => 'cao_contenttypes_ceao_handler_users_autocomplete',
    'access arguments' => array('C&O Administrator'),
    'type'             => MENU_CALLBACK,
);

eg, remove the trailing % (Drupal will add in the string for you just fine when it has one) and then inside your callback do something like this:

function cao_contenttypes_cao_handler_users_autocomplete($str='') {

  $list = array();
  if ($str) {
    // choose users from among a limited subset
    $users = _cao_contenttypes_cao_handler_users();
    array_walk($users, function ($item) use ($str, &$list) {
      $comp = substr($item->name, 0, strlen($str));
      if ($comp == $str) {
        $list[] = $item->name;
      }
    });
  }

  drupal_json_output($list);

}

eg, give $str a default value and always return the array of results, even if empty.

Additional comment:  Consider cache()ing the output of _cao_contenttypes_cao_handler_users() if it is a heavyweight function.


Every time it calls the hook, the variables may or may not have the array key 'attributes' - so the error happens on certain hook call, but not others. It's easy to fix, just check if it exists

function MYTHEME_theme_suggestions_item_list_alter(array &$suggestions, array $variables) {
  if (!empty($variables['attributes'])) {
    $moduleclass = str_replace('-', '_', $variables['attributes']['class']);
    $suggestions[] = 'item_list__' . $moduleclass;
  }
}


You would need to add a relationship which would be the Quiz Result : User.

Then you would find the quiz result : score in the fields


How can I add a variables to my page.html.twig file?

There is no index called header_attributes inside $variables array no need to create it, there is page index just use it:
Try this out:

function [yourThemeName|yourModuleName]_preprocess_page(&$variables){
  $variables['page']['header_attributes']['class']= 'myClassHere';
}

Note don't forget to clear cache.
In your twig you will get your class by:

page['header_attributes']['class']


Figured it out - put it the ID request in to an array:

$form['#attributes'] = array('id' => array('payment_form'));

Instead of

public function getFormId() { return 'payment_form'; }


How do we use drupal_add_library(), drupal_add_css() and drupal_add_js()?

Drupal_add_js() and Drupal_add_css() are quite simple to write in Drupal 8.

We basically create a module_name.libraries.ymlfile having list of all the jss and css that we wish to use.

An example of which is

name_of_the_key: // This would basically work as a key for you.
  version: 1.x
  js:
    js/name_of_your_js_file.js: {}  // Name of your js file
  dependencies:  // Adding dependencies if you have any.
    - core/jquery
    - core/drupalSettings
  css:
    theme:
    css/name_of_the_css_file.css: {} // Name of your css file.

This would basically add all the files but would not attach these files to your page/form.

So in order to attach the js and css to your page/form, you simply replace

drupal_add_js()
drupal_add_css()

with

$form['#attached']['library'][] = 'name_of your_module/name_of_the_key'; // Name of the key would be the key that you have defined in module_name.libraries.yml file.

So if your module uses different js and css file at different points in a forms/pages you could define n number of keys in your libraries.yml file and use it accordingly.

Source: https://www.drupal.org/node/2274843 and guidance form AjitS.


How to give custom function in D8 custom field widget class?

Because this is your custom widget, you don't need to create a custom submit function.

Just add WidgetBase::massageFormValues method to your class:

class CertfieldDefaultWidget extends WidgetBase {
  ....
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    // manipulate with $values where $values is an array of your fields defined in your formElement.
    return $values;
  }
  ....
}


How to translate the title, axis labels and legend of a chart?

Here are the steps to create a translated version of a chart (or more general: a report) using the Forena module:

Make sure (core) module locale is enabled.
Instead of using the "edit" icon to change the specs of a report, use the "translate" button next to edit. Then select the language to which you want the report (chart) to be translated.
On the next screen, enter the translated report (chart) title.
You should get some informational message as in this example (in which I created a 'nl' version of drupaladmin/active_users, for which I changed the tite from "Active users" to "Actieve Gebruikers"):

  Translation, Actieve Gebruikers has been created. Switch languages to translate.

  Your report, nl/drupaladmin/active_users has been saved.

After switching your active language to the language for which you want to create a translated version, you'll be able to change anything of the report (charts) specs to the specs of your additional language.
In your case here, you can now modify those 4 strings

Bottomline: tranlating Forena reports is similar to translating nodes.


Need help to work with videos and FFMPEG

The only advantage these modules is assistance in managing your dependency on FFMPEG and how you want interface it in PHP code.

PHP FFMPEG is a helper module for managing a dependency on the PHP FFmpeg library. If you want to use the PHP FFmpeg library, and require a Drupal module that will ensure your module has FFMPEG available to it, this module will help.
FFmpeg Wrapper is a handful of custom functions that interface with FFMPEG via PHP's passthru() function. If your PHP environment can execute passthru() and you want some basic functions to execute some ffmpeg console commands, this module will help.

Both are API modules that don't provide any other integration with Drupal.


Hi Rich who isn't the normal Drupal developer and was left to learn on his own. Welcome to Drupal.

I've encountered scenarios in which I had an exposed sort with a dropdown list and I needed to remove all the options that didn't fit my pattern. I used a hook_form_alter() that modified the '#options list for the element to unset() the items I didn't want to allow the user to select. However, this method doesn't prevent those items from showing when -All- is selected, so that may not work if that's an option for your users.

The way you'd add a new field is to create a custom field handler but it sounds like what you want might instead be a custom sort handler or a custom filter handler. The three are similar but not identical in their implementation.


Can drush return if site is in maintenance_mode?

i think if drush says maintenance_mode set to "0" it is set to 0,  none the less you can check drush variable-get but it will return 0


Use Drupal's AJAX Form functionality to add elements to a form from the client.

If you try to update a Drupal form with JavaScript on the client side, it will not be submitted correctly. Drupal knows what was in the form when it was sent to the client, and expects that same structure to be sent back. Therefore, you need to use AJAX to tell Drupal the form is updated (with more fields, etc.).


did you translate the site using any module

go for Content Translation core module: http://drupal.org/documentation/modules/translation


Missing bundle entity, entity type block_content_type, entity id basic

To get passed this error I deleted some rows in the config table:

delete from config where name in ('block_content.type.basic', core.entity_view_display.block_content.basic.default', field.field.block_content.basic.body');


OpenLayers module only displays latitude/longitude instead of map

Go to your display settings for your content type and choose 'OpenLayers', then click the gear icon and Select which OpenLayers map you would like to use. Only maps which have the geofield placeholder layer may be selected. If your preferred map is not here, add the geofield placeholder layer to it first.


pass php page to page callback with hook_menu

The value to 'page callback' can only be a function name.

If you must use 'a whole PHP/HTML page' then work around by using the hook_theme.

<?php
function my_example_menu() {
  $items['my/example'] = array(
    'title' => 'My title',
    'page callback' => 'my_example_page', /* callback function */
'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
);

return $items;
}

/**
 * Implements hook_theme
 *
 */
function my_example_theme($existing, $type, $theme, $path) {
  return array(
    'the_html_page' => array(
    'template' => 'the-html-page', /* create file with this name + .tpl.php */
  ),
);
}

function my_example_page(){
  return theme('the_html_page');
}
?>

The value of 'template' in hook_theme() is the name of your file. Create the template file with .tpl.php extension and place it in the same directory as your module. You can put any html that you need in the file.


D7: How to deal with the variables visibility?

For the maximum visibility use global variables like below

$a = $_POST['a'];
$b = $_POST['b'];
global $c;
$c = $a * $b

and you can anywhere like below,

function mail_send($form_values) {
  global $c;
  print_r($c);
}

There is no special methods exists in drupal, it is just like php.


Creating breadcrumbs based on content type relationships

For the time being I was able to figure it out by adding node reference fields to each of the content types. Then referencing my items to the chapters. I then found the Corresponding Entity Reference Module and used that to link them up. Using Custom Breadcrumbs I could use the reference tokens to create my breadcrumb.

Only downside is that I had to go into each item node. Took some time!


how to overide prvatemsg url 'messages' to 'something'?

If what you want is to do a redirect to a thank you page after you handle your form posted data then just add to your function a redirect via a call drupal_goto().

Something like this:

function _MY_MODULE_custom_submit($form, &$form_state) {
  // process your form stuff...
  drupal_goto('thank-you');  // redirect to page 'thank-you' providing this is one of your drupal pages
}


How do I display a link as an embedded player?

Another method is to create you own module.   Checkout Media Link

Below is the code you would need. This module adds a podbean audio player display for your link field.  Modify the theme code for your embedded player.  Another good place to look at is the field example module.

Again, this module requires the Link module

<?php

/**
 * @file
 * Defines a display format for a link that will embed a player.
 */

/**
 * Implements hook_field_formatter_info().
 */
function media_link_field_formatter_info() {
  return array(
    'audio_player' => array(
      'label' => t('Audio Player'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'field types' => array('link_field'),
    ),
    /*
    'video_player' => array(
      'label' => t('Video Player'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'field types' => array('link_field'),
    ),
    */
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function media_link_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  foreach ($items as $delta => $item) {
    $elements[$delta] = array(
      '#markup' => theme('link_formatter_'. $display['type'], array('element' => $item, 'field' => $instance)),
    );
  }
  return $elements;
}

/**
 * Implements hook_theme().
 */
function media_link_theme() {
  return array(
      'link_formatter_audio_player' => array(
          'variables' => array('element' => NULL),
    ),
  );
}

/**
 * Theme function for 'audio player' link field formatter.
 */
function theme_link_formatter_audio_player($vars) {

  $url = $vars['element']['url'];
  return "<div>" .
  "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width='210' height='25' id='mp3playerlightsmallv3' align='middle'>" .
  "<param name='allowScriptAccess' value='sameDomain' />" .
  "<param name='movie' value='http://www.podbean.com/podcast-audio-video-blog-player/mp3playerlightsmallv3.swf?audioPath=" . $url . "&autoStart=no' />" .
  "<param name='quality' value='high' /><param name='bgcolor' value='#ffffff' /><param name='wmode' value='transparent' />" .
  "<embed src='http://www.podbean.com/podcast-audio-video-blog-player/mp3playerlightsmallv3.swf?audioPath=" . $url . "&autoStart=no' quality='high'  width='210' height='25' name='mp3playerlightsmallv3' align='middle' allowScriptAccess='sameDomain' wmode='transparent' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' /></embed>" .
  "</object>" .
  "</div>";
}

?>


Features installed with profile are overridden

Apparently things in a profile info file are loaded before things in a profile install file.  I moved the two features from the info file into the install file and put them last.  After a new site install, the features were not overridden and worked as expected.


Add target="_blank" to menu item of type MENU_LOCAL_ACTION

There seems to be a module for this: Menu target.

In case you need to do it programmatically, you can have a look at the source code for inspiration. As far as I see, the module adds a special class to the menu items you select, and then some JS captures the click and opens a new window:

  $('a.target-blank', context).once('target-blank', function () {
    $(this).click(function() {
      window.open(this.href);
      return false;
    });
  });


Any way to export webform node to other installation?

Have you tried the Webform share module (it is a helper module to prepopulate newly created webforms and to export / import webforms between sites), it may be helpful for this scenario as it provides the following feature:

  Example usage 1: Prepopulated webforms

Create a webform with the required components.
Export the webform
Edit the webform content type and paste in the content from the export (under Publishing options)
Use the standard node add content links and each new content item created should be prepopulated with the exported webform.

  Example usage 2: Synchronization of webforms

Export the webform that has the settings you want
Import these over the existing webform.

Note: Existing webform components are replaced with the new webform components. If a component is dropped or the key is renamed, you will no longer have access to any user submitted data.


Yes, you're right: Modules are still modules, the equivalent of what WordPress calls plugins. Each module can implement one or more plugins.

For example, the Voting API module has a plugin for each of the methods to show the result: Average, Sum and Count.

Plugins also needs a plugin manager, which is the responsible for actually calling the plugins.

You can see this on:

https://github.com/pedrorocha-net/votingapi/blob/8.x-1.x/src/Plugin/VoteResultFunction/Average.php
https://github.com/pedrorocha-net/votingapi/blob/8.x-1.x/src/VoteResultFunctionManager.php


How do I get all children's taxonomy term IDs?

You are close, but you want to pass some additional parameters to that method.

$vid = 'my_vocab_machine_name';
$parent_tid = 87; // the parent term id
$depth = 1; // 1 to get only immediate children, NULL to load entire tree
$load_entities = FALSE; // True will return loaded entities rather than ids
$child_tids = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, $parent_tid, $depth, $load_entities);

See the api documentation for more info.


How do I render a field value including its format?

While you could spend a lot of time dissecting how the Field API works, you really should be using the Field API directly to render field content instead of querying the database yourself. There's a lot of encapsulation and abstraction added to fields that will awaken the Old Gods if bypassed.

Using the Field API, if you want the whole formatted field, complete with label and all values, you want to use field_view_field():

$nid = 1;
$node = node_load($nid);
$output = field_view_field('node', $node, 'field_foo');

// $output is a render array, so it needs to be rendered first
print render($output);

If you just want to display the formatted value of one item in a field, you need to use field_view_value(), which is a little more involved:

// Must load field content for entity before using field_view_value()
$fields = field_get_items('node', $node, 'field_foo');

// $index corresponds to the value you want to render. First value = 0.
$index = 0;
$output = field_view_value('node', $node, 'field_foo', $fields[$index]);

print render($output);

If you want to use a formatter other than the default specified for the field instance, pass it using the $display parameter in either field_view_field() or field_view_value():

$display = array('type' => 'my_formatter');
$output = field_view_field('node', $node, 'field_foo', $display);


How to filter by two fields using a single exposed filter in Views?

I think you could either:

Use the Global: Combine fields filter which allows you to choose two fields (out of those already added to the display as a normal field) to filter on. The filter can be exposed, its operator changed, etc. like normal. Views warns This filter doesn't work for very special field handlers.
Use the Search: Search Terms filter. This uses search.module's data to do the query (check out the search index build mode).


Return table and item-list, but only table is displayed

Your are mixing render arrays and html, use for both table and itemlist the same:

$build['itemlist'] = array(
        '#theme' => 'item_list',
        '#type' => 'ul',
        '#items' => $products,
        ...,
);


You can use
uc_payment_balance() function to know how much the customer still owes to you.

  uc_payment_balance($order)

where $order - the order object


If I understand you correctly, you want to redirect everyone to the www version of the site.
How about this.

RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

It will redirect anything that isn't www.example.com to www.example.com and pass along the url.

http://httpd.apache.org/docs/2.4/rewrite/intro.html has more options you can use.


Add a trademark to a word everywhere on a site

You can use "String Overrides" (http://drupal.org/project/stringoverrides) module to accomplish what you want to do and it will work even if JavaScript is disabled and the changes will be cached as well by the Drupal cache.

Note: This will work with content pass by the t() function, if you have the word hard coded on the theme or module it will not work. Also it is CaSe SeSiTiVe.


Custom RESTful api GET request only works if user is already logged in, although _access has been set to 'TRUE'

The problem of no json output was, it turned out, because the site was under maintenance mode! And like Berdir said 503 is not access denied error!


How to submit multiple patches to a contrib module?

if these 3 fixes/patches unrelated, I would go with first option as it keeps things clear and if any of these patches introduces any other issues/conflict it will be easier to maintain it. I understand how this is time consuming, but it's better if you do it the right way.


how do i modify the paypal order details?

There is a patch in the queue that supports sending itemized information to PayPal, but it was never completed / integrated as far as I know. It gets tricky when you itemize, because any rounding errors in taxes, discounts, etc. triggers a failure to accept payment at PayPal.

In order to do this yourself even without the code being part of the module, you'd need to alter the form used to redirect to PayPal or the API request used to process the payment. Either of these would be possible in a custom module using hook_form_alter() or the relevant alter hook from the PayPal module for the payment method you're actually using.


Date range field misses the minutes when they are the same

Hope you are using core date module with end date. If you are, here is my field configuration in content type:

Once have the field configured with custom date format, the display seems working as expected.

Let me know, if I missed configuration details here.


Cannot modify language field in node form using hook_form_alter in drupal 7

Your code doesn't work because the node edit/create form sets $form['language'] using the following code. (See node_form().)

  // Basic node information.
  // These elements are just values so they are not even sent to the client.
  foreach (array('nid', 'vid', 'uid', 'created', 'type', 'language') as $key) {
    $form[$key] = array(
      '#type' => 'value',
      '#value' => isset($node->$key) ? $node->$key : NULL,
    );
  }

It's then the Locale module that changes the form field in locale_form_node_form_alter() using the following code.

  if (isset($form['#node']->type) && locale_multilingual_node_type($form['#node']->type)) {
    $form['language'] = array(
      '#type' => 'select',
      '#title' => t('Language'),
      '#default_value' => (isset($form['#node']->language) ? $form['#node']->language : ''),
      '#options' => array(LANGUAGE_NONE => t('Language neutral')) + locale_language_list('name'),
    );
  }
  // Node type without language selector: assign the default for new nodes
  elseif (!isset($form['#node']->nid)) {
    $default = language_default();
    $form['language'] = array(
      '#type' => 'value',
      '#value' => $default->language,
    );
  }

If your module is executed before the Locale module, its changes to the language form field are not retained, as the Locale module set $form['language'] to a different array.

In order for your code to work, you need to change the weight of your module, or implement hook_module_implements_alter() to alter the order hooks are executed.

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Move mymodule_form_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

This code changes also the order in which hook_form_FORM_ID_alter(), and hook_form_BASE_FORM_ID_alter() are executed.