Search api autocomplete with commerce kickstart i am using search api with commerce kickstart i have created a view and used it as an exposed form on the homepage, I have used the search api autocomplete module but its not working because the server is not supported. So I have made a custom module to do the autocomplete feature for my search filter block. This is the code

<?php

function ajaxforms_menu() {
$items['ajaxforms/autocomplete'] = array(
'page callback' => 'ajaxforms_products',
'access arguments' => array('access ajax autocomplete'),
'type' => MENU_CALLBACK
);
return $items;
}

function ajaxforms_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'views_exposed_form-display_products-page') {
$form['#submit'][] = 'ajaxforms_submit_funtion';
}
}
function ajaxforms_submit_function(&$form, &$form_state) {
$search_str = $form_state['values']['views-exposed-form-display-products-page'];
$form_state['rebuild'] = TRUE;
drupal_goto('path_to_your_search_view', array('query' => array('search_api_view_fulltext' => $search_str)));
}

function ajaxforms_products($string) {
$matches = array();

// DB table which holds products
$query = db_select('commerce_product', 'p');

// Select rows that match the string
$return = $query
->fields('p', array('title'))
->condition('p.title', '%' . db_like($string) . '%', 'LIKE')
->range(0, 10)
->execute();

// add matches to $matches
foreach ($return as $row) {
$matches[$row->title] = check_plain($row->title);
}

drupal_json_output($matches);
}

But its not working I dont know where I am wrong on this. Anyone have any idea on how to solve this ? I want the autocomplete in the block of the exposed filter search which I am using as a block

I got it working by using this example jQuery Autocomplete

If anyone else get stuck in this just ask me and I'll try to help out


Update url-aliase for nodes of a specific content type I'm using drupal 7 in combination with path auto. I imported nodes of a specific content type using the feed importer, but the url alias is not set correctly.

My problem is, that i can not use the bulk update for content paths, because there is other content, that was migrated manually and that uses non generic url-aliases.

Is there a way to trigger the bulk alias update for a specific content type?

To update URL for Existing Contents You could go to admin/content
In Update Options, You can choose Update URL alias after filtering a specific content type


What does "dynamic permissions" mean? What does dynamic permission mean, in Drupal 8?
When should I use this?

I consider it generating permissions based on some data within your site.

For instance, I wanted to create permissions based on terms or vocabularies for roles, in regards to if they could use the functionality a contrib module I maintain provides:

http://kevinquillen.com/drupal/2016/02/21/dynamic-permissions-in-drupal-8

If you look at the NodePermissions class, it does something similar.


How do I use "IGNORE" in a database query? I would like to run a query similar to INSERT IGNORE INTO the_table (nid, language) VALUES (8, 'Chinese'), but I cannot find any documentation on how the "IGNORE" statement works with the Drupal DB API.

Does anyone know how to achieve that?

db_merge('the_table')
  ->key(array('nid' => 8, language' => Chinese))
  ->fields(array(
      'nid' => 8,
      'language' => Chinese,
  ))
  ->updateExcept('nid','language')
  ->execute();

Would the code above be the equivalent of my initial query ?

EDIT: updateExcept method doesn't exist, no idea why it s still in the documentation

What you want is a MERGE query with no UPDATE part. Something like this should work:

db_merge('the_table')
  ->key(array(
      'nid' => 8,
      'language' => Chinese,
  ))
  ->insertFields(array(
    'nid' => 8,
    'language' => Chinese,
  ));
  ->execute();


Multiple Charts with Chart Module? I need to present multiple graphs in a single page. Is it possible to do this using the Charts module? Up until now I have been using the following to return a chart to the page.

return theme('chart', array(
                      'chart' => $chart,
                    ));

After a while doing the following worked, I do not know why it did not work from the beginning :

return theme('chart', array(
              'chart' => $chart,
              )).theme('chart', array(
              'chart' => $chart,
              ));


As an admin, how can I view individual user permissions for individual nodes? I’m attempting to sell individual nodes (video classes) to individual customers on my client’s website. I've learned how to do this via two videos from Commerce Guys website. It uses the following modules:

Content_Access, ACL, References, Rules, Commerce

Briefly it works like this:
Two content types are created - a video class product, a video class. Each video class product has  a reference to a video class. Once purchased an individual then has permission granted to view the video class, the one ref’d by the video class product. By default video class content type permissions are turned off. But on the access control tab of the content type there is an option that is checked that reads ‘Enable per content node access control settings’

My question is this: As an admin how can i view an individual user’s permission setting for individual nodes? and then change that permission?

I’m asking because although it works initially, at some point the user’s permissions are being being reset, ie turned off and I’m not sure why.

Any help would be greatly appreciated.

You can use "Devel Node Access". After enabling it, you can add it as a block. It shows you a table with detailed permission for each content.


Rules send email containing tokens from submitted node displays token for empty field I have a rule that sends the contents of a node to an email address on save, I am including the contents of the mail with tokens. However, if the field is blank then instead of not showing, the token itself shows in the email. Is there any way to prevent this from happening, or include all the fields in one token?

you may use PhP in your send mail rule action to check if your field is empty.

Be careful it's a bit tricky because token is not actually empty when the field is empty, it's just not computed, as you saw when you tested.

Unfortunately, the token will be rendered, if field not empty, whatever you put around it in PhP, even ' or ".

So, it's not really clean, but the way I see it is explode and then check whatever you want (for my part I use here only the first part, "[node") :

<?php
// Explode your token (or your value, you don't know yet)
$a = explode(':',"[node:body]");

// Check if first part is [node
if($a[0] != '[node') { ?>

[node:body]

//Don't forget to close the if() statement
<? } ?>

Not very good if you have to check this on many fields, NOT CLEAN at all in fact, but working :D


Annotation on top of views text? Is there a contrib module out there that provides the text equivalent of image marker? E.g. I have views output and i want to place a post it on top of it.

The closest thing i've seen is the annotation field for Drupal 5 which is a bit outdated and i don't really know how it works.

Try out Image Annotator module.

  The module allows you to annotate images, and works in combination with field_collection. The module defines a new field called 'Image Annotator' that can be linked to an image field, so you can add multiple markers to an image.


Site is redirecting to old domain on button submission, files are linking to old domain I have a D7 site at www.example.com, an old one, not updated since 2012 (Drupal version 7.34). I made a clone copy with separate clone database under dev.example.com

All files like CSS are still linking to www.example.com (while they are available at dev.example.com).

And most important, on /admin/ backend when under dev.example.com if you click any Submit button in any page, it redirects to the www.example.com website. So if I submitted any operation at dev.example.com/admin/* it redirects to same page at www.example.com/admin/*

I've cloned websites million times, I never had this behavior. How do I prevent redirects for files and on submissions?

update: I found in settings.php I have $base_url = www.example.com enabled, can somebody confirm this is the reason?

Yes, you have to edit it to dev.example.com. In the Drupal code, the modules use a function who returns the base URL. So if this URL is the old site... it resolves to the old site.

It's also used to protect your website against XSS.


Email webform results - only filled fields Is there a way to email the webform results with only the filled (NOT empty) fields
I don´t want all the fields to be mandatory and 80% of my long long form will be optional and it´s very wierd looking to have all those fields listed in the results, if the fields remain empty

You could alter the webform email template to check for submission results before outputting them.

The documentation for utilizing the template is here:

http://drupal.org/node/1337488

Look under the Heading 'Using a webform email template'.


Adding options to View field settings I want to be able to add arbitrary attributes to rendered view fields.  So for example, I may want to add the attribute itemprop="url" to the rendered A tag for a url field.

I don't want to do this in the actual theming layer - I want to keep it in the view definition.

Is there a way of altering the option forms of any field handlers, so that I can add a new form element that does this.  I would then need to alter the render function to ensure the field is outputted correctly with the new attributes.

So essentially I would want to change the options_form, render functions etc. in the views handler class (e.g. views_handler_field_url.inc).

Any help would be much appreciated.

What you need to do, is to subclass the handler(s) and add the methods you want to overwrite or change. Then you need to replace the normal handlers with your custom create handler(s) wherever you need this, in hook_views_data_alter.


How to detect which module creates session? I am trying to achive Varnish HIT for anonymous user but get only MISSes.

It seems that my Drupal 7 site somehow starts new session for every anonymous user which opens even main page of the site. I want to detect which module makes session to start?

Unless you have a strong suspicion on a particular module or a small number of modules that could be creating a session, finding the 'culprit' module could be too tiresome.

I would suggest searching for the 'cookie name' instead of a string like '_SESSION' as a more accurate and a faster way.

Say if the cookie name is 'PLAY_ACTIVE_ACCOUNT' (real example from site play.google.com), you could navigate to the parent directory of your contrib module and do a grep -iRn PLAY_ACTIVE_ACCOUNT * to find the filename and line number of where this session cookie is being set. And then disable the module or take other action.

You can discover the name of your cookie by using your browser. In chrome you could do this by typing chrome://settings/content in a new tab and then clicking on the button 'All cookies and site data'. And then typing in the name of your site domain (like I have used play.google.com for example)


Simple way to add dropdown arrows to a dropdown containing menu? I have a menu (Main menu). It's a superfish based menu that contains simple dropdown appearances. This menu doesn't have any Superfish style attached to it. It just uses the JQuery of this library and that's it; because of this reason I now need to attach arrows to these specific menu links that contain dropdows... Is there any simple module for this purpose and would you even recommend a modular solution in this case?

I would recommend that you use the settings of the Drupal Superfish menu itself. There is an option to use "Auto-arrows".

They can be further themed via CSS.

Superfish settings (in configure superfish block)

This is your site html source. That auto arrow element is there, but because it uses a white background-image you will not see it, so style it like you need it.


How to make Shipping services available in Rules tokens (data selectors)? I am using D7 and Drupal commerce, with a flat rate shipping service. In my country the VAT for both products and shipping costs must be included in the total VAT amount. But the only line items available in Rules are product line items. So in order for the VAT post to include the VAT for the shipping cost, I need the token:

commerce_line_item

... to also include the shipping service selected in the order. I have spent days trying to figure this out, with no luck. I have read this answer, but those suggestions does not work either. If I remove the filter that only shows product line items in the order summary view, the shipping shows in the table together with the products, which I do not want. And also the tokens still only reflected the product lines.

This is how I need it to look:

Product line item 1
Product line item 2
Product line item 3
   Net amount excl. VAT
   Shipping service
   VAT (including vat on products and on the shipping service)
   Total amount

Any help?

If the data about a product are not available when processing a "line item", you can make them available. To do so, use a technique similar to what is explained in my answer to "How to access commerce_product field of line-items using Rules to flag the Commerce Product?", which includes a Rules Component that looks like so:

{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

Here is a blueprint of what you need to do:

Create a Rules Component, similar to the above Rules Component. Just an import of that Rules Component should be enough (to get started and further improve it as detailed below).
Rework the Drupal Message shown via the last Rules Action in the Rules Component (Starting with "Some details about this product"), by also using any of the available tokens that you're interested in.
Execute that Rules Component inside your Rules Loop of the rule in which you want to loop over all line items.
Improve the Rules Component from Step 1 by creating whatever additional Rules Action(s) you need. Make sure to place these Rules Action(s) AFTER that Rules Action (in the Rules Component) that performs "Fetch entity by ID".


For $vars['id'] == 1 render field Y instead of field X So on my Blog listing page, the first listing is "featured" meaning it spans two columns rather than one, I've achieved most of my styling changes by adding CSS class feature to $vars['id'] == 1 for the blog page.

However, the image for  first teaser is a different proportions and therefore uses custom field header image rather than custom field thumbnail image. In the following:

function innovista_preprocess_node(&$vars) {
  if ($vars['id'] == 1 && arg(0) == 'blog') {
    $vars['classes_array'][] = 'feature';

    //do stuff to switch field here?

  }
}

I want to add a command to switch render of $content['field_blog_thumbnail_image'] with render of  $content['field_blog_header_image']. How can I go about this?

Thanks for your time!

Ok so the way I achieved this was to go into my node--content_type.tpl.php file and do a simple check for 'feature' in the classes string. Printing the correct image depending on the outcome of the check.

So first in admin I set both header and thumbnail images to display when showing as a teaser. But then in the template file I began by hiding them:

hide($content['field_blog_thumbnail_image']);
hide($content['field_blog_header_image']);

This means that they don't render with print render($content);

In the place where I wanted to display the image I then used simple logic to check the $classes variable to see if the string contained 'feature'. If it did I render the header image, if not, the thumbnail image:

if(strpos($classes,'feature')==true){
    print render($content['field_blog_header_image']);
} else{
    print render($content['field_blog_thumbnail_image']);
}


How To Force Commerce Cart View To Update (Ajax?) I admit to being a Commerce -novice-. It's getting better, but it's still quite confusing in some spots. I've posted several questions here over the past year trying to skin the same cat in different ways. We have a Drupal 7 cart. The pricing is pulled in from an external web site via http_request which updates the unit price of all items in the cart on hook_form_alter().

The problem is that the -initial- price that displays in the cart is always 0. The user always has hit  to refresh the page for that pricing to update the View. Commerce seems to want to pull the unit price in from the Product nodes so after a user hits  the cart displays but with a 0 unit price. When they hit  -then- our code fires and updates the price.

So... I need is either:
a) a way to force that view to 'refresh' when the page is rendered (ie. it initially loads with the zero prices, runs the http_request code and -then- renders again). Yeah, it's ugly but I'm just sick of this.

b) Figure out a way using the Rules (which I haven't been able to do) to get the line item price to pull in from the http_request with PHP. This -never- seems to work. It -always- wants to use a rule based on an existing field. If someone could give me a tutorial on how to use PHP with Commerce for the Unit Price I'd buy them a CASE of virtual beer!

c) Figure out a way to assign that http_request price as the line item price when the user hits the 'Add' button. Again, probably a noob thing, but I cannot figure out how to override the Unit Price for the Line Item to the value I want. It -always- wants to use the Unit Price from the Product node.

ANY help would be most appreciated!

Implement a custom rules action and wire it to rules event Calculating the sell price of a product. The sell price of a line item can be forced to any value using the action Set the unit price to a specific amount. The missing piece is a custom rule action capable of retrieving the amount. As a starting point I propose the following (assuming the custom module is named acme):

/**
 * Implements hook_rules_action_info().
 */
function acme_rules_action_info() {
  return array(
    'acme_random_amount' => array(
      'label' => t('Generate random price (with params!)'),
      'group' => t('Examples'),
      'parameter' => array(
        'product_id' => array(
          'type' => 'text',
          'label' => t('Product SKU'),
          'description' => t('The SKU of a product.'),
        ),
        'account' => array(
          'type' => 'user',
          'label' => t('User'),
          'description' => t('A user account.'),
        ),
      ),
      'provides' => array(
        'amount' => array(
          'type' => 'decimal',
          'label' => t('Amount'),
          'description' => 'Return a random numeric amount, except for admin.',
        ),
      ),
    ),
  );
}

/**
 * Rules action: Generate and return random amount of money.
 */
function acme_random_amount($product_id, $account) {
  $amount = mt_rand(100, 1000);

  // Fix price for admin.
  if ($account && $account->uid == 1) {
    $amount = 420;
  }

  // Blue sells, let's boost the revenue.
  if (strpos($product_id, 'BLU') !== FALSE) {
    $amount *= 100;
  }

  return array(
    'amount' => $amount,
  );
}

The rule then looks something like this:

{ "rules_pick_random_price" : {
    "LABEL" : "Pick random price",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "acme", "commerce_line_item", "commerce_product_reference" ],
    "ON" : [ "commerce_product_calculate_sell_price" ],
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "acme_random_amount" : {
          "USING" : {
            "product_id" : [ "commerce-line-item:commerce-product:sku" ],
            "account" : [ "commerce-line-item:order:owner" ]
          },
          "PROVIDE" : { "amount" : { "amount" : "Amount" } }
        }
      },
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : [ "amount" ],
          "component_name" : "base_price",
          "round_mode" : "0"
        }
      },
      { "drupal_message" : { "message" : "Set the price of [commerce-line-item:commerce-product:sku] to amount: [amount:value] for user [commerce-line-item:order:owner:name]" } }
    ]
  }
}

Note that in order to get at the product SKU, it is necessary to introduce a condition Entity has field checking for the presence of the commerce_product field on the commerce-line-item variable.

Please keep in mind that this rule will be executed on every page request for every item in the cart. Additionally it is executed whenever an add-to-cart form is displayed. If this is on a high traffic site, you probably need to think about an appropriate caching strategy.


HTTP ERROR 500 comes on using theme function I used following code:

Inside a route callback function.

 $my_module_form = \Drupal::formBuilder()->getForm('\Drupal\my_module\Form\MyModuleForm');
    $my_module_header_message = "hello;
    $my_module_footer_message = "hello;

 return theme('my_module',
      array(
        'my_module_header_message' => $my_module_header_message,
        'my_module_form' => $my_module_form,
        'my_module_footer_message' => $my_module_footer_message,
      )
    );

Inside my_module.module file

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my_module' => array(
      'template' => 'templates/my-module',
      'variables' => array(
        'my_module_header_message' => NULL,
        'my_module_form' => NULL,
        'my_module_footer_message' => NULL,
      ),
    ),
  );
}

I have also create templates/my-module.html.twig file and rendering hello sample content.

This is my MyModuleForm.php file

<?php
/**
 * @file
 * Contains \Drupal\example\Form\MyModule.
 */

namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
 * Implements an example form.
 */
class MyModuleForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'my_module_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = array();

    $form['my_module_error_message'] = array(
      '#type' => 'markup',
      '#markup' => '<div id="my_module_error_message"> </div>',
      '#weight' => 0,
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

}

I am having problem in defining and calling hook theme for rendering drupal forms.

I think any of these 3 are wrong, a)my form definition, b) theme definition or c) theme call.
Please tell me where am i doing wrong?

In D8 controllers return a render array. Put the template name you have defined in hook_theme() in #theme. Prefix the variable names with a '#':

return array(
      '#theme' => 'my_module',
      '#my_module_header_message' => $my_module_header_message,
      '#my_module_form' => $my_module_form,
      '#my_module_footer_message' => $my_module_footer_message,
);


Limit a user to edit AND view only a specific content type? I have a role dedicated to creating and/or editing a specific content type.  It is the only activity to be allowed for this role.

I have set up login destinations module to go to the content overview and it pretty much works fine.  Users can only edit the allowed content type and when they add content, they immediately get the content type they are allowed to use.

The issue is that I want the user in this role to ONLY see the content type they are allowed to modify.  Currently, it lists all the nodes, which will be confusing for the folks using this role.

Any ideas on a way to use the content overview screen and limit the nodes viewable?

Thanks in advance.

If you have to control the list of content where they go to find content to edit, then you should use VIEWS & make list of only those content which they have permission to edit. Set a page for that list & navigate them there. It's pretty easy..

But if you want to restrict full content type for viewing then you can use Content Access module for that.


Force access denied on 'admin/structure/menu' for everyone except admin I need to write a "simple" feature in custom module which returns access denied for all the users except admin who tries to rich 'admin/structure/menu'. I've tried with hook_page_alter, hook_page_build and also with hook_menu_alter, but none of those functions work. Function hook_menu_alter is caching menus so it sets flag:

$items['admin/structure/menu']['access callback'] = FALSE

to all users and I (as admin) can't see this page also. Any help?

Menus are cached, but decision making functions aren't. So what you need is:

function MYMODULE_menu_alter(&$items) {
  $items['admin/structure/menu']['access callback'] = 'MYMODULE_menu_admin_access';
}

function MYMODULE_menu_admin_access() {
  return $GLOBALS['user']->uid == 1; // Or whatever makes most sense for your use case.
}


How to submit multiple patches to a contrib module? I'm building a web application and use some contrib modules. I heavily rely on a particular module, for which I already submitted a patch a couple of months ago, which was eventually committed.

On these days I had some new requirements, so I added a new functionality to the module and discovered and solved two (unrelated) bugs.

Now a stupid doubt grips me and I'm stuck. My question is: what should I do now?

Create three issues (or write in the existing ones, if the bug was already known) and submit right away my code in three different patches (which are independently written on the current dev version). This means that when a patch will be committed, I'll have to create a new version of the remaining patches for the new dev version
Create a issue with patch for one of the bugs/features, wait that it gets committed, open another issue for another one of the bugs/features, submit a patch on the updated dev version, wait that it gets committed, then open the third issue, submit the patch for the last bug/feature on the again updated dev version. This could potentially take weeks or months.

Usually I would say 1, but due to the short timeframe between patches (a couple of minutes, just the time to create the issues) and the fact that only one person is the creator of all of them, gives me the impression of spamming. It's not a problem for me to create and "maintain" three issues and the related patches, I jut want to do it in the right way.

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


Is there a way to partially rebuild the router or invalidate a route cache? I'm using the Groups module (http://dgo.to/group) to set up groups on a SaaS project I'm working on. I've set up a domain field on the groups, allowing groups to have vanity domain. As such, groups can have custom front pages, which are shown at site route. The front page is set as a field on the Group entity. For example, group 1 may set their front page path as /page/1 and group 2 may set it as /page/2.

To show this front page, I'm using inbound URL processing, showing the different paths on the different domains. To get the different paths to cache independently, I've overridden Drupal\Core\Routing\RouteProviderRouteProvider::getRouteCollectionCacheId():

  /**
   * {@inheritdoc}
   */
  protected function getRouteCollectionCacheId(Request $request) {
    $cache_id = parent::getRouteCollectionCacheId($request);

    // Get the current domain.
    $domain = $this->currentPath->getRequestStack()->getCurrentRequest()->getHost();

    $cache_id .= ':' . $domain;

    return $cache_id;
  }

I've got this all working, however I ran into an issue in that when the path to the front page of a group is updated, the page content doesn't update until the router is rebuild.

I did find a solution, rebuilding the router in hook_entity_update() using \Drupal::service('router.builder')->rebuild(). This works, but it seems very heavy handed.

I tried finding a way to invalidate the cache tags for the route using the cache tags invalidator, but I could not figure out which cache tags to pass.

So my questions are:

Is there a way to partially rebuild the router, rather than rebuilding the whole thing? Or...
Is there a way to invalidate the cache for a route?

Instead of \Drupal::service('router.builder')->rebuild() you can invalidate route matches:
Cache::invalidateTags(['route_match']);

You don't need to rebuild the router table, because the static routes don't change. What you need to clear are route matches, which are calculated on the processed path and then stored for the unprocessed path. And this is the relation which changes in your case.
The router builder invalidates the route matches because after a route rebuild there might be routes missing which are still in route match collections.
To be more selective you can add a second cache tag for the frontpage in RouteProvider::getRouteCollectionForRequest and then only invalidate this tag.
Of course you also need to invalidate entries of the front page stored in page caches, but the front page has probably already a specific cache tag you can target.


Views - Filtering nodes by current user profile field I have been trying to do this for many days but no luck.

On registration, user has a choice to choose his/her interests - checkboxes with term reference widget.
For example - I have made vocabulary 'Interests' with terms sports, computers, painting etc. Every node is related to terms also.

I need to display only the nodes, that users are interested in. For example, if user checked computers on registration, views have to display only nodes with term computer.

I guess there has to be some way to filter only current users profile_field_interests. I couldn't find a way in Drupal 7.

Any suggestions?

You want to use the Views module to create the list – actually a list
of users (rather than nodes/content).
Then you want to use relationships settings to add in the interests.
Finally, Add a contextual filter on "user: uid" with a default value
fetched from the currently logged-in user.

If you haven't used Views before you in for a ride. If you have used Views but not relationships or arguments/contextual filters, then you're also in for a ride.

There's a pretty nice guide for learning Views in the links in my signature – I hope that can be of help. Look especially for the episode on relationships.


Custom text in a View that Links to a PRODUCT (not a node) I'm using Drupal Commerce and a View that displays all my products of a certain type.

The first item displayed in the view (for each product) is the Title and it is helpfully linked to the product page.

I also want to add another link to the product page that says 'Register Now' but I can't figure out how to create custom text that also links to the product page!

I've tried adding the product UUID, ID, and 'Link to Product' fields in my View...and putting them above my 'Custom Text' field...but none seem to work.

When I use {{ id }} for example (as the link in the custom text field), it just makes the link '/id' ...but that's not the actual link to the product, so naturally I get an error. The same problem persists for the other referenced fields.

So...anyone know how to create custom text that links to the actual product?

Option A)

You could add another Title and then simply override the title so it says Register Now by Rewriting the results of the field.

Option B)

Add path as a field and exclude from display.

Add a  Custom Text and checkmark display this field as a link and use {{ path }} as your url.


How to delete files from public folder? I am storing some files in  public folder, programmatically I want to delete those files through the provided path. I tried using below code, but not worked.

function delete_public_files($arg1, $arg2){
  $uri = 'public://';
  $path= file_create_url($uri);
  $fullpath = $path.$arg1.'/'.$arg2;

  //file_unmanaged_delete($fullpath);

  $fid = db_query("SELECT fid FROM {file_managed} WHERE uri = :path", array(':path' => $fullpath))->fetchField();
  if ($fid) {
    $file = file_load($fid);
    file_delete($file);
  }
  else {
    file_unmanaged_delete($fullpath);
  }
}

These files are not recorded in the file_managed table and file_usage table also. So how can I delete these files. If I pass the path to file_delete($fullpath); It will says error that first argument should be object. So how can I achieve all these things. Thanks for any appreciation.

file_delete deletes a file where it is located and its database record also.

First check file_load whether it is rendering an object file.

// load the file
$file = file_load('YOUR_FILE_ID');

// delete file from disk and from database
file_delete($file);

The file_delete() also takes a second argument $force that if set to TRUE will remove the file even if it's reported as in use by the file_usage table.

use drupal_unlink($fullpath) if files are not recorded in the file_managed table and file_usage table.

See this


How do I prepopulate the value of a taxonomy term reference field on the node creation form? I'm using an approach similar to the one taken in this question.  The difference is that I have a taxonomy term reference field in the user profile that I want to use to prepopulate a custom content type.

To prepopulate a text field on a custom content type with a value from the user profile, I have added this code to a custom module:

function MYMODULE_form_MYFORM_node_form_alter(&$form, &$form_state, $form_id) {
 // test if node for has been assigned a NID. If not then populate fields with default data */
  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))){
    global $user;
    $user_fields = user_load($user->uid);
    //set age
    if (isset($user_fields->field_acc_age['und'][0]['value'])){

      $form['field_ad_age']['und'][0]['value']['#default_value'] =  $user_fields->field_acc_age['und'][0]['value'];
    }

However, when attempting to prepopulate a taxonomy term reference field from the user profile to the custom content type, the above code doesn't work; there is no error, but the value is not carried across.  I assume this is because term references are stored differently in the DB, but I don't understand how to change the code to make it work.

Try the following code.

function MYMODULE_form_MYFORM_node_form_alter(&$form, &$form_state, $form_id) {
  // Check if the node has a node ID. If not, then populate the fields with the default data.
  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))) {
    global $user;
    $user_fields = user_load($user->uid);
    // Set age.
    if (isset($user_fields->field_acc_age['und'][0]['tid'])) {
      $form['field_ad_age']['und'][0]['value']['#default_value'] = $user_fields->field_acc_age['und'][0]['tid'];
    }
  }
}


search results in JSON format I have a website built on drupal with search functionality. When I search for example for "test" the link of the search is displayed like search/node/test

Is there any possibility that if I call search/node/test?json or search/node/test/json the returned page would be plain text in json format of node ids ?

Try Services Search & Services module. Using these module you can expose search results as JSON.

Another option is Views Datasource module. Construct a page view which accepts search term as an argument and displays search results in JSON format.


Assign content automatically to specific user I added a new roles - technical support and management. Added several user to that role.

Created new content type called Claim Report contain fields ( title, body, area ).

What I want to achieve is, when authenticated user create new content claim report, select specific area and save, it will automatically shown to specific technical support user account sort by area.

Ex :

techspp1 - area 1

techspp2 - area 2

techspp3 - area 3

When authenticated user create content and choose area1, that specific content only shown in techspp1 account page, choose area2 shown in techspp2 account page only.

Then techspp1 reply / give solution and the user claim content get updated with that solution and get status solved / on-progress.

Can anyone help ?

You can use Node Access Rules to achieve this goal. Using this you can create rule to access that particular content having some condition as per your requirement.


Using PHP namespace hybrid for Drupal modules I've been getting into PHP namespaces and had a thought about how to clean things up a bit in my custom modules. I was thinking that for hooks I could use the traditional Drupal method of defining functions in the global namespace with the module name prefix but for all other functions and classes I could define them inside a PHP namespace. So, for my module "donut_win" a file would look like this:

<?php
namespace {

function donut_win_menu()
{
  $items['donut/win/%'] = array(
     'title'           => 'Hey, there!'
    ,'description'     => "Eveyone wins when donut wins."
    ,'page callback'   => 'Donut\\Win\\render_page'
    ,'page arguments'  => array(1)
    ,'access callback' => true
    ,'type'            => MENU_CALLBACK
  );

  return $items;
}

function donut_win_cron()
{
  # magic!
}

} # namespace global

namespace Donut\Win {

function render_page ($bingo)
{
  # so much magic!
}

}

I'm interested in what potential pitfalls would be with this method and any other disadvantages or advantages. Is this a good idea or am I crazy?

It looks like there aren't any technical pitfalls. But, using PHP namespacing is not part of Drupal's coding standards. Clive sums it up nicely in a comment on the question:

  Drupal has it's own coding standards which it's best to follow, and namespacing functions isn't part of that. If you're not bothered about the Drupal conventions, then sure, do whatever works for you...but if you're looking to write a module to contribute back to the community, or want it to be understood easily by other Drupal devs in the future, it's best to stick to standards


Why drush is not maintained in drupal.org? Drush project page says, "The Drush project has moved to Github."

I would like to know if there is any specific reason for moving to Github.

The motivation for moving to GitHub is discussed on our wiki page:

  Drupal.org is poor fit for Drush as we get features we don't want on our project page

  Usage statistics (Drush isn't a module and thus can't report usage)
  Release names must map to a single Drupal version
  The issue to fix this stuff is nearly five years old.


open a modal just before submit to get an answer yes or no and then submit I'm altering a comment form and on my page i want to show a modal to ask the user for an answer then i will submit.

I tried to drupal_get_form on a ctools modal but a lot of problem on submit it will return to the same submit page and an outher problem with the form_i can not get.

is there any good example or a good idea to do that?

Create a file named as 'search_result.js' and include it into the particular module using drupal_add_js(path/filename.js); and the copy and phaste the following code into search_result.js

 (function($, Drupal, window, document, undefined) {

Drupal.behaviors.searchResults = {
  attach: function(context, settings) {

       $("#elementID").click(function(){
        if(confirm("Are you sure that you want to proceed?")){
            return true;
            }
        else {
            return false;
            }
        });
  }

}
})(jQuery, Drupal, this, this.document);

Note: "#elementID" is the id of the element on which when you click the confirm window is shown


Set up Node content 'localization' / site wide region filter - similar to languages idea What is a good approach re structure and modules to be able to render site content based on a location drop down? It is not an option to display all the content via views.

I'm aware of Views Global Filter. This is be good, but it doesn't work against nodes for one. Therefor only addresses some of the site content.

In principle the user would select from a dropdown a location (custom, based on municipalities). This would then dictate the content presented to that user.

From the admin side, the menus stays the same. One could then create different 'versions' of the same page, each flagged for a specific locality. If the locality doesn't have a corresponding node version, the 'default' node version would be displayed.

Ultimately, I would like to be able to use one dropdown (session stored) that will affect the node content displayed, other views used on different pages and search results.

The translate module is very close, but I don't need the translate functionality, but the rest. Where a few objects are associated to the same url, but rendered depending on the filter.

  Example
  Something like this (-no it's not a multi-council site, just the concept here):

id    page     name               zone
--    ----     ----               ----
1      1       Local Council      East
2      1       Local Council      West
3      1       Local Council      North
4      2       Building permits   East
5      2       Building permits   West
6      3       Pet Registration   East
etc...

  main-menu:
  Home | Local Council | Building | Pets

Therefor, the first page version will be the 'default' and any subsequent ones are then flagged for a zone. If a zone does not have a node with their flag, the default is displayed.

Location offers an option to get a location associated to the node, but how do I track the different 'versions' of the same page to same menu item then? And how do I stop search from giving me every version as a result?

I can see various bits that is getting close, but if some could explain the puzzle pieces please.

There are two 'out of the box' solutions.  The one is to use taxonomies to classify your content in different zones (one for the default zone), and views to decide when to display what.

All you then need to do is allow for your content to be self referencing - in other words add a entity relation field on each content type to itself.

So if you have a content type called basic_page, add an entity relation field in basic_page that can reference basic_page (cardinality of unlimited).   Your default zone node can now have relations to nodes of the other zones.

The other option - the one I would rather consider - is using the entity-translation module.  The module allows you to define 'custom languages'.  Now each zone can be a 'language'.  The fact that you are using languages to implement zones is the beauty abstraction - you are 'interpreting' language as a zone.

Using entity translation, all your node data is automatically 'grouped' as translations of the same entity.

I have done translations on Drupal sites a couple of times: IM me if you have questions.


Where can I get a list of all the Views handler properties when building my own Views handler? I'm learning about Views handlers and need some clarification on how its built.

Looking through the Views Bulk Operations module as seen below. There are 2 IF statements that checks for base table name and revision table. Now my questions are:

When it says table, are they referencing to a table name in the database?
title, group, help, etc... where can I find a list of other parameters for this as seen below in the screen shot?
These fields show up when you click on the "add field" button in the View, but what dictates if it shows up in a content type or user type view?

When it says table, are they referencing to a table name in the database?

Often yes, but not always. A Search API index View declares a "table", for example, but if Solr etc. integration is enabled, it won't necessarily be talking to a database/table. A lot of the time though, yes, a "table" tells Views the base table to select data from; the FROM part of the SQL query.

  where can I find a list of other parameters for this as seen below in the screen shot?

The hook_views_data() API docs walk you through all the possibilities in comments and code.

  These fields show up when you click on the "add field" button in the View, but what dictates if it shows up in a content type or user type view?

The loop in the code you've shown, combined with the condition immediately after. All entity types are looped over, and if their known Views data has a base and/or revision database table, a new field is added to provide operations (because VBO knows it can process those "tables").


Field definition in custom field and varchar_ascii When making custom field and doing field definitions for string I came upon this setting.

  'type' => $field_definition->getSetting('is_ascii') === TRUE ? 'varchar_ascii' : 'varchar',

I just cant find a reference what would it be if a field definition is set to "varchar_ascii" is it something to do with "Collation" ?

The doc block of database.api.php/Schema API state:

  A special varchar_ascii type is also available for limiting machine name field to US ASCII characters.

You can see its implementation in Schema::createFieldSql() of the MySQL abstraction layer.

So yes, it changes the default UTF-8 character set/collation to ASCII.


making correct return array of ControllerBase I am new to Drupal 8 and it is hard to comprehend the documentation. I am required to make a custom module. I came across examples in creating custom modules, but I am having difficulty in making the correct return type. For example, consider the code snippet take from doc:

<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloController.
 */

namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {
  public function content() {
    return array(
        '#type' => 'markup',
        '#markup' => $this->t('Hello, World!'),
    );
  }
}

In this example, the controller is called when some page (defined in route) is visited. In this case an array is returned with #type and #markup, whose definition I cannot find anywhere. Similary consider another example:

<?php
namespace Drupal\acme\Controller;
use Drupal\Core\Controller\ControllerBase;
class DefaultController extends ControllerBase {
  public function hello($name) {
    // the {name} in the route gets captured as $name variable
    // in the function called
    return [
      '#theme' => 'hello_page',
      '#name' => $name,
      '#attached' => [
        'library' => [
          'acme/acme-styles', //include our custom library for this response
        ]
      ]
    ];
  }
}

In this case, the return type is #theme, #name and #attached. These two code clearly shows different return type. As a beginner, I am having difficulty in understanding what to return from function as I cannot see those definitions in the documentation of ControllerBase class.

Where in the documentation are these tags defined and how do I use them in different scenarios? Thanks.

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

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

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

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

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

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

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


How do I set the tab title? How do I set the title of the tab from a controller in Drupal 8? This is the code I am using:

Controller

class myController extends ControllerBase {

    public function node($nId) {
        $nodeObj = Node::load($nId);
        $elements = getRequiredDetails($nodeObj);

        return [
            '#theme'    => 'my_mod',
            '#title'    => 'This is the Tab Title'
            '#contents' => $elements,
            '#attached' => [
                'library'=> [
                    'my_mod/my_mod',
                ],
            ],
        ];
    }

    /**
    * Returns a page title.
    */
    public function getTitle() {
        $route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();

        return $route->getDefaults('#title');
    }
}

Route

my_mod.node:
 path: '/node/{nId}'
 defaults:
   _controller: 'Drupal\my_mod\Controller\myController::node'
   _title_callback: 'Drupal\my_mod\Controller\myController::getTitle'
requirements:
   _permission: 'access content'

But the '#title' in my controller sets the title in the page, not in the tab.  Is there anything I am doing wrong?

If I put something like die('Title Here'); in getTitle(), it will show in the tab. I need to call that method from the route.

If you use Meta tag module, you can use following method. From this method you can get Meta tag title and other Meta tags for view section also.

my_module.services.yml

services:
my_module.route_subscriber:
class: Drupal\my_module\Routing\RouteSubscriber
tags:
  - { name: event_subscriber }

my_module/src/Routing/RouteSubscriber.php

namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

    /**
     * {@inheritdoc}
     */
    protected function alterRoutes(RouteCollection $collection) {

        if ($route = $collection->get('entity.node.canonical')) {
            $route->setDefaults(array(
                '_controller' => 'Drupal\my_module\Controller\MymoduleController::view',
            ));
        }
    }
}

MymoduleController.php

namespace Drupal\my_module\Controller;

use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Entity\Node;
use Drupal\node\Controller\NodeViewController;

class MymoduleController extends NodeViewController {

    public function view(EntityInterface $node, $view_mode = 'full',
    $langcode = NULL) {

        $elements = getRequiredDetails($node);

        return [
            '#theme'    => 'your-theme',
            '#contents' => $elements,
            '#attached' => [
                'library'=> [
                    'my_content/my_content',
                ],
            ],
        ];
    }
}


Change mark-up with a textfield using Ajax In a form I have a field where the user have to enter the name, after this I have to update a markup with data from an external DB using the textfield as a parameter, How can I do this or even Is this posible?

PD: I am using autocomplete to show a list of users when the user is writing in the field.
Thanks.

<?php
/*this part is in hook_form_alter*/
$form['submitted']['empleado']['#ajax'] = array(
'callback' => 'ajax_saldo_markup_callback',
'wrapper' => 'saldo-markup-reload',
);
$form['submitted']['saldo']['#prefix'] = '
';
$form['submitted']['saldo']['#suffix'] = '
';
$form['submitted']['saldo']['#markup'] = _busqueda_saldo_vacas($form, $form_state);
/*this part is in hook_form_alter*/

function ajax_saldo_markup_callback($form, $form_state) {
    return $form['submitted']['saldo'];
}

function _busqueda_saldo_vacas(&$form, $form_state){
$username = $form_state['values']['submitted']['empleado'];
/*DB Query's*/

    foreach ($result as $row) { //At the end I get only one data
    $form['submitted']['saldo']['#markup'] = $row->Data;
    }
}
?>

With this code It seems to work, with Devel, the property "#markup" changes, but is not displayed, if I change it to "#title", it is displayed.

I could make what I was trying to do:

<?php
/*this part is in hook_form_alter*/
$form['submitted']['empleado']['#ajax'] = array(
'callback' => 'ajax_saldo_markup_callback',
'wrapper' => 'saldo-markup-reload',
);
$form['submitted']['saldo']['#prefix'] = '
';
$form['submitted']['saldo']['#suffix'] = '
';
$form['submitted']['saldo']['#value'] = _busqueda_saldo_vacas($form, $form_state);
/*this part is in hook_form_alter*/

function ajax_saldo_markup_callback($form, $form_state) {
    return $form['submitted']['saldo'];
}

function _busqueda_saldo_vacas(&$form, $form_state){
$username = $form_state['values']['submitted']['empleado'];
/*DB Query's*/

    foreach ($result as $row) { //At the end I get only one data
    $form['submitted']['saldo']['#markup'] = $row->Data;
    }
}
?>


How do I stop a stuck-and-running cron job (Elysia Cron on Pantheon)? One of my cron jobs, which are all managed by Elysia Cron and running in its default channel, is stuck and running (R).  My site is hosted by Pantheon, in case that matters.

The job in question is schedule to execute at 15 minute intervals.

What do you recommend I do to stop the stuck-and-running job?

update elysia_cron set running = 0 where name = '[THE NAME IF YOUR CRON JOB]';

Actual sql query based on Mika A answer above


Conceptual Question...Link to an exposed filter result created by a view in Drupal 7 I haven't been able to find the answer by searching, so i thought I would pose this question, I realize there may be more than one right answer, but basically I want to link to a specific result of an exposed filter without having to disable ajax.

I have a block created by a view on a panels page which will have the latest 4 magazine issues. (image and link) I want to link to a specific result in the exposed filter, when the user clicks-through.

The exposed filter has year (-3+3) and season which has the taxonomy terms (fall, winter, spring, summer) The default (when terms are not selected) is to show 4 of the latest magazine issues sorted by most recent.  Since there are only 4 issues per year and the year will be relative to "now"; Would the way to go about this be to clone the view with the exposed filter page 4 times for each season? How would one re-write the link to go to that specific result in the exposed filter? I'm sure there are other options, to achieve this, so please let me know.

Thanks.

You could disable ajax, and then set your exposed filter to the relevant values for each link, and then save the url of each page.

Then re-enable ajax however use the links you previously saved to create hard coded links to the view with specific filters.

This works because even if ajax is enabled you can still pass in arguments via the query string.


Status Report vs Available Updates My Status report shows that my Drupal version is 7.32 but my Available Updates page says 7.30. Can you tell me why they would be different? No recent updates have been made.

This could indicate that your site was hacked due to drupalgeddon bug. If you have not updated from 7.30 it is likely that an attacker changed the version numbers. Check here: https://www.drupal.org/node/2357241


How to add Product image field to view I'm not sure how much sense this makes as I've confused myself so much trying to do this.

I'm using Drupal 7.28 and the Drupal Commerce 7.x-1.9.

Basically the image and the description fields are both on the Product Type not the content type as each product has its own description and image.

In my view I now need to add the image field, but I can't add it, which I believe is because the field isn't in the content type.

When I add the 'Content: Referenced Products' relationship to the view, I am then able to add the image field to my view.

However when I then select to link this image field to the original content, the field links to the admin page where I edit the product - not the content type node that is displaying the product.

Also, after adding the image field, the view lists the image for every single product variation whereas I just need one image that links to the node.

This drives me nuts in Drupal Commerce. Now that you have the relationship, add a field to your view Content:Path using the relationship and tick boxes for Exclude from display then go to Rewrite results and tick the box next to Use absolute link (begins with "http://"). Move this field so that it appears above your image field. Then, in your image field, Link image to [Nothing] and under Rewrite results tick Output this field as a link and under Link path enter the token for your path.

Good luck.


Should I use the Rules module to implement custom code when performing state transition? I need to run some custom code when I go from state A to state B (using the workflow module).

Should I implement this with the Rules module and call my function from there or implement all of it in hook_workflow from a custom module?

In short, what is the Drupal approach?

Using the Rules module for this is indeed an option, whereas you should be able to implement your "custom code" using the Rules Action to "Execute custom PHP Code". If you do, make sure to not forget the PHP filter (otherwise you'll run into "Rules "Execute custom PHP Code" option not available ...").

Of course, that required 'PHP filter' might be your show-stopper. BUT: are you sure you need "custom code" at all? There may be alternative (site building only) techniques to even not need that "custom code" (and hence you'd avoid the need for that PHP filter also). And/or as a variation, you could write your own (custom) Rules Actions also ...

Not to forget these benefits also:

Less custom code (= easier to maintain and/or upgrade to future Drupal versions).
Possible out-of-the-box integrations with other modules, such as Flag, VBO etc.


Problem while updating modules I'm running a Drupal website for a while but suddenly and for an unknown reason the website become unable to update modules via the back office.
The download of the modules goes good but when I click to the button to update the database I got an error page and when I see the recent reports logs I have that:

UpdaterException: Unable to determine the type of the source directory. in Updater::factory() (line 99 of ../www/includes/updater.inc).

Is there any solution for that problem?
Notice: I'm using Zeus server instead of Apache.

It looks like the directory it's expecting the source to come from doesn't exist. Here's the snippet of code which causes the exception to be thrown.

if (is_dir($source)) {
  $updater = self::getUpdaterFromDirectory($source);
}
else {
  throw new UpdaterException(t('Unable to determine the type of the source directory.'));
}

When updating this is the default directory: $directory = 'temporary://update-extraction-' . _update_manager_unique_identifier();

Make sure your defined temporary folder in the file system can be written to by Drupal.

If all else fails, manually update your modules via file transfer.


getvalue() of multiple values field return only the first value I added a new field in the field manage user page. This is a sample integer multivalue field. (we can enter several integer)

I edited the profile of the admin user. I added (and save) some values in this field :

42
66
23
77

In a custom module, I load the current user and I want display all values of my integer multivalue field :

// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// Get field data from that user.
$mycustomfield = $user->get('field_mycustomfield');

but when I print $mycustomfield->getValue(), I get only the first value :

// Display values
kint($mycustomfield->getValue()); // return only 42, but I want get 42, 66, 23, 77

How can I get ALL values of a custom field ?

Thanks :)

EDIT

I try this ...

// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// Set and save field data from that user.
$user->get('field_mycustomfield')->setValue(array(1,2,3,4,5));
$user->save();

// And display
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$user_mycustomfield = $user->get('field_mycustomfield')->getValue();

kint($user_mycustomfield); // print array(1.2.3.4.5) x)

With a new user, if I set several values from his user profile edit page, getValue() return only the first value

But if I set several values via the api, I can get all values with getValue

It's really strange..

Drupal fields are represented by the ItemList class (whether they're multi-valued or not). The convenience method getValue() iterates through each item's getValue() method to build an array representation of the data value.

To retrieve a string representation of all the items in the list, you can use ItemList::getString(), which iterates through all the list items and calls getString() on each, then implodes them using ", " for glue.

So, for your example:

var_dump($user->field_mycustomfield->getString());

will output

string(14) "42, 66, 23, 77"


Getting the value of taxonomy field in a node.html.twig template (Drupal 8.x) I'm currently trying to figure out how to get the value of a field of a node in node.html.twig template. The field (machine_name: news) is linked to a taxonomy and multiple values can be selected. I see a lot of threads here on Drupal StackExchange - tried all the solutions, but not a single one fixes my problem.

I'm currently trying:

  {{ node.field_news[0].value }}

But then nothing is printed. When I try:

  {{ node.hasField('news') }}

... the value '1' is printed. So the field is available.
I tried dumping the whole 'node' object using the Twig dump() method, but then I get a white-screen-of-dead due to memory restrictions.

Any idea's what is the correct way? I'm using Drupal 8.3.2

I found the problem. The 'news' field is a multi-value selectable field. The correct way to access the field would be:

{{ content.news.0 }}

Of course, this will only print the first value in the collection, so I created a for loop in the twig template to loop over the different values.

I needed the 'title' and the 'url' of the taxonomy term. This could be retrieved by:

{{ content.news.0['#title'] }}
{{ content.news.0['#url'] }}


Help required to set up multisite using organic groups (OG module) I would like to create different multisite using organic groups in drupal. Each organic group would be a subdomain or domain. How can I achieve this functionality? I do not want to use domain access module.

What I exactly want is, when an organic group is created it should ask for the subdomain or domain and the user can enter the subdomain or domain which is to be associated to that organic group. Then when the user enters the subdomain.site.com the appropriate organic group should load. site admin associate to this organic group can login like this subdomain.site.com/user.

How can the above scenario achieved through organic groups?

Ok I have done it using Organic groups, spaces module and PURL.

First Install Spaces module after installing drupal
Then you can install PURL module and then organic groups module and OG theme module. OG theme associates theme to a group. You can also install OG menu if needed.
Once PURL is installed, go to admin/config/search/purl/types, enable subdomain option and domain option if needed.
Now create a content type of Group type or install OG example module (it automatically creates a organic group content type)
Now create a node which is of type group - node/add/group
Fill in the options and enter the Subdomain. For the subdomain to work you should have added ServerAlias *.site.com in your httpd.conf file
Once the node of type group is created your minisite is ready.
Using OG theme you can associate a separate theme for your organic group created.
Using og menu you can associate a separate menu for your organic group.


On export Managed_files With Features No UUID Added I have a custom field  of type 'managed_file' along another field of type - 'file'. This node is exported into feature. The field with 'file' type gets UUID attached while it does not for 'managed_file' field. In the database table 'file_managed', there are UUIDs for all the files included ones uploaded with 'manged_file'. Why is it not including the UUID for managed_file custom fields in the feature? Is there a separate module for this? Any suggestions how to best export/import files? Your help is much appreciated

uuid 7.x-1.0-alpha5+17-dev, uuid_feature 7.x-1.0-alpha3+15-dev, strongarm - 7.x-2.0, Drupal 7.26

I end up creating module for handling assets exporting via Features either as custom field or not. Here is write up
http://margotskapacs.com/2014/04/handling-artifacts-for-custom-module-in-drupal/


Display Wordpress posts I currently have both a Drupal and a WordPress site. Is there a module that can display the latest posts from my WordPress site, or will I need to write my own?

The Aggregator module that ships with Drupal core can pull in posts from the WordPress site's RSS feed. For more functionality and overall flexibility, you could use the Feeds module.


Barrio theme not showing user menu drop-down I tried to show the multilevel dropdown submenu for the user account menu in subtheme using bootstrap_barrio but it is not showing up. however i did the configuration in the block to show multilevel and put the menu links as expanded.

after investing a lot .. i found that barrio theme is only coming with impelemntation for the navigation menu not for the user account menu .
what i did is i just copy /templates/navigation/menu--main.html.twig and renamed it
menu--account.html.twig

and it works fine


Modifying the node-form in domain module Before I start i'll confess that i'm a drupal noob..I'm implementing a requirement in drupal 6.22 with drupal's Domain Access module ( http://drupal.org/project/domain )  which unfortunately has less documentation for a person of my level.

My requirement is such that the people who typically create/add content (page/story) do not need to see the fieldset of domain module with the Domain Access Options, and the created node by default should be sent to all affiliates and published to all the Sites in affiliates list.

I felt that rather than covering up the fieldset in a theme based manner which wasn't much preferrable i felt it needed to be a form alter kind of approach.

Initially planned to use hook_nodeapi to set the $form['domain']['#access'] = FALSE, but realised that it actually does the following as per Drupal's Forms API

  "the element is not rendered and the user submitted value is not taken into consideration."

Since I require the values to be set in an invisible manner that wouldn't help.
I wish to learn the following

Is my approach of using hook_nodeapi the right way, else any other like hook_form_alter or hook_form_FORM_ID_alter a better suited one or am i totally on the wrong track.
How does one set multiple checkboxes as checked in 'checkboxes' type in drupal forms. Couldn't find examples suited to my level of IQ (:D)
If I manage to accomplish my current requirement is there a possibility where I could set some params such that only specific affiliated sites are set for a node based on the user's access and my business logic.

Any help or suggestions on this specific issue are most welcome.

Thanks and Cheers!!

I found my solution: I set the respective values in the node save events, which didn't require to use the interface provided by Drupal. I didn't have concerns on the form and its settings.


Term taxonomy child from first and second level menu I have a drupal commerce with taxonomy which have child.The menu was generate automatically.
Exemple:

Vehicle
      |-->4 wheel
                |-->car
                |-->bus
      |-->2 wheel
                |-->motorbike
                |-->bicycle

I want to display a link "4 wheel" and a "link 2 wheel" when we are on the "Vehicle" page (which don't have product inside)
And I want to display "motorbike" and "bicycle" when we are on the "2 wheel" page (which don't have product inside).

I have a drupal commerce default content display and the default views product_category.
I found this video which make me make a new view call catalog which does exactly what I want (video at 15:18). https://www.youtube.com/watch?v=y1jqu8JnLbU
But the main menu (automatically generated) still going to product_category. So now if I want a can make a menu and add every link by my hands but I don't like bad work.

So my question is how can I say to drupal commerce: "Hey now stop using the default view which is call product_category and use my view which is call catalog.
Or
How can I configure the product_category view to display all the child taxonomy like I explain.

I found many stuff but nothing very helpful
https://drupal.stackexchange.com/questions/5732/is-there-a-good-tutorial-for-entity-views-attach-module
The path module
The PHP filter with code
Try to make a block this context filter and display it ...

If someone can help It will be nice !

I've found a way to do it. It's not the best way but it's a way which is enough clean for me for now .
It's with Menu block module.
I made 2 blocks with this module and I configure it on a specific page.
http://www.youtube.com/watch?v=1rku2vHqZP4

If you want you can also use Pathauto module to generate nice url so you don't need to configure  on evry specific page but on every page with a specific URL like www.yoursite/Vehicle/*.

To configure that go to admin/config/search/path/settings and set the Slash (/) option to "Do not Replace" under "Punctuation" then go to the taxonomy path which you need and put [term:parents:join:/]/[term:name] the URL will be like www.yoursite/Vehicle/4-wheel/car.

Hope that help.


Multi Dimensional Taxonomy I'm trying to extend my already existing Taxonomy list by a second value per existing one. Let's say I have a Taxonomy list like this:

First Item
Second Item
Third Item

Now i want to store a second value (FI, SI, TI) to receive a list:

First Item | FI
Second Item | SI
Third Item | TI

where I can access either the first or the second value of one taxonomy item. Is that somehow possible?

The only thing I would know to achieve that, is a custom content type.

You can add new field to taxonomy terms. Go to vocabulary and than to Manage Fileds tabs and add new textfiled. After that you can edit you tems and add seecond values.


How to reference identical files on multiple nodes? I have created two nodes that contain a File Upload.
Is it possible to reference files common to both nodes or do I have to create duplicates? I want to reduce the overhead of managing large number of uploaded files.

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

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


Is there a Self-Imposed Bulk Operations Limit? My database has millions of nodes.  We've been approved to delete a very large amount of them given certain criteria so I set up a view with VBO to handle the batch deletions.  I've exposed the pager limit setting in Views so I can run batches of different sizes.  When I try to run anything higher than 1000 nodes per batch (10 per run to prevent timeouts), the batch sets its max value to some number around 1000, depending on the server.  This is limiting me to run either 1000 at a time or attempt to run the entire result set.

I'm looking for any ideas as to why there is this seemingly self imposed limit on the bulk operations.  My sandbox server sets the batch max at 1001 while my production server sets it to 995.

Drupal 7.27
Views 3.7
VBO 3.1

No. there is no such limit.

In Views, make sure you have enabled the option to select all items across all pages. With that configuration, all items will be selected regardless of the pager configuration.


How to sort taxonomy terms on a term reference field? I have a taxonomy term reference field on a node. On the "node/add" page I would like to sort the terms by "due date" (a field added to that vocabulary).

If you're stuck using a term reference field, here are some widget options:

https://drupal.org/project/term_reference_sortable
https://drupal.org/project/ttr_configurable_widget
https://drupal.org/project/taxonomy_orderselect


hook_page_alter and trying to change the '#theme_wrappers' property I'm going a bit Drupal crazy trying to change the '#theme_wrappers' property of certain blocks in my sidebar region. I am able to set it using hook_page_alter and can dpm() it and confirm it is being set, but it never calls the function I point it to:

 $element = $vars['page']['sidebar_first'];

  foreach($element as &$elements){
    if (array_key_exists('#block', $elements)){
      $menuBlock = (array) $elements['#block'];
      if ($menuBlock['delta'] == "navigation" || $menuBlock['module'] == "menu"){
        $elements['#theme_wrappers'] = array('wet4_menu_tree__menu_sidebar');
      }
    }
  }

=====================

function wet4_menu_tree__menu_sidebar(&$variables) {
  dpm($variables);
    return '
' . $variables['tree'] . '
';
}

Any ideas?

As I commented above, the issue was that I was missing the & before $vars in this line:

$element = $vars['page']['sidebar_first'];

It was not creating a reference so it wasn't actually setting my '#theme_wrappers' property.


How can I copy multiple nodes and reset fields belonging to the copies in one operation? I want to copy a list of nodes, create one copy of each node, and at the same time, reset the contents of two fields on each new copy node.

I am using Views Bulk Operations to select the nodes, and Replication with Replication UI to make copies of them.

I think I should be able to reset the two fields on my new copy nodes just with Rules, but I've been unable to work out a Rule that actually works, and several widely linked resources that refer to using VBO with Rules seem to have been deleted recently.

In my opinion is easier if you write the code in a custom module.
You should create a custom form with form api with a button that call a function that select the nodes with db_select and after does the operations, copy :

// Load a node
$node = node_load(1);

// unset version and node id's
unset($node->nid);
unset($node->vid);
unset($node->path);

and unset values of the two fields for each node and save node

unset($node->field1);
unset($node->field2);
node_save($node);

After create a custom block and in block_view load the custom form.


How to hide child field collection using jquery I have 3 field collection 1st is parent in that having other 2 is child field collections.

parent FC: Student Info
child FC 1: English Info
child FC 1: Maths Info

Set field setting "unlimited" to parent field collection(i.e Student Info).

Now I want hide 2 child field collection (i.e English Info and Maths Info) on click of "Add another item"
I have hide child FC using jquery

For exmaple:

jQuery('.child1').hide();

jQuery('.child2').hide();

Child field collection hide initially, but if I click "Add another item" button then jquery removed and child FC shows. I have tried to bind click event in jquery but it's not working.

Can you replace the code in your JS file with the following:

(function ($, Drupal, drupalSettings) {

  'use strict';

  Drupal.behaviors.myModuleName = {
    attach: function (context, settings) {
        $('#node-student-form .field--type-field-collection .field--name-field-child-english-info').css("display","none"); // Child FC 1
        $('#node-student-form .field--type-field-collection .field--name-field-child-maths-info').css("display","none"); // Child FC 2
    }
  };

})(jQuery, Drupal, drupalSettings);

This is based on this article
The attach() function ensures that your code runs each time an Ajax call is made


How to create a group page when creating a new group? When I create a new group (using the Organic groups module), I want to use the Rules module to create a new group referenced page.

I can create a new page using the Create new entity action, but I haven't been able to set the group reference/audience. I've tried using both Add entity to Group and Set a data value, but I can't figure out how to set the parameters.

{ "rules_create_1st_story_page" : {
"LABEL" : "Create 1st Story Page",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "og" ],
"ON" : { "node_insert--story" : { "bundle" : "story" } },
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "story_page",
        "param_title" : "Page 1 - Start here",
        "param_author" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "og_group_content_add" : { "entity" : [ "node" ], "group" : [ "node" ] } }
] }}

Have a look at the exported rule below, which is a variation of the (exported) rule in your question:

{ "rules_create_1st_group_page" : {
    "LABEL" : "Create 1st Group Page",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "group" : "group" } } } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "post",
            "param_title" : "Page 1 - Start here",
            "param_author" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "grouppage_created" : "Created GroupPage" } }
        }
      },
      { "list_add" : { "list" : [ "grouppage-created:og-group-ref" ], "item" : [ "node" ] } },
      { "entity_save" : { "data" : [ "grouppage-created" ], "immediate" : 1 } }
    ]
  }
}

Some more details about "my" variation, about the content types involved:

"Group" is the content type I'm using for my OG groups.
"Post" is the content type which has an Entity reference field with machine name og_group_ref (and widget = OG reference), so that I can assign nodes of content type "Post" to the appropriate field. Be aware however, this field allows for unlimited values (not sure if that's your case also).

Some more details about the actual rule:

Rules Event: After saving new content.
Rules Condition: Content is of type Group.
Rules Actions:

Create a new entity, of type Post (note the grouppage_created variable name I've used, instead of just the default entity_created ...).
Add an item to a list, whereas the list is grouppage-created:og-group-ref (a multi value field, remember, so you cannot/should not use "set a data value, a common mistake when creating custom rules ...), and the item to be added is ... you probably guessed it: the node (of type Group), that just got saved.
Save entity, for the grouppage_created (not sure if this Rules Action is really needed, but IMO it's a kind of safe (best?) practise to be sure that this newly created grouppage_created-entity also gets saved).

And yes I actually tested this rule in my own environment ... Sure enough, in my case a new node (of type Post) got created, after I created a new Group.

Your turn to adapt your rule (with your content types), to make it similar to my rule here (assuming you also allow multiple values for your og-group-ref field. If yours is single value, then probably all you need to change is to replace the Rules Action Add an item to a list by an action to Set a data value (using similar variables).

PS: I'm assuming your question is about D7.


Is there a Drupal Commerce integration with Facebook/Instagram Shopping? Facebook catalog allows selling through their catalog. They have integrations for several platforms like Big Commerce and Shopify. The basic integration without commerce requires manual shipping. Big Commerce verified that their Facebook catalog integration allows you to tie back to your ERP system for tying to business shipping function.

Does DC have a FB catalog/shopping integration similar to this?

Thanks,
Kevin

I open-sourced my custom solution for using Facebook Product Catalog with Drupal Commerce 2.x.

While it isn't a plug-and-play module, with a few modifications it could be useful for you.

Check out my blog post to get more information: https://gorannikolovski.com/blog/drupal-commerce-and-facebook-product-catalog


Is there a way to set the styling for the "choose file" button for Webform module? I've not been able to figure out how to isolate the "choose file" button that's set in file upload field for webform module. I can style the field, but I can't get the button. I've looked all of the place, but can't find anything on getting anything on that specific button. This is a D7 site using the 7.x-3.18 version of webform.

It would be great if I could add a class, but if I could just get ahold of it in some way that doesn't affect the entire field that would be ideal.

Here is the output:

<input type="file" id="edit-submitted-resume-upload" name="files[submitted_resume]" size="22" class="form-file">

The ID handles the entire field and I've been able to do a little with that, but can't use it to control that button.

Any ideas?

Thanks in advance.

Yes, actually styling a FILE INPUT field is hard because, just like you're seeing, it's a singular field that is hard to pick apart.

Here is a discussion of styling file input fields from stackoverflow.

As you can see - thought there are many solutions presented, they all require some jquery and essentially hide the input field and replace it with something else.

So in short - there is no easy way to do it.


What can I do to remove this entity definition from the database? Long story short, in developing a website in Drupal 8 we decided that the custom entity we were building could just as easily be made with standard nodes. We deleted the entity code (or something to that effect) and now, somewhere hidden in the database, is the definition for the team entity that we've removed. Fortunately, this isn't causing too many issues. However, when deleting fields from a content type (and probably in some other circumstances of which I'm not yet aware), we get the following error:

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "team" entity type does not
exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 133 of
[...]/core/lib/Drupal/Core/Entity/EntityTypeManager.php).`

I've attempted doing what was suggested here, but it resulted in the above error.

What can I do to clean up the database/website so this error stops happening?

First solution (the best one if you can) (thanks @Clive) :

Put the deleted code back
Uninstall the module
Reinstall the module with the new code

Second solution (ugly, but worked for me)

Open your favorite SQL client (adminer in my case)
Search for your entity id in all tables
Remove all matching entries
Clear the cache


Autosubmit exposed filter? Is it possible without change in core files to display exposed filters without "Submit" button and with autosubmint functionality? I mean autosubmit form, not autocomplete.

This is not an option at the moment in Drupal 8.
This option was removed in this issue
There is an issue for it.
They are trying to get it into ctools right now. ( 20-10-2016 )


View: Distinct list of all referenced entities Basic setup: 3 content types

Festival
Event
Speaker

Event has a entity 1-to-1 reference field containing a Festival.

Event also has a 1-to-many reference field containing Speakers.

How can I set up a View to list all of the Speakers taking part in a Festival? (A Speaker can take part in more than one Event).

Create a view of events with relationship to the speakers and contextual filter to festival

For filtering duplicates you have to turn on aggregation as seen above and setup body aggregation settings: group column: format

The contexual settings for festival are

NOTE: To see preview for a festival put a festival node id in the contextual filter and press preview

Finally you can put the view block display on content region or any other region from  structure > block layout and the block with relevant event/speakers will be present when you visit a festival page


Tables are not creating with hook_schema I need to create a module to save data of term page visits.

<?php

function term_count_schema() {
  $schema['term_search'] = array(
  'description' => 'Stores timestamp range..',
'fields' => array(
  'tid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Taxonomy ID.',
   ),
  'vid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Vocabulary ID.',
    ),
  'timestamp' => array(
    'type' => 'int',
    'not null' => FALSE,
    'description' => 'UNIX timestamp.',
   ),
 ),
 'primary key' => array('tid'),

  );

  $schema['term_count'] = array(
'description' => 'Total views.',
'fields' => array(
  'tid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Taxonomay ID.',
  ),
  'vid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Vocabulary ID.',
  ),
  'totalviews' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Total number of views which increments on every page load.',
  ),
),
'primary key' => array('tid'),
  );
  return $schema;
}

This is not creating tables term_search & term_count ind DB. Any thing wrong in my code.

<?php
/**
 * @file
 * Contains install and update functions for Views.
 */

/**
 * Implements hook_install().
 */
function mid_components_install(){

}

/**
 * Implements hook_schema().
 *
 */
function mid_components_schema(){
    $schemas = array();
    $schemas['mid_components'] = array(
        'description' => 'The mid_components data.',
        'fields' => array(
            'cid' => array(
                'description' => 'Primary key',
                'type' => 'serial',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
            'title' => array(
                'description' => 'Human readable name of the component.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
            ),
            'machine_name' => array(
                'description' => 'Unique machine name of the component',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
            ),
            'description' => array(
                'description' => 'Description of the component.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => FALSE,
            ),
            'options' => array(
                'description' => 'A serialized array of options for this display; it contains options that are generally only pertinent to that component.',
                'type' => 'blob',
                'size' => 'big',
                'not null' => FALSE,
            ),
            'status' => array(
                'description' => 'Status of the component',
                'type' => 'int',
                'not null' => TRUE,
                'default' => 0,
                'unsigned' => TRUE,
            ),
            'created' => array(
                'type' => 'int',
                'description' => 'The Unix timestamp when the item is created',
                'not null' => TRUE,
                'default' => 0,
            ),
            'changed' => array(
                'type' => 'int',
                'description' => 'The Unix timestamp when the item is modified.',
                'not null' => TRUE,
                'default' => 0,
            ),
        ),
        'primary key' => array('cid'),
        'unique key' => array('machine_name' => array('machine_name')),
    );
    return $schemas;
}

/**
 * Implements hook_uninstall().
 */
function mid_components_uninstall(){

}

Follow this method. And Make sure after doing any chnagings to your .install file, uninstall your module and reinstall it again.


How to load block on link click with AJAX framework? I have tried in my custom module:

Declaring a path for Ajax callback

function custom_menu() {

  $items['ajax-block/%'] = array(
    'title' => 'Ajax test callback',
    'type' => MENU_CALLBACK,
    'page callback' => 'ajax_link_callback',
    'page arguments' => array(1),
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access content'),
  );

  return $items;
}

now the callback itself

/**
 * Callback ajax
 */
function ajax_link_callback($from_cid, $mode = NULL) {

  if ($mode != 'ajax') {
    drupal_set_message('Turn Javascript');
    drupal_goto(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '<front>');
  }

  $commands[] = ajax_command_html('.region-content', some_func());

  return array('#type' => 'ajax', '#commands' => $commands);
}

I have a few manually created links:

link1
link2
link3

Now I need such functionality - when I press link1 - block1 loads content in to .region-content, when I click link2 - block2 and etc.

How can I do this?

Looks like your missing the ajax_deliver command

$commands[] = ajax_command_html('.region-content', some_func());
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);


Cannot see Display Suite menu under Administration I am following this training. I have downloaded the module and have also enabled it. The video mentions a new 'Display Menu' under 'Administration'. I can't see it, though I am logged in as an administrator.

What am I doing wrong? (I am still new to Drupal)

UPDATE

I just tried to install the Module on a fresh install, and I don't get an issue there. Looks like my current system is corrupted. Is there any tool to 'correct' it?

Try clearing your drupal cache, or alternatively try visiting the URL directly under admin/structure/ds


Boost makes the editing of content/settings impossible Once the Boost is enabled and I add its code into the .htaccess something weird starts to happen. No changes are being saved when editing the content or settings, after hitting the submit button the page just reloads ignoring the changes, no messages are shown, and sometimes the admin menu disappears. For the not logged in users the Boost works fine, html files are being generated and served. But it makes impossible to administer the site, looks like it affects the Drupal for logged in users as well or something. As soon as I remove Boost's code from the .htaccess – everything starts working again.

Using it on Apache 2.2.29

Tried to set it for the specific pages only, but had no success.

Could you help me and tell what needs to be done?

Did you add the Boost section in your .htaccess, which is necessary to make it work? If you already have, you might check that the part about GZIP is present.

I had this same problem, and what I did was to disable and uninstall and remove the Boost module. Then I installed and enabled the previous Boost version where this GZIP section is present. I saved that part in .htaccess and went back to installing the latest Boost version again, but with the added GZIP part in the .htaccess file.

You can also check this thread out: Impossible to edit nodes, log to in etcetera after enabling Boost and editing .htaccess

The most important gzip rules are these (if you want to try this without disabling, uninstalling and the re-installing the module:

  # GZIP
  RewriteCond %{HTTP:Accept-encoding} !gzip
  RewriteRule .* - [S=1]

  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{SERVER_NAME}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz -s
  RewriteRule .* cache/%{ENV:boostpath}/%{SERVER_NAME}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz [L,T=text/html,E=no-gzip:1]

Hope this helps.


Turn off Twig cache in general Drupal does cache Twig templates. Normally, it is a good thing, as long as you don't have a multilingual site.

In my case every t()is not working as the template is cached in the wrong in English, giving German no chance to ever be outputted.

Is this the proper way to deal with t() calls?

 $settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

It seems a bit wrong. As I understand these settings are more for the development process, not for production. Also there really should be a setting to use caching in a language specific way.

In Drupal cache content is language specific. Default is a cache context for the language. Sometimes you need to clear the cache one more time, but then this should work.

You can check this in the database table cache_render. All cid's should contain [languages:language_interface]=langcode and if you visit the same page in different languages you should see multiple cache entries.

Disabling the cache with a null backend is only for development. For production you need to find a solution for the language specific caching issue.


Show links only to sub menus items, not to parent menu I added some links to Main menu and created sub links for it. Now the problem is that I've to give url to the parent menus of sub links. I want it to be disabled. Links should be for sub menus only. How can I do it. Please help. In the pic, I don't want link for 'Contact us

Use Menu item container module, containers have no URL path associated with them. So they are not links, just regular text

  By default, the Drupal menu system only allows you to add menu items
  that are links. With this module, you can add menu items that are
  simply containers, and not links.

also look into Special menu items and Menu Firstchild modules.


Can't get jQuery UI autocomplete working The text field that is created seems to just act like a normal textfield, no autocomplete function or any indication that it works at all.

There's no errors in the console. I've run checks to see if jQuery UI is loading, it is. I'm using jQuery Update module, so both libraries are at version 1.10.

I'm using the Bootstrap theme, but I've tried disabling that and using Bartik, it makes no difference.

Any ideas?

Here's the form alter function I'm using in my module. It fires just fine.

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

    $form['business_category'] = array(
        '#title' => t('Business Category'),
        '#description' => t('Category' ),
        '#type' => 'textfield',
        '#id' => 'business_category',
        '#attached' => array(
            'library' => array(
                array('system', 'ui.autocomplete'),
            ),
            'js' => array(
                drupal_get_path('module', 'mymodule') . "/custom.js",
            ),
        ),
    );

}

Here's custom.js

(function ($) {

        $( "#business_category" ).autocomplete({
            source: [ "cat1", "cat2", "cat3" ]
        });

})(jQuery);

Adding drupal behaviours, as suggested by @2pha, did the trick:

(function ($) {
    Drupal.behaviors.infiniteScrollAddClass = {
        attach: function (context, settings) {

            $( "#business_category" ).autocomplete({
                source: [ "cat1", "cat2", "cat3" ]
            });
        }
    }

})(jQuery);


Simple Panels question on where the panels get placed on the page This is a silly question but how does Panels know where to insert the panels I just made? I didn't type a single line of PHP and yet there it is! It's like magic (woooh...)! On a side note, can I define where it gets placed through PHP? Thanks.

Panels places the panel into the 'content' region of the selected page.

If you want to place it somewhere else on the page, try using mini-panels to create a block and place it that way.  No need to write custom PHP code for that.


Drupal 8 - Drush composerRequireDrupal8 error System: Ubuntu 14.x

Drupal: 8.x

Drush: 8.x

I recently have installed Drush using composer global require drush/drush:dev-master code and it got installed successfully.

I ran command which drush and the terminal gave me the path /home/ravi/.composer/vendor/bin/drush.

The problem is, I am not able to execute any commands from project root. It gives me below error:

PHP Fatal error:  Cannot redeclare composerRequireDrupal8() (previously declared in /var/lib/composer/vendor/composer/autoload_real.php:63) in /var/www/html/study/drupal/8/vendor/composer/autoload_real.php on line 70

But when I execute below command from project root:

/home/ravi/.composer/vendor/bin/drush status

then Drush works perfectly well.

Is there any way I can use Drush from project root? Or have I made any mistakes in installation? Please help.

PS: I have tried updating composer and composer self-update but it did not help.

Please do not install Drush using composer global require.

Quoted from http://docs.drush.org/en/8.x/install-alternative/.

If you have Drupal 8 installed conventionally best practice would be to install Drush 8 globally by downloading the latest drush.phar, see http://docs.drush.org/en/8.x/install/.

If your Drupal 8 site is composer based then Drush 9 is probably already included. If not see http://docs.drush.org/en/master/install/.