How to add an image upload field in a custom Field Type I'm defining a new custom Field Type in Drupal 8, let's say MyFieldType, with custom widget and formatter also.

Such Field Type should have these two fields:

text: a simple text value
image: a field where the user that use this Field Type can upload an image, as the built-in image field type.

I created the custom field type with the text field with no problems. Now I'm trying to add the image field also, but I'm stuck and I don't understand how to proceed.

What is the correct way to add an image upload field in a custom Field Type?

What I tried

Below there are the main parts from the custom Field Type. All files are from the folder modules\custom\my_field_type\src\Plugin\Field.

From the file FieldType\MyFieldType.php:

class MyFieldType extends FieldItemBase {

  //

  public static function propertyDefinitions(
    FieldStorageDefinitionInterface $field_definition
  ) {

    $properties['text'] = DataDefinition::create('string')
        ->setLabel(t('Text Value'));

    // $properties['image'] ... go here?
    // ...

    return $properties;
  }

  //

  public static function schema(
    FieldStorageDefinitionInterface $field_definition
  ) {

    $columns = array(

      'text' => array(
        'type' => 'varchar',
        'length' => 255,
      ),

      // What column for the 'image' field?
      // ...

    );

    $schema = array(
      'columns' => $columns,
    );

    return $schema;
  }

}

From the file FieldWidget\MyFieldTypeWidget.php:

class MyFieldTypeWidget extends WidgetBase {

  public function formElement(
    FieldItemListInterface $items,
    $delta,
    Array $element,
    Array &$form,
    FormStateInterface $formState
  ) {

    $element['value'] = [
      '#type' => 'textfield',
      '#title' => t('Value'),
      '#default_value' => isset($items[$delta]->value) ?
          $items[$delta]->value : null,
      '#empty_value' => '',
    ];

    $element['image'] = [
      '#type' => 'file',
      '#title' => t('Image'),

      '#default_value' => isset($items[$delta]->image) ?
        $items[$delta]->image : null,

      '#empty_value' => '',
    ];

    return $element;
  }

}

I can see the file upload field in the edit form (adding a new field with this custom type), but I don't know how to go on and (eventually) how to handle the uploaded image inside the class MyFieldType.

What you want to do, is to save a reference to the file which is uploaded.

Since what you are making is an image upload with extra text field, you should consider using either

\Drupal\image\Plugin\Field\FieldWidget\ImageWidget
\Drupal\image\Plugin\Field\FieldWidget\FileWidget

as foundation to your widget. That way you should be able to reuse much of the trick image/file handling and just add custom parts or overrides for your custom widget.

You should also consider using either

\Drupal\image\Plugin\Field\FieldType\ImageItem
Drupal\file\Plugin\Field\FieldType\FileItem

as foundation to your field type, since they also handle a lot of things for you. The image variant adds a lot of stuff, like alt, height, width, which is something you probably want/need at some point, so no reason making all of this yourself.


Updating computed field's value without needing to clear cache I have a computed field that lists content related to a node, so it's value should be changed when I add a new node. Whenever, I add a new node I need to clear the cache to update the computed field's value.

How do I prevent caching value of the computed field OR re-compute the value after adding a new node?

Check out the rules module (http://drupal.org/project/rules):

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules).

You could add a rule to clear the cache whenever a new nodes has been added.

It's not exactly the way you asked for, but it gets the job done - updating the computed field's value whenever a new node has been created.


Drupal 7 : I want "Access Denied on Node but Title listing in view" I used content access for restricting content of particular content type.

Anonymous user can't see Node and get Access Denied But want to listing of those restricted node's title to Anonymous user.
I searched and found premium content module but not found way to use it.

What I want,When Anonymous go:
On node == Access Denied,
On View (listing Title) == can see Title.

kindly help me for premium content OR any other Solution.

Using view you can achieve this functionality,

In you view go to Query settings in others tab, In the popup select Disable SQL rewriting

This is what views says about this option

Disabling SQL rewriting will disable node_access checks as well as other
modules that implement hook_query_alter().

Then Content access will not able to alter this query, so your users who don't have permission to view the particular content type also can see the views results

While When they are trying to access the node, on that time content access will not allow them to see that node.

Hope this helps.


How to insert values into Global custom text field of views programmatically? How can I programmatically insert values into Global custom text field from the views. I have tried using the $views variable from the hook_views_pre_render(&$views) and my_theme_name_process_function(&$vars) but was unsucessful in getting the value ?
When I try for a simple field I can insert html into the markup programmatically.

$view = view Object
(
    [db_table] => views_view
    [base_table] => node
    [base_field] => nid
    [name] =>view_name
    [vid] => 3
    [description] =>
    [tag] => default
    [human_name] => view_name
    [core] => 7
    [api_version] =>
    [disabled] =>
    [editing] =>
    [args] => Array
    (
        )

    [use_ajax] =>
    [result] => Array

  [result] => Array
        (
            [0] => stdClass Object
                   [field_field_final_ort] => Array
                            (
                                [0] => Array
                                    (
                                        [rendered] => Array
                                            (
                                                     ['#markup'] => YES

I want to similarly change the value of GLOBAL custom text field using views object but there is not such array for global custom text field.
What is the way for changing it?

My code was

function my_themename_process_views_view_field(&$vars) {

  if ($vars['view']->name == 'view_name') {
foreach( $vars['view']->result as $key => $value) {
$value->field_name[0]['rendered']['#markup'] = '';
}

}

I want to apply this similar code for global custom text field but there is no suxh available inside result array

How can I alter values for each row of global custom text field value ?
The answer given below gives same values for each row .

You should be able to do that with hook_views_pre_render(). Please try the following code:

function YOUR_THEME_views_pre_render(&$view) {

  switch ($view->name) {
    case 'YOUR_VIEW_NAME':
      //  override the global custom text field value
      $view->field['nothing']->options['alter']['text'] = 'My custom text';
    break;
  }
}

If the global custom text value need to be different for each view result, you can configure it using replacement patterns.

In order to programmatically insert values into Global custom text field, You can use template_preprocess_views_view_fields()

function YOUR_THEME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];

  foreach ($view->field as $id => $field) {

    // The global custom text content
    $vars['fields']['nothing']->content = 'Some global custom text content';

    // change the global custom text content depend on result (node id)
    if ($vars['row']->nid == 10) $vars['fields']['nothing']->content = 'CHANGED';
  }
}


Using rules, how do I assign an action to a vbo list item based on its position in the list? I'm using rules and conditional rules. I have an action set that is using a vbo list (4 node titles sorted by post date desc) to flag nodes on the list.  This works fine. However, I need to make the first item on the list sticky and the 2nd item on the list promoted.  Then I need to remove sticky and promoted from the 3rd item.

Do I need to be using alert_entity_list:0 and alert_entity_list:1 or should I be looking for alert-list-item:0, etc. ... or am I way off base?

I should have posted this as my answer and not as a comment to my question.  As stated above, the answer would be entity-list:0 token.


Views is ignoring my field .tpl.php file when the field is used as a replacement pattern in a rewritten field I've been trying to modify a multiple-values field in a view. I thought I'd found the answer, creating a custom .tpl.php file using the naming structures detailed in Views UI's "Theme information" popup.

However, it seems that these tpl.php files are only respected when the field is output immediately, and not when it's set to be excluded from the display and then rewritten into another field using a replacement pattern. Views is seeing the file, and uses it if I don't have "exclude" ticked, but if I use a re-write pattern for the field, Views completely ignores the tpl.php file.

This happens regardless of whether "Use field template" is ticked for this field in Views UI's field Style Settings.

I almost always aggregate my fields like this to control the HTML output. How can I make Views respect my tpl.php file when re-writing the field content into another field?

Have you tried using the other method? Using template.php. I don't have time to test this, so consider this as a possible answer.

Add the following code to the bottom of your template.php file (located in /sites/all/themes/yourtheme/ folder)

function themename_preprocess_views_view_fields($vars){

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

replace themename with your theme name
replace view_name with your view name
replace block_1 with your machine name
replace field_name with your field name


Print base path in html.tpl.php Im trying to print the full path to my theme in my html.tpl.php file. In the following code the 2nd part prints correctly but the first part does nothing.

<?php print base_path() . path_to_theme(); ?>

It should be

base_path().drupal_get_path('theme', 'THEME_NAME')

Other Examples of path

$GLOBALS['base_url'] => http://example.com/drupal
base_path() => /drupal/
request_uri() =>    /drupal/documentation?page=1
request_path() => documentation
current_path() => node/26419


Why are titles required for book pages? After I enabled the Book module, Drupal suggested to add a new book page and give it a title.
On my site, I'd give a title to a book only to chapters; for regular pages, I just use a title using a progressive number, such as Page 1, Page 2, Page 20.
I saw in some video the title is mandatory.

Why are titles required for book pages?

On Drupal, the node title is always required. On books, the title is even more important, since it is used for the links to the other pages of the book, shown after the page content.

I took the screenshot on Drupal 7, but the same is true for Drupal 8.

The only way to avoid entering a title would be having a module that automatically adds a title to nodes, like the Automatic Nodetitles module, or the Automatic Entity Label (which has a version for Drupal 7 and Drupal 8).

  Automatic Nodetitles is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

  "Automatic Entity Label" is a small and efficient module that allows hiding of entity label fields. To prevent empty labels it can be configured to generate the label automatically by a given pattern.


Where to view Google Analytics "Track clicks on outbound links" results? I am using Drupal's Google Analytics module 8.x-2.5. The module configuration has a check box for "Track clicks on outbound links", which I checked since the module was installed. However, I don't see outbound link stats in Google Analytics - am I missing something? Is there something else that needs to be done for setup?

The module tracks outbound links via GA event tracking. It will send a click action to GA under the Outbound links category. The metrics for this event category can be found in the Behavior > Events menu in the GA interface.


Include third party library in custom module without composer I have zero command line access to a remotely hosted drupal site so I'm unable to run composer. My custom module requires the ryanwinchester/hubspot-php package. Is there any way I can manually add this library to my module without having to run composer? I'm willing to do any workaround no matter how dirty or frowned upon the technique is. I am able to run composer locally so I can at least produce a vendor folder with the autoload.php included.

Could I manually include the autoload.php in my module? Is this something I could just require in every class that uses the package?

It's quite common that production sites are unable to run composer. Even if command line access is available the site code is read-only, so composer would be unable to make any changes.  Either developers have to use composer locally and upload all modules and vendor files to the production environment, or a build system takes care of that task.

Your Drupal site will only have one vendors folder and autoloader, which is used by Drupal and all modules; modules don't have to include the autoloader themselves.

I'm assuming you haven't used composer to set up the site initially, and have only downloaded the Drupal zip file and added your modules.  Composer is unable to automatically determine dependencies from modules when using the zip file, but you can still add the dependencies yourself.  From the root directory of your site (not the module with the dependency), add any required packages as a dependency to the project:

composer require ryanwinchester/hubspot-php

This will add the third-party package as a dependency of your site, install its files to the vendor directory, and also make it available to any modules.

Updating Drupal core with this setup is trickier however.  You'll need to replace the composer.json file with the updated version to make sure that you get the correct dependencies for Drupal core, and then re-add any of your additional dependencies.

You can read the documentation on using Composer to manage an entire site:
https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

Using drupal-composer/drupal-project instead of the Drupal core zip file will allow you to add Drupal modules with composer, as well as automatically resolve and include any dependencies of those modules.


Synchronize commerce stock for product variations I am selling tickets to a class at multiple price points (think student, adult, senior), and each class has limited seats. I have the product display working great using product reference with inline entity form - Multiple values. I can successfully checkout with each product variant.

I have run into a snag using Commerce Stock as the stock is per product, which in my case is each variant of the class. So say I have 30 seats, I need to be able to sell 30 of any product variant, but no more than 30 of all product variants total (per class, which is a single product display).

Is there a way for the stock to be per product display, not per product? If not, is there something I can invoke using Rules to subtract from all product variants stock when one is purchased?

Ultimately, I am looking for a way to synchronize all product variant's stock in a single product display.

Here's a relatively straightforward way to track stock based on a group:

  Caveat Emptor: This will only work well if you have unique products per product display, if you try to re-use products (same ticket for multiple events) it could wreak havoc on your stock numbers.

Before starting: Download and enable "Rules Data Transforms" and "Conditional Rules"

Create master stock field. Add a field to your Product Display called "master stock" or "open seats" or whatever makes sense for your use case.
Clone rule. Find the rule that decrements stock on the product level, clone it, disable the original. If it is a component, you may need to locate the event rule that calls it and clone/disable that rule as well. Just depends on your setup.
Edit new cloned rule. Inside your newly cloned rule, you are going to add an action that decrements the master stock.
Calculate new Stock number. First, calculate the new stock number by subtracting one from the product's stock field. This will be the new stock number that we will set on the product display, and all of it's children.
Load Product Display. Pull a product display from the line item field commerce_display_path. This can be tricky, which is why I had you install the Rules Data Transforms (link above).

A. Add a condition Entity has field and we're checking that the line item has the field commerce_display_path (this works great with default add-to-cart settings, but may not work if your add-to-cart doesn't track the display node path).

B. Add an action Explode Text under data transforms. You are exploding commerce-line-item:commerce-display-path using the delimited / and calling it "display_path"

C. Add an action Convert data type under the first group called Data. Your target type is integer and the value to convert is display-path:1 (the second value after exploding) and we'll call this product_display_nid

D. Add an action Fetch entity by id. Click the "Switch to data select" button and pull in the newly converted product-display-nid
Set master stock. Set master stock value of product_display by adding an action Set a data value for the product_display's master stock field to your calculated new stock price.
Create inline condition. Next we need to create a conditional to bring in the "field_product" (or whatever field you use for product references). This is why I had you install the Conditional Rules module. (Yes, this could be accomplished with core rules components, but this feels more straightforward.)

A. Click Add Conditional

B. Click Add if and let's make the conditional an Entity has field by loading the product-display node and looking for your product reference field. By default it's called field_product

C. Click Add loop and loop over the product-display:field-product list and call it sibling_product
Set all sibling products stock. Finally, we need to add a Set a data value action to set each sibling_product's stock field to the new value. Note, this will include the product that has been purchased.

There you go! Admittedly, this is a pretty naive solution. If your master stock says "10" then all of your products will be "10" and when one is purchased, they will all say "9." When there is only 1 seat left, there will still be 3 tickets that could be purchased.


Submitting webform without refreshing the page I have a webform displayed as a block:

Is it possible to submit the form without refreshing the page, followed by a message saying the webform has successfully been submitted? If so, could someone guide me in the right direction?

Thanks!

Check out Webform AJAX module.

This module adds AJAX support to Webform (3.0 and above).
As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.

I think that may do what you are asking. Should then show up as options in form settings.

Also, be sure you are set to "no redirect"


Uploaded image accessible by many nodes Is it possible to upload an image to Drupal which is accessible by all nodes programmatically?

What I want to do is upload an image to display as a banner (CSS background) for nodes that have a specific radio button selected.

My idea is to have the user upload the image to one place then in my template.php file detect which radio button has been selected & from that pull that image in as a CSS background.

Is this even possible?

Yes, any file uploaded into an image field in Drupal is accessible by its File API.

To address your issue, there are many ways to go about this. One solution that comes to mind is a multistep solution:

Create a content type with an image field. You'll be using this content type to manage any background images you want.
On the node type that you want to add an image background to, add an Entity Reference field that references the node type created in #1 with a Checkboxes/radio button widget.
Edit your theme's template.php to add/update the MYTHEME_preprocess_node($variables) function. Inside of this function you'll be using $variables['node'], node_load(), file_load(), &  drupal_add_css() to retrieve your selected image node reference, load the node, lookup the referenced file, & add inline CSS to your node display.


How do I implement routes? How can I implement the most basic route in Drupal 8? What files do I have to write, and which classes do I need to implement?

Implementing the most basic route in Drupal 8 require:

The file containing the routing definitions (helloworld.routing.yml)

helloworld.hi:
  pattern: '/helloworld'
  defaults:
    _controller: '\Drupal\helloworld\Controller\HelloWorldController::hi'
  requirements:
    _permission: 'access content'

A controller class that returns a render array or a string (src/Controller/HelloWordCOntroller.php)

namespace Drupal\helloworld\Controller;

class HelloWorldController {
  function hi() {
    return 'Hello world!';
  }
}

This is the equivalent of what in Drupal 7 was a MENU_CALLBACK. Implementing a local task, or a local action requires other files to be added, differently from Drupal 7, where a local tab would be implemented using the same hook used for a MENU_CALLBACK.


Display taxonomy terms and nodes together I have a taxonomy with some terms and subterms and a content type Product, for example:

Term1

Subterm1A

Subterm11

Subterm1B

Term2

Subterm2A
Subterm2B
Subterm2C

Term3

Subterm3A
Subterm3B

Products can be assigned in every level of the taxonomy (terms, subterms, etc.).
If I enter in the Term1 page, I'd like to display a list of the subterms and also the list of Products assigned to Term1 (subterms and Products are at the same level).
How can I achieve this?

Thanks a lot!

You can use the Views module.  Views provides a view by default that overrides the taxonomy term paths.  Enable this view (or clone the view if you anticipate making a lot of changes and want to reference the original; then enable the clone).

Then edit the view by adding the relationship Taxonomy term: Content using Name_of_my_vocabulary.  You will then be able to add the fields from the product nodes that you want.


Toolbar to insert HTML tags while editing content This very site features a neat toolbar just over the textareas in forms, where clicking on "B", for instance, will spawn **strong text**, abstracting away the need to know Markdown.

Is there a way to do the exact same thing with, for instance, filtered HTML, or another text format based on HTML, on my Drupal site? I find that WYSIWYG editors tend to bloat the actual code and I want my users to get used to seeing HTML tags, but for the moment they can't be bothered with typing the markup in themselves.

After asking on #drupal on irc.freenode.org, I was looking for the BUEditor module that does just that, specifically looking at its native support for HTML tags:

Screenshot (using BBCode)


apache solr result logged users node should appear on top and then other user's node I am using apache solr modules. My requirement was if I hit the search logged in user node should appear on top and then other user's node. How to achieve this requirement. Any help will be greatly appreciated.

I strongly recommend using the Apache Solr View module, with this module installed it is only a matter of indexing the correct data and building the view with the correct sorting.


No matter which size is my viewport, the narrow.css file is the only one triggered with IE7 and IE8 in my Omega site I´m using Omega theme in D7.
After configuring all the .css files to achieve an adaptive design, I realize that ie7 and ie8 looks like hell.

The problem? The different css files (that have different codes according to different mediaqueries) are not triggered.

No matter which size is my viewport, the "narrow.css" file is all I see.
Not even the default.css

Is there a workaround to this?

Thanks!

You can load css file by using this code:

drupal_add_css(path_to_theme() . '/css/ie8.css', array(
  'weight' => 999,
  'browsers' => array('
      !IE' => FALSE,
      'IE' => '(lt IE 9)&(!IEMobile)'),
      'group' => CSS_THEME)
);

== 2nd option ==

try Respond.js module

  This Drupal module provides IE 6-8 support for responsive themes.


How might one get a conditional display of tooltip or popup message from a rewritten view field? The issue concerns a View displaying a partial set of fields from a content type "video record," containing a collection of info about videos. One of those items is a Boolean (checked or not checked) indication of whether or not this video is allowed to be added to a user's shareable lists, generated by the module Flag Lists. If it IS shareable (Boolean was checked in full record) then the View displays a checkbox, allowing it to be added to a list. If it's NOT shareable (Boolean was unchecked) then we want to suppress the checkbox and display something else instead; currently that is just an "X" and that is working. Partial display of this here:

The "X" in the View field, a table cell, is the result of a View field rewrite plus display of the text "X" on the condition of "no results."

However we also want to have some form of tooltip/popup message, for hover on the "X," that explains why it's not allowed to be selected. Ideally, if this View field contains "X" then the tooltip would be active; otherwise it wouldn't. Here is a simulation of that:

This is currently working and the tooltip message is generated by the module "Tipsy." However that requires CSS selectors to associate it with the proper item. The only way we can see to use this is to manually add (to Tipsy config) a unique selector for each and every item in the list where this condition applies. Most problematic is that the selectors (as far as I have been able to understand) merely identify a position in the table – so if the table is resorted, they would get out-of-sync.

Can anyone suggest another path for getting to the desired result? That could be either a different way to get the tooltip/popup message that would only be active on the relevant table cell contents, OR maybe backing up farther and presenting the checkbox/no checkbox option a different way, depending on the full content page's condition of shareable/not shareable.

You are actually on a good track - and you can use html in the no result text field. An easy solution to just attach the tooltip to the 'X's would be to add the needed info for tipsy there:

X

In the Tipsy module settings you would need to add the appropriate selector in the form of: a.tipsy-tooltip. The selector does not need to be unique - you can use classes instead of ids. That way you can address multiple entries with just one selector.

Selectors are not linked to the position in the table, but rather identify a particular tag. In this case the element the 'a' tag which wraps around X. If the table gets resorted, the tooltip is still attached to the Xs.

Edit 1

The Problem might just be your selector: a.views-field views-field-nothing.

CSS classes are interpreted linearly and the order is important. In this case you are telling tipsy to look for a html element views-field-nothing which itself is nested unter a link a with the class views-field. If you look at the inspector though you will see that the actual mark-up is different and probably looks close to this one:

    X

A link a nested in a element with the classes views-field and views-field-nothing. Tipsy can't convert the default tooltip to a tipsy tooltip because it doesn't find the link to start with.

The correct selector would look like this: .views-field.views-field-nothing a (The missing space between the first two classes is important, as are the dots before the names which indicate they are classes rather than html elements or ids. If you made a space between the first two, it would look for an a-tag nested in a element with the class views-field-nothing which itself is nested under the element with the class views-field.)

Since views-field is a class applied to all fields views outputs you can as well leave it out though and just write .views-field-nothing a

The Problem with views-field-nothing is that it applies to all views and not even just for fields where 'no result' applies - views also uses the same class for fields of the type custom text. To make sure you just target the links you want to turn into tooltips it is easier addressing them with a class on the link itself - e.g. with the a.tipsy-tooltip selector I suggested. It specifically looks for all links with the class tipsy-tooltip so tipsy can extracts their title attribute and uses it for its tooltip text.

You should also pick the 'HTML Attribute' option in this case (Source: 'HTML attribute', Selector: 'title'). The only time you really need to use the 'Child Element' option is when you want to use HTML in the tooltip as you can't do that with the former. With the 'HTML Attribute' option tipsy uses whatever you put as the links title as the tooltip text - no extra classes needed.


Date field select option in custom module I am using drupal 7 and i am need of create a custom module to show the selected filter option values to be displayed on some other pages. By default we using the filter in the views, it shows the filter result values on the same page. So that only i prefer to go custom module.

In my custom module i have four fields which are two drop down values and one keyword search functionality and final one is year based search. I have a problem with passing the drop down option year based filter. The functionality works fine for me. But while the we show the drop down of the year it doesn't mention the default select year. The first option shows empty and rest of the option shows the year. While picking a year it searches fine, But I want to show the default value in the year field, to know the field was choosing the year.

I code is

    function customsearch_box($form, &$form_state, $form_id){
    $form['release_date']= array(
        '#type' => 'date_select',
        '#title' => t(''),
        '#title_display' => 'invisible',
        '#date_format' => 'Y',
        '#size' => 40,
        '#default_value' => 'RELEASE DATE',
        '#attributes' => array('title' => t('Enter the terms you wish to customsearch for.')),
      );
    }
    function customsearch_box_form_submit($form, &$form_state) {
      if($form_state[input][release_date][year]=='RELEASE DATE'){
        $form_state[input][release_date][year]='';
      }
      $form_id = $form['form_id']['#value'];
      $form_state['redirect'] = array('research-result',
      array('query' => array(
        'field_srch_release_date_value[value][year]'=>trim($form_state['input'][release_date][year]),),),);
    }

I can't find a link to any documentation for this at the moment, but the default value for a date field expects the date in a certain format: yyyy-mm-dd. It might sound counter-intuitive but something like this should work:

// Make up a date with the correct year
$time = mktime(0, 0, 0, 1, 1, $year);

// Format the date
$default_value = date('Y-m-d', $time);

// Set the default value
$form['release_date']['#default_value'] = $default_value;


Users add payments to order without editing order Use case is that users need to be able to "pay off" an order eg. Yearly Fees of $200, the user might pay it off sporadically $5 or $10 at a time until order balance reaches $0.

Users are able to add payments through admin/commerce/orders/%/payment if the permission "Edit own orders" is active. This however means that the customer is able to edit the order details (prices, products, status etc.) which is a problem.

Is there a workaround for this? Im coming up blank.

Have found the answer in "commerce/modules/payment/commerce_payment.module"

Lines 964-972

    // Creating new payment transactions.
case 'create':
  if (user_access('create payments', $account)) {
    // We currently allow any user to create any payment transaction,
    // regardless of the order, because entity_access() doesn't give us a
    // way to discriminate on the order.
    // @todo: find a way to prevent creating a payment transaction if the
    // user doesn't have access to the order.
    if (!isset($order) || commerce_order_access('update', $order, $account)) {
      return TRUE;
    }
  }
  break;

need to be updated to the following

    // Creating new payment transactions.
case 'create':
  if (user_access('create payments', $account)) {
    // We currently allow any user to create any payment transaction,
    // regardless of the order, because entity_access() doesn't give us a
    // way to discriminate on the order.
    // @todo: find a way to prevent creating a payment transaction if the
    // user doesn't have access to the order.
    if (commerce_order_access('view', $order, $account)) {
      return TRUE;
    }
  }
  break;

This does not appear to have any security implications.


Unable to print form submission result The structure of my form is as follows:

Form is built here

  function mymodule_member_search_form

The form submission processing happens in the callback function

  _mymodule_search_form_submit(&$form, &$form_state)

Here I am able to get the results and do the various processing I want and the final result I have stored in

if(isset($myvalues)){
        $form['results'] = array(
            '#type'     => 'item',
            '#markup'   => $myvalues,
        );
    }

But the values are not printed on the page after form submission, I have also set

$form_state['rebuild'] = TRUE;

in the above submission function

What am I missing here?

Additional Information is this form I have added as a block. So do I have to pass this ass the result of block? If yes, how do I do that?

Thanks.

I believe you start with a fresh form in mymodule_member_search_form(), i.e. with $form = array();. Is it correct? If so, your $form['results'] are not in the form returned by mymodule_member_search_form(). You should either do the processing in form callback itself or fetch results from the form prior to redefining it.


How to detect 404 in THEME file I'd like to attach a library to a custom 404 page.  I'd like to do this in my theme file.  How can I know if the current response will be a 404 Page Not Found?

Got it.

In your hook within your theme file:

  $status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
  if ($status && $status->getStatusCode() == 404) {
    $page['#attached']['library'][] = 'themename/notfound';
  }


tablesorter pager.js is not working I have successfully added the tablesorter.js library to a table in my drupal website but when I try to add the pager, the input and select Html that I add do not show up.  I add this HTML

    <form>

        <input type="text" class="pagedisplay"/>

        <select class="pagesize">
            <option selected="selected"  value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option  value="40">40</option>
        </select>
    </form>

but something in the drupal site makes the select options and the input options disappear from the final page.

I had to add the form and form elements as a Form under the src/ directory and call it with

 $form= \Drupal::formBuilder()->getForm('Drupal\pup_viewfiles\Form\PagerForm', $extra);


Hide main page content block I've configured the Main page content block to show on all pages except those listed. The paths I have listed are:

commodity-selection
commodity-selection/*
value-chain-studies
value-chain-studies/*

When visiting one those pages however, the main page content is still present. Even after all caches are cleared.

Is there a trick to hiding the Main page content block?

What I'm trying to achieve is a page that that presents its content within a tab. Other tabs are populated with content from other nodes.

My approach so far has been to use Quicktabs to create a block with the node content  I want (ie. node 1, 3, 5). I place that block in the content region and configure it to show on the page I want (node 1). I planned to then hide the Main page content block to hide the node 1 content, without success.

Appreciate your suggestions.

Main content is required. To hide it you can do this (I'm using bartik and hiding only for article) in theme's template.php:

function bartik_preprocess_page(&$vars) {
  if($node = menu_get_object()){
    if ($node->type == 'article') {
      $vars['page']['content']['system_main']['#access'] = FALSE;
    }
  }
}

However, I think you need to rethink your approach and either use Views, Display Suite, or Panels to take over the rendering.


Is it possible to call a custom ajax event after removing a file from a managed_file field? I have a custom form with a managed_file field element. I'd like to call an ajax event after removing a file (clicking the REMOVE button).
Is there a way to expand the existing ajax callback for the remove button?
What I'm trying to do is fire a custom ajax event after clicking the REMOVE button on a managed_file element to remove an element from the dom.

I tried to do the same in D7 a while ago and I discovered a JS only solution is not possible. You need to add an ajax command to the Drupal callback.
Here's a similar question to yours. This one is about the upload button and you want the remove button.
In D7, the upload and remove button were handled by the same function and when I look at the D8 class of the managed file I also see only one callback: uploadAjaxCallback. So it might be worth checking that out.


Using groupby in hook_views_query_alter() I have a view that is using a format that doesn't include group by fields in its settings. I'm trying to mimic that by using the hook_views_query_alter() function in a module.

I know the code is running, because I see the DPM value and the error log string, but the group by doesn't seem to be working. I know that group by in views is a different thing than mySQL's group_concat (which you can use via aggregation, but that doesn't work in this case because we need one field to not be aggregated.) So I'm not expecting to see a group_concat in the printed-out query. But I would have expected it to produce the same results as if I had set up Group By in unformatted list settings for the same four fields (which does work as expected.)

Here is what my view looks like without any group-by (either in the settings or the module):

You can see that there are two complete chunks of information for April Carlisle, because she is speaking at two sessions.

If I turn on Group By for speaker name (content: title), job title, and company in unformatted list settings, this is what I get (and what I want):

So I had thought that my module code would reproduce that result, but it's not. Can anyone tell me why?

Here's the main function:

function group_speaker_carousel_views_query_alter(&$view, &$query) {
  switch($view->name) {
    case 'speakers_carousel':
      error_log("view name now: ".$view->name);
      $query->groupby[0]['field'] = "title";
      $query->groupby[1]['field'] = "field_job_title";
      $query->groupby[2]['field'] = "field_company";

      $select_query = $query->query();
      $query_string = (string)$select_query;
      dpm($query_string);
      break;
  }
}

"Group By" is not working on hook_views_query_alter and it is views module issue. that is reported at https://drupal.org/node/590534, http://drupal.org/node/1608742, http://drupal.org/node/389230#comment-2637200

So, You should use other hooks such as general hook_query_alter.

function hook_query_alter( &$query) {

  if($query->alterMetaData['view']->name == "your_views_name"){
     $query->groupBy("domain_source.domain_id");
     //also you can unset other group by critera by using, unset($query->getGroupBy());
  }
}


Form Ajax not working when rendered from Ajax callback I am trying to load a Drupal form through an AJAX callback when the user selects an option from a select list. The code used to generate this form as follows:

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['dashboard_list'] = array(
    '#title' => t('Select Dashboard:'),
    '#type' => 'select',
    '#ajax' => array(
        'callback' => 'Drupal\dashboard\Controller\DashboardController::OnPanelSwitch',
        'effect' => 'fade',
        'event' => 'change',
        'progress' => array(
            'type' => 'throbber',
            'message' => NULL,
            ),
        ),

   );
return $form;
}

Inside of OnPanelSwitch(), which is called when the user selects an option from the list. I am using the renderer service to get the form's HTML and then inserting the form into a div.

 public static function OnPanelSwitch(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();

    $AddChartForm = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddChartForm');
$AddChartFormHTML =\Drupal::service('renderer')->render($AddChartForm);

    $ajax_response->addCommand(new HtmlCommand('#formarea', $AddChartFormHTML));

    return $ajax_response;

}

This HTML is then inserted into a DIV in the page. The form being loaded via AJAX is built in the following manner and contains a single select list:

public function buildForm(array $form, FormStateInterface $form_state) {
   $form['query_type'] = array(
      '#title' => t('Query Type'),
      '#title_display' => 'invisible',
      '#type' => 'select',
      '#options' => array(t('Chart'), t('Table')),
      '#prefix' => '
 '
',
      '#ajax' => array(
          'callback' => 'Drupal\dashboard\Controller\DashboardController::OnQueryFieldChange',
          'effect' => 'fade',
          'event' => 'change',
          'progress' => array(
              'type' => NULL,
              'message' => NULL,
              ),
          ),

  );
return $form
}

The OnQueryFieldChange() callback is not being called when this form is being loaded via the initial AJAX call. If I load this form without AJAX through the twig template everything works correctly. So it seems to be an issue of the form being loaded via AJAX.

From my research it seems like I might have todo something with Drupal Behaviors to enable AJAX for this form? Any guidance would be really helpful.

I have fixed the issue I was having by just returning the render array of the form rather than trying to get the form's HTML. So my AJAX callback function now looks something like this:

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

   $ajax_response = new AjaxResponse();

   $AddChartForm = \Drupal::formBuilder()->getForm('Drupal\dashboard\Form\AddChartForm');

   $ajax_response->addCommand(new HtmlCommand('#formarea', $AddChartForm));

return $ajax_response;


Avoid access to profiles (user/%user/view) I want to avoid access to user/%user/view, so only admins can see profiles. At first I tried with changing the permission user_view_access without any luck.

I tried to use the hook hook_menu_alter:

53 function mymenu_menu_alter(&$items) {
54   $items['user'] = array(
55     'access callback' => 'user_access',
56     'access arguments' => array('access administration pages'),
57     'type' => MENU_NORMAL_ITEM,
58   );
59   $items['user/%user_uid_optional'] = array(
60     'access callback' => 'user_access',
61     'access arguments' => array('access administration pages'),
62      'type' => MENU_NORMAL_ITEM,
63   );
64   $items['user/%user/view'] = array(
65     'access callback' => 'user_edit_access',
66     'access arguments' => array('access administration pages'),
67     'type' => MENU_NORMAL_ITEM,
68   );

It doesn't work neither. Do you have any hint?

There are four problems with the code you reported:

The code is changing the menu type, when it should not do so.
The code is changing values that it should not touch, if the purpose is to only change who can access the user profiles.
user_edit_access() and user_access() expect the argument they receive to be a user object, not a string. It is wrong to set "access arguments" to array('access administration pages'), as you are doing.
Even if you would set "access arguments" to array(1), user_edit_access() allows the users to see their own user profile; if you want to avoid to show to the users their own user profile, then that function is not the function I would use as access callback.
As said by jhedstrom, it is not necessary to use code in this case, when it is enough to don't give the permission to access user profiles to those roles you don't want to be able to see any user profile. The answer I am going to give takes the assumption you don't want the users to see any user profile, including their own; in this case, removing the permission to access user profiles doesn't help, as Drupal still allows the users to see their own user profile.

function mymenu_menu_alter(&$items) {
  $items['user/%user/view']['access callback'] = FALSE;
}

function mymenu_user_view_access($account) {
  return $account && $account->uid && user_access('administer users');
}


Moving field content to new field collection fields automatically I'm working on existing site which has small boxes with an image, title & text in them multiple times on a page. Currently it uses fields for each one so there'll be six image fields, six title fields, etc but I'd like to making them all one field in a field collection which can be added multiple times.

Creating the new field collection an appropriate fields is fine but what is the best way of moving the existing multiple field images, titles, etc to the field collection?

Create your Field collection,
Add new fields to it
Add field Collection Field To your content type
Create a Custom module ( if you don't have)
With Getting help of Batch Operation Docs, Create A Batch Operations on your desired content type
On each epic load node, get your fields data,
Add those values to field collection ( add an item at field collection programmatically)
Check the Results
remove old fields from the content type

I Strongly Recommend befor write batch, try it on one node, I mean create a route ( I mean item with hook_menu) then in call back try to achieve what you want, after success convert it to a batch operation or do it with VBO + Php Filter module(instead of batch processing)


How to generate XML feed with nested tags using Xpath Parser? I have a XML file as below

<rss>
  <channel>
    <title>Channel Title</title>
    <description>Channel Description</description>
    <owner>
      <owner:name>Owner Name</owner:name>
      <owner:email>Owner Name</owner:email>
    </owner>
    <item>
      <title>Item 1 title</title>
      <author>Item 1 author</author>
    </item>
    <item>
      <title>Item 2 title</title>
      <author>Item 2 author</author>
    </item>
  </channel>
</rss>

In my Xpath parser settings, I gave /rss/channel/item as context and I am getting only the item title and item author into my node. How it is possible to add title,description and owner details into my node?. And I also want the same structured XML output using Views data export.

You need to move your context 1 level back.

context: /rss/channel

title: title

description: description

owner name: owner/owner:name

owner email: owner/owner:email

item title: item/title

item author: item/author


Where is the group of a fields group stored in datababase (to get it programatically)? I have installed the Field group module, which, as the name implies, groups fields together. Once you have ordered the fields of content type, is there any way to programmatically get the group of the fields that are grouped together?

I have search in database (columns field_config, field_config_instance) and there is not any column to save that information. Where is that information (the group of field) stored in database?

Thanks in advance.

I have never used field_group module, but your approach seems wrong, looking in the database doesn't help often.
I suggest you should install the module devel, turn it on.
Then use the function dsm() to see the content of your node/form that you are in.
If I assume you are in the hook_form_submit() to process something, dsm($form_state), if you are in another hook with a node as parameter of your hook, just dsm($node), you might find what you are looking for.

Cheers


D7: How to deal with the variables visibility? Now I have some variables collected from POST

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

I need to use them in 2 functions: hook_form() and the callback mail_send() the function that format and sends my email with form elements.

I have implemented the following hooks:

function MYMODULE_page() {...}
function MYMODULE_form() {...}
function MYMODULE_form_submit($form, &$form_state) {
mail_send($form_state['values']);
}

//a custom callback mail function call in the submit.
function mail_send($form_values) {}

...

Now I don't know where to place those variables to have maximum visibility:

if I place them in MYMODULE_form() the show up in the form but they are not available in the mail_send().
if I place them outside everything they are not available inside functions.
if i place them inside a hook_init() the same as above.

I need a place where all variables are visible. Thanks

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.


Redirect anonymous users to custom URL I would like to implement a custom redirect for anonymous users that try to access a form built with FAPI. user_is_logged_in is used in access callback to provide true or false.

However, I couldn't find documentation on how to hook into access callback functionality e.g. what happens when it returns FALSE? Now it automatically redirects to default user login page but I need change this.

You can make the page available for all users, also anonymous, and in the page callback redirect the anonymous user to your custom page.


I want to re-order the default fields on registration form I want to change the order of the default fields on the user registration form like E-mail adress, password ect ...

I have no idea how to order these. (I'm a noob at Drupal by the way)

You will need to write a custom module for this, there is some good reading here. https://www.drupal.org/developing/modules/7.

You should create a folder like /sites/modules/<module_name>.

Create a <module_name>.info file

name = Custom order of fields
description = Customizes field orders
core = 7.x

Also create a <module_name>.module file an add the following code. The weights control the order, lower is higher on the page.

Please note that this might cause some problems with the field ordering if you add or change fields with the manage fields UI, so you might have to tweak the values a bit later on. You can go the the manage fields page and in the right top click Show row weights, this allows you to change the weights of the fields created with the UI.

function <module_name>_form_user_register_form_alter(&$form, &$form_state) {
  // Move the whole group.
  $form['account']['#weight'] = -10;

  // Move a single property within the group.
  $form['account']['name']['#weight'] = -10;
  $form['account']['mail']['#weight'] = 5;
  $form['account']['pass']['#weight'] = 15;

  // Move a value out of the group and order it.
  $form['name'] = $form['account']['name'];
  unset($form['account']['name']);
  $form['name']['#weight'] = -10;
}

Finally if you want the order to persist on the account edit page, copy all code again into a function named    <module_name>_form_user_account_form_alter(&$form, &$form_state)


overriding template file of display suite layout applies on other pages I created a display suite layout "tow column stacked" in manage user section, then I want to override that template, and make a new one in my theme templates folder,
the ds module suggest for me :

  ds-2col-stacked--user.tpl.php
  ds-2col-stacked--user-user.tpl.php

so I created ds-2col-stacked--user-user.tpl.php in my templates folder, but this template is overriding as well the registration page!

how can override with the correct name, to apply this new template only for user edit account page ("/user/%/edit") ?

Thanks in advance.

You can use hook theme suggestion in your template file. It gives you the right way of naming you tpl file.

function THEME_preprocess_node(&$variables) {
  print_r($variables['theme_hook_suggestions']);

}

function THEME_preprocess_page(&$variables, $hook) {
  print_r($variables['theme_hook_suggestions']);

}


form rendering through tpl file I want to render drupal 6 form through tpl file.
for that
1. I have written mytheme_theme in template.php file and there I have define my template forms arguments and path for tpl file.

I have written tpl file
in form function at the end I have called theme by '#theme' => 'my_template'

doing all these thing my from is rendering through tpl but now its not going into submit_hander() and validation.

can any one help me these? I am not getting what's wrong in these.

see in my template.php contain:

function cs_theme(&$existing, $type, $theme, $path) {
  $hooks = zen_theme($existing, $type, $theme, $path);
  // Add your theme hooks like this:
  /*
  $hooks['hook_name_here'] = array( // Details go here );
  */

  // @TODO: Needs detailed comments. Patches welcome!

  $hooks['my_theme_example'] = array(
                  'arguments' => array(
                  'order' => null,
                  ),
                  'render element' => 'form',
                 'template' => 'mymodule_template',
                 'path' => drupal_get_path('theme', 'theme_name') . '/templates',
              );

  return $hooks;
}

In these way I have printed all the form fields
in my .tpl file is:

   <?php print drupal_render($variables['order']['logo']);?>

You need rewrite 'form' like this:

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  $form_registry = &$theme_registry['form'];
  $form_registry['function'] = 'mymodule_form_theme';
}
function mymodule_form_theme($element) {
  // I'm not sure that $element has 'from_id' but you could pass it if you need.
  if ($element['form_id'] == 'yours_form_id') {
    return theme_form($element);
  }
  // Else return what you need I guess that better to use hook_theme()
  // and then call theme() function.
}

Look at theme_form() to understand what variables need to pass in form tag.
I don't understand why do you need this. What is the reason to use template file?


Test if a value exists in $form_state If I wanted to rebuild a form in Drupal 7, conditional on the state of the form, I would do something like this:

if (isset($form_state['values']['foo'])) {
  $form['...
}

Now, $form_state is an object in Drupal 8. What would be the best equivalent?

Pretty much $form_state->getValue('foo');.

See the docs page for getValue.


Language switcher block hides for authenticated user I have a language switcher added to my site. It works fine as long as I'm an unauthenticated user. Logging into site replaces it with:

I see this behavior also  when I add a message block to any of the regions.

I'm also using big pipe. Could it be causing some issue? Is this a bug with language switcher block?

Any help is appreciated.

Thank you

Things you can try one of the following:

Uninstall Big Pipe module
Try switching to another theme. It might be that the active theme has a JS error which breaks the execution of the Big Pipe
Enable JS aggregation if disabled, or disable it if enabled
Check for console erros in the developer tools


Using token_replace in php filter with webform2pdf I'm trying to use submission id of webform in webform2pdf.

My problem it is possibility of usage result of token_replace in php filter.

<?php
  $node = node_load(53470);
  $sid_token = '[submission:sid]';
  $sid = token_replace($sid_token, array('node' => $node));
  print 'strlen($sid) = '. strlen($sid);
  foreach (str_split($sid) as $position => $symbol) {
    print 'Position ' . $position . ', symbol ' . $symbol . '<br>';
  }
  print 'echo($sid) = '; echo($sid);
?>

[submission:sid] must return string '145', but result is:

strlen($sid) = 16

Position 0, symbol [
Position 1, symbol s
Position 2, symbol u
Position 3, symbol b
Position 4, symbol m
Position 5, symbol i
Position 6, symbol s
Position 7, symbol s
Position 8, symbol i
Position 9, symbol o
Position 10, symbol n
Position 11, symbol :
Position 12, symbol s
Position 13, symbol i
Position 14, symbol d
Position 15, symbol ]

echo($sid) = 145

As I understand it means that token_replace function is called after php filtered expression execution but I need to use result of $sid inside php

<?php $submission = webform_get_submission(53470, $sid); ?>

When you use token_replace(), you need to provide it with a proper data array. Since you provide it with a node, your token replace can only replace [node:*] tokens (exceptions for global tokens such as [site:*]). If your submission is a node, you should be able to use [node:nid] instead.

If you were to use $sid = token_replace($sid_token, array('submission' => $node));, you can use tokens like [submission:*], but only with node properties (nid instead of sid).

If your submission is of another entity type, you will have to provide that as data as well.


How to add a custom field to personal campaign page - Civicrm I'm using Drupal 7 and Civicrm 4.4.1 and I enabled the Personal Campaign Pages so individuals can create campaigns.  It comes with the standard default fields such as Title, Goal Amount, Welcome, and Your Message.  I would like to add another field to that form which I can then access through views to display in a table.

The field I'd like to add is called sponsor, so I could then show the sponsor when listing a view of all Personal Campaign pages.  I've tried creating a custom field dataset and applying it to the Contribution type that I'm using, but I didn't have any success.

Any ideas on how to create a custom field for these pages?

At this time, you cannot currently add custom data to Personal Campaign Pages (see the list at example.org/civicrm/admin/custom/group?action=add&reset=1).  If you wanted to do that, your best bet would be to write the code (or pay someone to write the code) that does this, and get this contributed back into CiviCRM.


How to let flexslider's picture point to its own node uri? I do several step below:

1 Add a PIC field to "artical" node type.
2 Make a view and set it flexslider,then limited type "artical",show "PIC" field.

And now I need to make slider that when I click on picture,the browser jump to the exect node that picture own.

How to do so?

you can set the configuration in the view configuratin page, just see my screen shot.


How can I wrap HTML list in some div? On my drupal 8 website I have created a view, with list of content. As an output format I have chosen HTML list. So currently it looks like following:

 <form id="views-form">

    ....

</form>

For formatting I would need to wrap the html list in some other div, is there a way to do it ? Can not find anything in the interface.

Expected:

<form id="views-form">

   ....

</form>

Another approach would be template files.

The template name depends on the entity you are theming.

For example, with views-view-list.html.twig:

change

<{{ list.type }}{{ list.attributes }}>

  {% for row in rows %}

      {{- row.content -}}

  {% endfor %}

</{{ list.type }}>

to

  <{{ list.type }}{{ list.attributes }}>

    {% for row in rows %}

        {{- row.content -}}

    {% endfor %}

  </{{ list.type }}>

If you go the template route, it can be general so that any view of that type will inherit your custom markup. Or, it can be specific to that view name or ID.

If you want to utilize jQuery, I would recommend being more specific with your class selectors and allow for multiple view instances. For example:

$('.views-class ul').each(function() {
  if ($(this).hasClass('item-list')) {
    $(this).wrap("

");
  }
});

Here is an example views-view.html.twig, which is one level up really from the above template... which prints the views name as a class... which allows view by view customization to structure and layout by CSS alone:

views-view.html.twig

{%
  set classes = [
    dom_id ? 'js-view-dom-id-' ~ dom_id,
    'views-wrapper',
    'view-' ~ css_name,
  ]
%}

  {{ title_prefix }}
  {{ title }}
  {{ title_suffix }}

  {% if header %}

      {{ header }}

  {% endif %}

  {{ exposed }}

  {% if attachment_before %}

      {{ attachment_before }}

  {% endif %}

  {% if rows.header %}

      {{ rows.header }}

  {% endif %}

  {# add custom wrapper here around rows, or in deeper template files. #}
  {{ rows | without('header') }}

  {{ empty }}

  {% if pager %}

      {{ pager }}

  {% endif %}

  {% if attachment_after %}

      {{ attachment_after }}

  {% endif %}

  {% if more %}

      {{ more }}

  {% endif %}

  {% if footer %}

      {{ footer }}

  {% endif %}

  {{ feed_icons }}

Plus, this template separates the header and exposed filters making custom templating and individual CSS easier to implement and maintain.

I add this answer because I believe Drupal theming layer should be utilized when possible before jQuery and other front-end technologies.


How to track what has (or hasn't) been "featurized" in the UI? On a sufficiently large or complex site that uses Features to export or manage configuration, it seems easy to encounter a scenario where an administrative user can inadvertently change a variable that has been "featurized" and end up having that variable reverted when features get reverted at the next code update.

The person making the change needs to remember (and to have access) to either check the Feature UI or grep the features code. I'm curious how other big sites might be handling this problem. Is there any trick to maybe highlight variables that have been featurized when they get exposed in the UI?

Try using the configuration module along with Drush. It writes the configurations into files which you can manage using GIT.

You run drush config-export –all on your dev and push your code with the config using GIT. Then you pull the changes on your prod server and run drush config-sync. It takes the config from the text files and puts them into the database making the changes live on the site.

Here is a nice article which explains this - https://shanetully.com/2014/04/drupal-and-the-holy-grail-of-workflows/


Howto override a function in privatemsg.module? There is a function in the module private message that I want to override. What is the right way to do this?

This is the function:

/**
* Format an array of user objects.
*
* @param $part_array
*   Array with user objects, for example the one returned by
*   _privatemsg_generate_user_array.
*
* @param $limit
*   Limit the number of user objects which should be displayed.
* @param $no_text
*   When TRUE, don't display the Participants/From text.
* @return
*   String with formatted user objects, like user1, user2.
*/
function _privatemsg_format_participants($part_array, $limit = NULL,$no_text = FALSE) {
 global $user;
 if (count($part_array) > 0) {
$to = array();
$limited = FALSE;
foreach ($part_array as $account) {

  // Directly address the current user.
  if (isset($account->type) && in_array($account->type, array('hidden', 'user')) && $account->recipient == $user->uid) {
    array_unshift($to, $no_text ? t('You') : t('you'));
    array_shift($to, $no_text ? t('You') : t('you'));
    continue;
  }

  // Don't display recipients with type hidden.
  if (isset($account->type) && $account->type == 'hidden') {
    continue;
  }
  if (is_int($limit) && count($to) >= $limit) {
    $limited = TRUE;
    break;
  }
  $to[] = privatemsg_recipient_format($account);
}

$limit_string = '';
if ($limited) {
  $limit_string = t(' and others');
}

if ($no_text) {
  return implode(', ', $to) . $limit_string;
}

$last = array_pop($to);
if (count($to) == 0) { // Only one participant
  return t("From !last", array('!last' => $last));
}
else { // Multiple participants..
  $participants = implode(', ', $to);
  return t('Between !participants and !last', array('!participants' => $participants, '!last' => $last));
}
  }
  return '';
}

I like to remove this part from the code:

// Directly address the current user.
  if (isset($account->type) && in_array($account->type, array('hidden', 'user')) && $account->recipient == $user->uid) {
    array_unshift($to, $no_text ? t('You') : t('you'));
    array_shift($to, $no_text ? t('You') : t('you'));
    continue;
  }

The _privatemsg_format_participants() function is called from template_preprocess_privatemsg_recipients() function, which is a template preprocess hook. You can simply override template_preprocess_privatemsg_recipients() into your module's .module file or theme's template.php file. Check the example below:

/**
 * Implementation of hook_preprocess_privatemsg_recipients().
 */
function [MODULE/THEME_NAME]_preprocess_privatemsg_recipients(&$vars) {
  $vars['participants'] = ''; // assign a default empty value
  if (isset($vars['thread']['participants'])) {
    $vars['participants'] = _[MODULE_NAME]_format_participants($vars['thread']['participants']);
  }
}

/**
 * Format an array of user objects.
 *
 * @param $part_array
 *   Array with user objects, for example the one returned by
 *   _privatemsg_generate_user_array.
 *
 * @param $limit
 *   Limit the number of user objects which should be displayed.
 * @param $no_text
 *   When TRUE, don't display the Participants/From text.
 * @return
 *   String with formatted user objects, like user1, user2.
 */
function _[MODULE_NAME]_format_participants($part_array, $limit = NULL, $no_text = FALSE) {
  global $user;
  if (count($part_array) > 0) {
    $to = array();
    $limited = FALSE;
    foreach ($part_array as $account) {

      // Directly address the current user.
      if (isset($account->type) && in_array($account->type, array('hidden', 'user')) && $account->recipient == $user->uid) {
        array_unshift($to, $no_text ? t('You') : t('you'));
        array_shift($to, $no_text ? t('You') : t('you'));
        continue;
      }

      // Don't display recipients with type hidden.
      if (isset($account->type) && $account->type == 'hidden') {
        continue;
      }
      if (is_int($limit) && count($to) >= $limit) {
        $limited = TRUE;
        break;
      }
      $to[] = privatemsg_recipient_format($account);
    }

    $limit_string = '';
    if ($limited) {
      $limit_string = t(' and others');
    }

    if ($no_text) {
      return implode(', ', $to) . $limit_string;
    }

    $last = array_pop($to);
    if (count($to) == 0) { // Only one participant
      return t("From !last", array('!last' => $last));
    }
    else { // Multiple participants..
      $participants = implode(', ', $to);
      return t('Between !participants and !last', array('!participants' => $participants, '!last' => $last));
    }
  }
  return '';
}

Note: Make sure to change [MODULE_NAME] with your module/theme name.


Hide a menu item for admin user How can I remove a menu item when admin is logged in?
I used the following code but it doesn't seem to work.

function mymodule_menu_alter(&$items) {
     $items['item_x']['access callback'] = 'mymodule_menu_access_callback';
     $items['item_y']['access callback'] = 'mymodule_menu_access_callback';
}
function mymodule_menu_access_callback() {
  global $user;
  if ($user->uid == 1) {
    return FALSE;
  }
  return TRUE;
}

User 1 bypass access controls, so that wont work. You could have 2 menus as blocks and use the block system to control which to use.

You could also use theming/CSS to hide the menu.


how to add form data in database My registration form is multi-step and the form is shown in popup. I m using lighbox2 for popup and working perfectly fine and i have added the form filed in a file that comes with lightbox2 and place in template folder and everything work fine, but the issue is how i can add the form data in database?

I use ajax when the ajax request sent it says access forbidden.

how I can insert data in database using ajax because my form is multi-step?

You'll need to define an ajax callback. This callback function can then be called by the form, and can submit values to the database for you using the Drupal database layer. In this case, I imagine the ajax handler will be added to the Next or Submit button.

$form['next'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#ajax' => array(
    'callback' => 'custom_ajax_callback'
  ),
);

Your module might also want to define its own database table to store temporary values for this.


Is it possible to autoplay a video when using module media_youtube, and perform an action when the video ends? I am using media_youtube module for embedded videos from youtube.
I am looking for a way to autoplay video as soon as it appears. Is it possible with this module?
Also I would like to make some action as soon as video ends. It would probably be going to some other drupal article. Is it possible?

The module developers hid these options well!

Click on Configuration (or Structure depending on versions)
Click on File Types
For Video, click on manage file display
For the display you are using (Default, Link, Preview, etc..), click on the YouTube Video tab under Display Settings.
Check the box called "Autoplay video on load"


Page title tag translated based on view title I've been working on a multilingual site using i18n modules, with the 'translate view' ('Internationalization Views') module, provided by i18n, active too.

I can translate the view's title and the content, but what I need to translate now it's the content of the tag <title>. I've searched the web, but didn't found any answers to this problem, can anyone help me?

EDIT:

I didn't see that the problem actually apply on just one view.
The text in italian is "cinematismi" and it should be translated into "Wiper mechanisms".

In the "translate interface" section I see the following strings:
(the first one doesn't matter because it was an old view)

The problem is that all strings are actually translated.
Can someone tell me what string should it be?

I Actually managed to do it. I'm still not really sure on what did the work, but I tried to handle the taxonomy translation too using entity translation. The view's name was based on a taxonomy name, so it's probable that translating the name of that taxonomy added the title tag translation some way (I hadn't done anything else, so...)


Is it possible to add a second `drupal.behaviors` to your module? I have a module that uses a bit of jQuery.

But when I submit a form I want it to call an other bit of jQuery on the landing page.

So I thought adding another Drupal.behaviors to my module.
But this doesn't seam to work.

(function ($) {
  Drupal.behaviors.popover_hide = {
    attach: function (context, settings) {
     // open link in new window.
     var linky = $('clickedme').attr("href");
     alert(linky);
     alert('linky');
     // remove class from link

     // set focus on new window eventueel
    }
  };
})(jQuery);

when I already have a Drupal.behaviors.popover loaded. ("popover" is the name of the module)

Turns out this does work I just needed to clear cache...

If you have this issue:
go to admin/config/development/performance and press the clear cache button.

.js files are cached even though if you have set caching to disabled on the page I just mentioned.


How can I get form_ids for all forms my module implements? I have a custom contact module that we periodically add new forms to - how can I get a list of all forms implemented by this module?

I'm integrating mollom and I want to just loop through all my forms in hook_mollom_form_list().

Forms aren't implementations of anything as such, they're just plain PHP functions that happen to return a certain structure by convention. There's no registry of forms or anything like that, and the module that a form is defined in isn't tracked anywhere (it's not information that Drupal needs). Form functions don't even have to be named in any particular way.

There's also hook_forms() which allows you to map multiple form IDs to a single form callback function, so that's an extra layer of complexity that would need to be handled somehow.

I can't think of a single reliable way you could get that information through code. Well, I'm sure you could use reflection to write something very specific to your module, provided your own form functions follow a predictable naming convention; but as far a generic solution goes, I'm 99.9% sure it isn't possible. Unless there's a creative way around that I'm just not thinking of.

If it's just for this single module, why not just write a function which returns an array of all the known form IDs. Then when you add a new form, update that function manually. It will be much easier than implementing the reflection code to do this.


How to get data from previous step in Drupal commerce checkout process I have Drupal commerce checkout process where user choose shipping and in next step choose payment method.

I need data about chosen shipping in payment method form alter.

Is there any way how can i get info about chosen shipping in payment method form alter?

I have found solution.

global $user;
$order = commerce_cart_order_load($user->uid);
$line_items_ids = array();

// get all line items IDs
foreach($order->commerce_line_items as $line_item){
  $line_items_ids[] = $line_item["line_item_id"];
}

// load only "shipping" line items
$shipping_line_items = commerce_line_item_load_multiple(
  $line_items_ids,
  array('type' => 'shipping'),
  FALSE
);

I haven't found cleaner way how to do this. Hope it helps somebody. I still would be glad if anyone knows how to do this better.


How to attach a view attachment display to an Openlayer Data Overlay display? [Drupal 7, Views 3, OpenLayers]

THE PROPOSED SCENARIO:

I would like to attach a view attachment display before an OpenLayer Data Overlay display. The attachment display would contain some exposed filters and a table of content data.

Using Better Exposed Filters I could enable auto submit and hide the submit button on the filter form at the attachment display, so both the attachment content table and the OpenLayer Data Overlay displays would get updated via AJAX. This would create a better user experience.

THE ISSUE:

Apparently I can attach view attachment displays to any view display but OpenLayer Data Overlay displays.

THE QUESTION:

Is there any work around or module implementation that could make it possible to attach a view attachment display to an OpenLayer Data Overlay display?

Another way to go would be perhaps having a block for the content data table and its filters. In this case, how could I get the AJAX on the block view to trigger the OpenLayer Data Ovelay view, so both views get the filters applied at the same time?

The proposed scenario works just fine if you attach the attachment display to the OpenLayers Map display instead of to the OpenLayer Data Overlay.


Comment author name = user name by default? My website can only be accessed by authenticated users. How can I automatically make the author's name the user's name without giving users the option to input anything else in the name field?

Well, correct me if I'm wrong, but from what I know (and based on a check I've just done in D6 sandbox) logged-in users do not have option to change their name, they see their username displayed in normal text instead of form textfield. So that's exactly the behavior you're looking for?


How to change the way a Content Type is displayed depending on user? I'm currently trying to create a Massively Multi Onlineplayergame (see tribalwars.net) in Drupal while learning it. To do this I want to be able to change the way a content type is displayed depending on what user is looking at it.

Say for example, if it's the current owner of the "town" I want the user to be able to edit it. While if it's not the owner I want the user to be able to send troops there.

I've been looking at events but there doesn't seem to be any event that allows me to do that sort of thing. Will I have to define a content type programmatically or is there any other way to do it?

Have a look at Display Modes, View Modes, and Form Modes, especially what is written about View modes within "View modes and view displays", which is like so:

View modes as a concept predate Drupal 8. They were present in Drupal 7. Drupal 6 had the concept of “build modes.” View modes exist to allow Drupal site building tools like Entity Reference fields to request a given entity be rendered in a certain way. For instance, if ‘song’ and ‘artist’ are each node types and song contains a reference field to artist. The full display of the song may need to render the ‘teaser’ for the artist. In this example ‘teaser’ is a view mode used by the artist node and ‘full’ is the view mode used by the song.

Then continue towards that present in Drupal 7 link, which further explains View modes, and includes this:

Contributed modules can be leveraged to add View modes to entities via the UI without writing code.

Display Suite

The Display Suite module makes it possible to add more view modes to your entities.

Entity View Modes

The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities.

Then head over to the Entity View Modes project page ... Guess what: that module is now included in D8 core ...


The best way to debug a custom token module development I'm building a custom module to build some tokens. I have added hook_token_info() and it works great. I haved added hook_tokens(), but I'm not able to debug with var_dump() or with dpm().

function mymoduletoken_token_info() {
  $info['tokens']['node']['seccion'] = array(
    'name' => t('Seccion'),
    'description' => t('Custon token to add to the G.A. script more optoins in seccion'),
  );

  $info['tokens']['node']['subseccion'] = array(
    'name' => t('Subseccion'),
    'description' => t('Custon token to add to the G.A. script more options into subseccion'),
  );
  return $info;
}

function mymoduletoken_tokens($type, $tokens, array $data = array(), array $options = array()) {
  dpm($type);
  dpm($token);
  dpm($data);
  dpm($options);
}

I would like to debug the different options to build the token with the information I need.

I think I'm following you...you want a way to invoke the tokens you've created outside of their natural context, so you can debug easily? If so, you can use the token_replace() function. As you're defining tokens that need a node object, you'll have to load an appropriate one up for the job:

// Load the node.
$node = node_load($appropriate_nid);

// Prepare the text string.
$text = 'something involving [node:seccion]';

// Set up some options. Your mileage may vary here.
$options['sanitize'] = FALSE;

// Get the replacement text.
$replacement = token_replace($text, array('node' => $node), $options);

That will invoke your module's implementation of hook_tokens(), and the dpm() calls will fire.

If you're doing a lot of token development it might make sense to wrap that functionality in a simple form.


Login destination to file download - prompt user we have some private file links that are pasted into emails. When a user clicks the link, if they are not logged in they get something like this:

http://mysite.com/user/login?destination=/system/files/private/myfile.docx

Once they login and authenticate, the file starts to download in the user's browser.

I'd like to override the automatic download behavior and provide a "download this file?" type prompt first, since users don't often realize the file download starts automatically.

Any ideas? Thanks in advance.

Well, there are a few ways you could handle this. All of them are going to involve some code to handle these type of requests. One way I can think of would be to catch these requests on your custom 404 page and redirect the user to the login page with a new destination and keep the file name as a parameter. Then, on the new destination page grab the file download parameter and provide them a big fat button that links to that file.

If they are already logged in and you want to do the same thing you would need some sort of pre-processing filter to capture these and do the same as above.


Migration sources files problem I am trying to migrate a drupal 6 to 8 through drupal migrate ui and i am getting a error with the sources files, drupal 8 is not able to read sites folders due is writting a double slash.

Does anyone why this happens?

  Source ID 3125: Cannot read from non-readable stream (http://dev.example.com/example//sites/default/files/)

The URL has an empty part in the path. I tried with full permissions in this folders, source in subdomain, domain, folder, etc.

How are you providing the location of the files?  IIRC, you can give it an absolute path ( /home/www/drupal ) or a URL ( http://www.example.com ).

In either case are you including a final '/'?  If so, try removing it.


Vocabulary set by another hierarchy and combinations I have to create a new taxonomy term that has no name field.

I created one master vocabulary.
Then I created another vocabulary and term having only entity reference field.
Default description field was deleted.
I would like to change hierarchy and combination of any terms from reference master vocabulary.

Normally, term has a mandatory name field and description field.
I'd like to change the name field type in the entity reference, but it is impossible.
After adding  a different entity reference field, it is an error to disable the existing name field.
Perhaps, the reason for the name field is probably because it is mandatory.

Name field of term, rather than being arbitrarily input, want to specification referenced by the fields of the other taxonomy terms.
Description field is same case. All field are refarence field from master vocabrary or others.
In other words, we want to make the vocabulary set by another hierarchy and combinations.

Do you have any idea?

It's a required part of the entity. The name field for a Drupal 7 taxonomy term is defined in the taxonomy's module:

hook_entity_info() invocation to designate name as the label (a human readable field that's required for displaying entity).
hook_field_extra_fields() invocation to define the name field within the taxonomy term for the admin UI.

The Drupal API does expose hook_entity_info_alter() & hook_field_extra_fields_alter(). You can use these function to redefine how you'd like specify your taxonomy term label field.


Using ajax to process textfield in Drupal 7 Inside of a hook_form_alter function, I want to leverage the #ajax property to modify/update database tables without leaving the form... In other words, I want the user to be able to fill in the field and either "tab", "click" or "enter" and have ajax respond.

The response should be an update of that field being displayed as well as an update to the DB...

If I can get the call back to wakeup, the DB call is easy. And hopefully the form displays that new data. Code I have so far is:

$form['license'] = array(
  '#type' => 'textfield',
  '#title' => t('License'),
  '#size' => 20,
  '#default_value' => 'default license',
  '#required' => FALSE,
  '#weight' => 10,
  '#ajax' => array(
    '#callback' => 'license_fillin_js',
    '#event' => 'change',
    .
    .
    .

  ),

So far, nothing seems to be waking up the callback.

This is probably very simple! Right?

change it to and then try again.

$form['license'] = array(
  -
  -
  '#ajax' => array(
    'callback' => 'license_fillin_js',
    'event' => 'change',
    .
    .
    .

  ),

As an example you can check this link


Is there a Rules Action to set an entity reference field to null / empty? Is there any rules action you can use to set an entity reference field to null or empty?

Thanks very much and have a great day.

Ahh, got it. If anyone else runs into a problem doing this. The issue I had was that I was leaving the data selector blank and it was giving me an error message. BUT If you switch to the direct input mode and leave it blank it will work. Have a great one.


Warning: Invalid argument supplied for foreach() in views_php_handler_filter->php_post_execute() I've created a view block with views3.
When I attach the views block to a node, I want to know if the node is sticky and if the content type is "lodging".
If the criteria are met, do not display view result.

In the views filter (php field) I've created the following code.

if (arg(0) == 'node') {
  $nid = arg(1);
  $node = node_load($nid); // get node id
}
$sticky_status = $node->sticky;  //  get sticky status
$node_type = $node->type;  // get node type
if ($sticky_status == '1' && $node_type == 'lodging') // condition if sticky is 1 (active) and node type is "lodging"
{
  $view->result = null;  // do not display views
}

The code is working fine and I get the desired result, however I also get the following warning message:

Warning: Invalid argument supplied for foreach() in views_php_handler_filter->php_post_execute() (line 84 of /var/www/html/planetlodge/sites/all/modules/views_php/plugins/views/views_php_handler_filter.inc).
Warning: array_slice() expects parameter 1 to be array, null given in views_php_plugin_pager->post_execute() (line 46 of /var/www/html/planetlodge/sites/all/modules/views_php/plugins/views/views_php_plugin_pager.inc).
Warning: array_values() expects parameter 1 to be array, null given in view->execute() (line 1155 of /var/www/html/planetlodge/sites/all/modules/views/includes/view.inc).

Where is the error in the code ?

The error is here:

$view->result = null;

Try changing it to:

$view->result = array();

Views is running over the $view->result var as an array without checking its type, but it's always expecting an array. As NULL isn't an array it complains, but it's just a Warning so the script continues. Because the results loop has failed you get the same effect as when the array is empty, and as you say everything works as expected.


Won't update taxonomy term I'm not really a Drupal guru, so any help it'd be awesome.

There's a taxonomy for every state (State Owner), which then allows me select the state when adding a new article.

However, I'm trying to add a National (NAT) to the list. I've added it to the taxonomy term list:

However, NAT won't show up on the State Owner field when adding a new article:

I can see the item on the DB too:

I've flushed the cache, even restarted the server... It just won't show up on the Add Article page (on the State Owner drop down).

Note that if I change the order of the states, it DOES change the order on the drop-down, so it's the correct taxonomy terms.

Any idea?

If anyone else lands here looking for an answer, after going around in circles for many many hours, I found out the solution.

When I gave up and was about to recreate a core component in order to overcome this issue, the first thing to do was to delete this taxonomy term, however, Drupal flagged to me that it'd affect the Access Scheme / Taxonomy Main. Interesting, so I decided to Google it, I found out this text came from a component called Workbench Access, which among other things could manage a Scheme for Taxonomy. Looking into installed modules, I indeed had it installed. Bingo. However, I had no access to it (that's why I never actually found it).

The old developer (which I no longer had access to), made me "Admin" of the system as part of his handover. However, this component was hidden for all users, but his.

After copying my hashed password, replacing his with mine, and logging in as him, I could see this component on his user homepage, which was just a matter of disabling it for State Owner and voilá. Working like a charm.


Write all PHP errors, warnings and notices to error_log Drupal catches PHP warnings and notices to log them via dblog or syslog. As a result, there are two places to monitor for PHP errors (with the watchdog UI not well suited to cater for any large number of notices).

Is it possible to prevent this behavior and have ALL php errors be logged to the error_log defined in the php config?

For that, you will need to implement the hook_watchdog to make calls to the error_log() function.

You could as example one of the places where is implemented, that is the syslog_watchdog. Instead of use the openlog() and syslog() function, you will use the error_log().


Import Data with Commas into Term Reference Field I'm having some difficulties to use feeds to import data that with commas.

I have a content type named device, and device has a field named features. features is supposed to be checkbox type which allows users to select multiple options from the provided list like A, B, C, D and the field type is term reference

I'm using feeds to map features column from a csv file to the features of device. When I do the import, instead of importing A, B, C, D separately, it created a new option as A, B, C, D altogether.

Is there anyway to separate them?

Thanks

Using the Feeds Tamper module, you can explode that field, then use ", " (comma space) as the separator.


How can I show node Hits (statistics)? How can I show Node Hits (Statistics_Counter) in Drupal 8 in a specific place?
I enabled statistics module and I now want to show user hits of a node (node view number/node visits count) in the submitted area instead of in the node links area.

I do this already in Drupal 7 with below code in node.tpl.php:

<?php print (int) $content['links']['statistics']['#links']['statistics_counter']['title']; ?>

What is the equivalent code for Drupal 8?

Drupal 8 uses twig templates so variables are handled/printed in different way.

Node links sections is handled separately because of which we can not hide/remove statistics in node.html.twig file. So to print node statistics count in submitted area, you'll first need to add that to base level of node template like content, author_picture, etc. You can do this by implementing template_preprocess_node() in your theme. Below is sample code which adds new variable containing node statistics count.

function [THEME_NAME]_preprocess_node(&$variables) {
  // Get statistics count for current node.
  $statistics = statistics_get($variables['node']->id());
  $variables['node_stats'] = \Drupal::translation()->formatPlural($statistics['totalcount'], '1 view', '@count views');
}

Change THEME_NAME with theme you're using. This will add node_stats variable which you can use inside node.html.twig file for printing node statistics count. Below is how you can print it inside template file.

{% if display_submitted %}

    {{ author_picture }}

      {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

      {{ node_stats }}

    {{ metadata }}

{% endif %}

This will print the node statistics count in submitted area of content. Links section will still show the node statistics count, to remove this, you will need to create new template file (if not already created) named as links.html.twig. You can copy existing file from "Core => themes => classy => templates => navigation => links.html.twig". After which you can exclude the statistics count from printing. Make sure to rebuild cache after adding new template file. See sample output below:

    {%- for key, item in links|without('statistics_counter') -%}

        {%- if item.link -%}
          {{ item.link }}
        {%- elseif item.text_attributes -%}
          {{ item.text }}
        {%- else -%}
          {{ item.text }}
        {%- endif -%}

    {%- endfor -%}

We've removed statistics count from links while printing using without() function links|without('statistics_counter')


Drush not working properly on Ubuntu I am using Ubuntu 14.04 . When I try to download, enable, disable any module drush gives the following error:

Additional uncaught exception thrown while handling exception.OriginalDrupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /var/www/html/gitrepo/drupal/core/lib/Drupal.php).Drupal::getContainer()
drupal8_bootstrap(0)
_drush_bootstrap_drupal_configuration()
drush_bootstrap(3, 7)
drush_bootstrap_max()
drush_bootstrap_to_phase(-2)
Drush\Boot\DrupalBoot->bootstrap_and_dispatch()
drush_main()
AdditionalDrupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /var/www/html/gitrepo/drupal/core/lib/Drupal.php).Drupal::getContainer()
Drupal::theme()
_drupal_log_error(Array, 1)
_drupal_exception_handler(Object)
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]

Sounds like you are not using the right version of Drush.  For Drupal 8.0-beta7, you need Drush 7.0.0-alpha9.  For Drupal 8.0-beta6, you need Drush 7.0.0-alpha8.

Drupal 8 APIs are changing rapidly; if you have mixed versions, you can easily encounter spurious problems.  Tracking HEAD of Drupal 8.0.x and Drush master is another viable strategy.


D7 Custom Module: Turning tabs into contextual links Created a module (D7) that turns every nodes edit tabs into contextual links instead. Works great... But on the first initial load to the page I get a warning. Disappears after I refresh once. Then it comes back around surfing to another page and back again.

Warning: Invalid argument supplied for foreach()
in mytheme_contextual_contextual_links_view_alter()
line 19....

Driving me bonkers. Code below. It's having an issue with my foreach($tabs as $tab)...

  function mytheme_contextual_block_view_system_main_alter(&$data, $block) {
      if (user_access('access contextual links')) {
        $tabs = menu_primary_local_tasks();
        $data['content']['#contextual_links']['block'] = array(
          'admin/structure/block/manage',
          array('system', 'main'),
        );
      }
  }

  function mytheme_contextual_contextual_links_view_alter(&$element, &$items) {
      if (arg(2) != 'edit' && arg(3) != 'edit' && arg(0) != 'admin' && arg(1) != 'add') {
        if (isset($element['#element']['#block']) && $element['#element']['#block']->delta == "main") {
          $tabs = menu_primary_local_tasks();
          foreach( $tabs as $tab ){
              $element['#links'][$tab['#link']['path']] = array(
                'title' => $tab['#link']['title'],
                'href' => url($tab['#link']['href'], array('absolute' => TRUE)),
              );
          }
        }
      }
  }

  function mytheme_contextual_preprocess_page(&$variables) {
      if (arg(2) != 'edit' && arg(3) != 'edit' && arg(0) != 'admin' && arg(1) != 'add') {
        $variables['tabs']['#primary'] = array();
      }
  }

Place the for loop inside an if statement

$tabs = menu_primary_local_tasks();
if($tabs)
{
      foreach( $tabs as $tab ){
          $element['#links'][$tab['#link']['path']] = array(
            'title' => $tab['#link']['title'],
            'href' => url($tab['#link']['href'], array('absolute' => TRUE)),
          );
      }
}


Problem uploading files and images containing spaces in the filename In Drupal 8 I have fields of type File and Image, inside Content types and forms. These fields stores files inside the "public" folder.

When I upload files with a name containing spaces, for example a file named "example with spaces.pdf", the file is correctly uploaded but once uploaded it is no more available.

The image below is just after uploaded an image containing spaces in the filename. Note that all seems correct:

When I save and publish the content I get this:

And returning back in the edit panel the thumbnail is no more available:

Same problem above trying to upload files inside a field of type File.

The file's url becomes something like this:

localhost:8888/sites/default/files/2016-05/example%20with%20spaces.jpg

But I'm redirected to the home page trying to open such url. Maybe there is a bug in Drupal when translates the url encoded filename in the real one.

If the filename has no spaces, or if the file is uploaded inside the "private" folder, there are no problems.

Any idea about how to solve this problem?

EDIT

I can reproduce the error with following steps:

Download Drupal

$ drush pm-download drupal --drupal-project-rename=drupal

Install Drupal

$ cd drupal
$ drush site-install standard \
--db-url='mysql://[db-user]:[db-pass]@localhost:[db-port]/drupal' \
--account-name=admin --account-pass=password \
--site-name="Drupal" \
--site-mail=noreply@example.com

Start Drupal

$ drush runserver

Create a new 'Article' and upload an image with spaces.

Maybe is there something wrong in steps above? Or a bug in the drush's built-in server?

Just I checked on different types of image files. So it could not reproduce your error. In my opinion, if your problem is in the server settings or the settings of the Drupal 8. Because viewing the forums, the Internet, communicate with colleagues at work, such a mistake, I have not met anybody.