problems with CKEditor install in drupal 7 I have installed CKEditor correctly and still get the error:

  The CKEditor component is not installed correctly. Please go to the
  CKEditor homepage in order to download the latest version. After that
  you must extract the files to the sites/all/modules/ckeditor/ckeditor
  or sites/all/libraries/ckeditor directory and make sure that the
  sites/all/modules/ckeditor/ckeditor/ckeditor.js or
  sites/all/libraries/ckeditor/ckeditor.js file exists. Refer to the
  README.txt file for more information.

I have downloaded and re-downloaded CKEditor several times. Everything is there but still getting error.

I am also confused about exactly what to put in the CKEditor global profile.

It's an issue that happens from time to time.

The instructions that you see are fine:

  Extract the archive and copy its contents into a new folder in the following location:
  sites/all/libraries/ckeditor

  So the actual library can be found at: sites/all/libraries/ckeditor/ckeditor.js

If the issue is caused by the message "The version of CKEditor could not be detected." at admin/config/content/wysiwyg.

This solution helped me yesterday:

Open "\sites\all\libraries\ckeditor\ckeditor.js" file in a text
editor.
Add in the first line of the ckeditor.js file:

// version:'4.4.4',revision:'4391'

and save it.

You can get more help about this module on the documentation page.


Creating new Invite Type When trying to create new invite type from admin/structure/invite-types/add I get this response:

  Sorry no Invitation Type modules available in the system.

I has been researching and there is no info referral to this. And I can not create that invitation type from anywhere, also there is no info to do it programmatically.
I get lost into code module but this is the line that returns that message.

It is required Invite by e-mail module, it provides an Invite Type.


Drupal Behaviors uncaught reference error I'm using Drupal 8.

What I'm trying to do is:

Access the active node
From the node get the value of field_test and assign it to a variable
Pass the variable to the drupalSettings function and subsequently to a custom module 'mycustommodule' that triggers an alert

In my content type, I created a field_test field, which is the field I reference in my code. The block is placed on a page of this content type.

This is the JavaScript code I am using.

mycustomblock.libraries.yml

custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

custom.js

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.mycustomblock = {
    attach: function (context, settings) {
      var testMe = drupalSettings.mycustomblock.test;
      alert(testMe);

  }
};
})(jQuery, Drupal, drupalSettings);

The error I get from the JavaScript console is this.

The error message is referring to this line.

Why is the instance of Drupal in the closing parenthesis throwing this error?

You will have to add the core library core/drupal to your library dependencies. This assures, that the Drupal core JavaScript is loaded before your custom module's JavaScript will be executed.

So your mycustomblock.libraries.yml should look like:

custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings


Commerce minimum quantity and purchase multiplier I have added a field to content type Product with the purchase quantity (default 1). Products can only be purchased by this quantity. For example, if its value is 5, you could buy 5, 10, 15, and so on. This is configured by products, and some products could have a value of 1, and others could have a value greater than 1.
After read some post about "quantities" and "minimum quantity", I haven't found how to do it. I have tried with some modules like Commerce Extras, and Commerce Add to Cart Extras. But without success.
Could some one give me some ideas how to do it?
Thanks in advance.

Ryan's answer on this question is the approach you'd want to take:

Install Commerce Custom Product.
Create a new line item type that has new quantity select field and widget. Expose this to the add to cart form.
Hide the regular quantity selection to the add to cart form.
Use a rule to take the value in the field you created in step 2 and set the quantity field to that value on the line item.


Custom Search Page Filtered by Content Type Is it possible to have custom search pages that filter based on content type? I attempted adding a hidden input to the search form like so:

<form class="search-block-form" data-drupal-selector="search-block-form-7" action="/search/node" method="get" id="search-block-form--7" accept-charset="UTF-8" data-drupal-form-fields="edit-keys--7">

<input title="Enter the terms you wish to search for." data-drupal-selector="edit-keys" type="search" id="edit-keys--7" name="keys" value="" size="15" maxlength="128" class="form-search">

<input data-drupal-selector="edit-submit" type="submit" id="edit-submit--8" value="Search" class="button js-form-submit form-submit">

<input type="hidden" name="type" value="blogpost">

</form>

But the search results page ignores the 'type' variable in the GET request and displays all results instead of just the results of the content type I want. I also noticed that you can create multiple custom search pages in the configuration page, but there doesn't seem to be any options for filtering by content type.
Is there anyway to have a search page that filters based on content type? Preferably without creating a view page.

You can use "custom search" module for filter search by a particular content type


What's the correct way to pass variables to the JavaScript of a custom CKEditor plugin? I saw that we can pass values to our JavaScript using drupalSettings. However, this is for Drupal custom module JavaScript files. Since a CKEditor plugin file is already attached/loaded in a different way, I am wondering what's the correct way to pass variables to it.

The following is the code that I made, according to the example, but I have the feeling that plugin.js is loaded two times:

one time in inline_comment_preprocess_html()
and one more time with inline_comment/src/Plugin/CKEditorPlugin/InlineComment.php

What's the correct way to pass variables to plugin.js?

inline_comment.info.yml

name: CKEditor Inline Comment
type: module
description: "Adds the Inline Comment plugin to CKEditor."
package: CKEditor

dependencies:
  - ckeditor
  - core/jquery
  - core/drupalSettings

version: '8.x-1.0'
core: '8.x'
project: 'inline_comment'

inline_comment.module

function inline_comment_preprocess_html(&$variables) {
  $lotus_height = '300px';
  $variables['#attached']['library'][] = 'js/plugins/inline_comment/plugin.js'; // I think I shouldn't try to load plugin.js two times
  $variables['#attached']['drupalSettings']['lotus']['lotusJS']['lotus_height'] = $lotus_height;

}

js/plugins/inline_comment/plugin.js

CKEDITOR.plugins.add('inline_comment', {
    //...
});

(function ($, Drupal, drupalSettings) {
    Drupal.behaviors.LotusBehavior = {
        attach: function (context, settings) {
            var lotusHeight = drupalSettings.lotus.lotusJS.lotus_height;
            console.log('lotusHeight' + lotusHeight);
        }
    };
})(jQuery, Drupal, drupalSettings);

I noticed if I remove the line with $variables['#attached']['library'][] and I dump($variables) there is no drupalSettings variable in #attached array.

You can pass options via getConfig option of the class that creates the plugin. See how the module "Color Button" does it:

https://cgit.drupalcode.org/colorbutton/tree/src/Plugin/CKEditorPlugin/ColorButton.php?h=8.x-1.x

This is passed along to the defined plugin when it is loaded up (the one defined in getFile.)

See: https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginBase.php/class/CKEditorPluginBase/8.6.x

and:

https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginInterface.php/function/CKEditorPluginInterface%3A%3AgetConfig/8.6.x

The variable names passed or modified in getConfig need to be the same names as the ones in the plugin to be overwritten.


Need advice to get an approach to do a personalized searcher? I have a content type called "Flats" which are Flats to sell' each one of them has a 'price' field (ex. 100 000, 150 000, 200 000) and each one has a 'city' field

I need to put a searcher in the home page of the site with 2 selects input, one for 'price range' (with values like 'lower than 100 000', '100 000 to 150 000, ...) and the other for 'city' (with values like: 'Barcelona', 'Madrid', ...)

The searcher should look for flat with prices within the price range and for the chosen city.

A first sight I think I'll need to create an API Form which once submitted should go to a view passing those 2 arguments (price range and city)  in the url as $_GET values.

Is this a right approach to do this?
Can I use $_GET values as arguments in a view?

Is there any module to do this in a easier way? I don't want to reinvent the wheel...

Thanks

Why don't you try a View using exposed filters?  If your content type is made with CCK then you could achieve what you're looking for quite easily.  This video might help you out.  Eric London's Drupal Blog also has something on exposed filters.  I would thoroughly recommend this approach, I've done something very similar to what you're looking for.


Where is menu settings for node types stored in database I looked in all tables to see where Drupal stores menu settings (including which menus should be available to a content type) for node types, but can't find it anywhere. We have a lot of content types on a multi site instance, and we're trying to enable menu for a content type directly in the database.

Thanks!

That data is in a number of different variables in the variable table.

Specifically for menu options, you'll find it in a var named menu_options_CONTENT_TYPE (e.g. menu_options_article for an "article" type). For the menu parent it's menu_parent_article, and so on.

Above assumes Drupal 7, it'll be different for 8.


Theming of User page I want to do theming of default user login page.

Can we create a page  similar like page--node--33.tpl.php.

Customizing and Overriding User Login page, Register, and Password Reset in Drupal 6 and 7

Customizing the user login, register, and password reset pages is fairly simple, and uses the following concepts:

preprocessing to set variables
registration of functions in the theme registry
creation of one or more theme templates.

Step 1.
In the site theme directory, create or edit your template.php file.

Step 2.
The first step is to implement hook_theme for your theme. In the template.php file for your theme, look for a function named yourtheme_theme() and modify it to add these return values. If the function doesn't exist, add the following:

For D6:

<?php
/**
 * Registers overrides for various functions.
 *
 * In this case, overrides three user functions
 */
function yourtheme_theme() {
  return array(
    'user_login' => array(
      'template' => 'user-login',
      'arguments' => array('form' => NULL),
    ),
    'user_register' => array(
      'template' => 'user-register',
      'arguments' => array('form' => NULL),
    ),
    'user_pass' => array(
      'template' => 'user-pass',
      'arguments' => array('form' => NULL),
    ),
  );
}
?>

Notes about that code:

Change the function name by replacing "yourtheme" with the name of your theme
The template can be the same for all three. The example above uses a different template for each case: user-login, user-register, and user-pass
The template names must use a dash, not an underscore
Note: It's user_pass not user_password

For D7:

<?php
function yourtheme_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'yourtheme_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'yourtheme_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'yourtheme_preprocess_user_pass'
    ),
  );
  return $items;
}
?>

Notes about the D7 version:

The 'path' lines tell Drupal where to find the .tpl.php files. This is optional, and in the code above, 'path' tells Drupal to find the files in the templates subdirectory of the theme's base directory.
Note the "_form" added to the user_register element.
Note: As it is the case for D6, it's user_pass not user_password

Step 3.
Now you implement three preprocess functions. There may be more concise ways to code this, but this works very well and is easy to read, so here we go!

For D6:

Notes about that code:

Change the function name by replacing "yourtheme" with the name of your theme
The line $variables['intro_text'] adds the text that follows to the $variables array, which gets passed to the template as $intro_text
The second line renders the form and adds that code to the $variables array, which gets passed to the template as $rendered

For D7:
The code is even simpler for D7 because we don't need to pass a variable containing the form content we want rendered. The variable exists already in the $vars array and can be rendered in the .tpl.php file.

The above preprocess functions simply add a variable into the $vars array that is then displayed in the .tpl.php file. Much more complex manipulation of the content of the render array is possible.

Please note, that the preprocess functions should go into the template.php file.

Step 4.
Create template files to match the 'template' values defined above.

For D6
We need the following template files (make sure to use a dash, not an underscore) :

user-login.tpl.php
user-register.tpl.php
user-pass.tpl.php

For D7
Same as D6, except using user-register-form.tpl.php instead of user-register.tpl.phpfor the register form.

Step 5.
Paste the following into user-login.tpl.php. Modify as necessary for user-register.tpl.php (D6) and user-register-form.tpl.php (D7):

For D6:

For D7:

Note the change to the syntax for causing Drupal to render the form. Also, the D7 sample uses a different class for the div, but that's just a matter of preference.

Step 6.
Save your template.php file to the theme's main directory. Save your .tpl.php files in the same place for the D6 examples, or, in the case of the D7 examples, to the directory you specify in the 'path' element of the $items array.

Step 7.
Rebuild the cache. Go to Administration > Performance and click on "Rebuild Cache" on the bottom of the page.

Now, the user login page will contain the new text from the preprocess function, and the tpl.php file(s) can be modified to suit the site's needs.

reference : Customizing and Overriding User Login page, Register, and Password Reset in Drupal 6 and 7


How to create an Entity reference with taxonomy term selection? I'd like to make an entity reference autocomplete field where I can only select the options which have a certain taxonomy term attached to it.

Example:
I have a sports player who belongs to a certain team. The player is part of content type 'person' with taxonomy term 'player'. Other taxonomy terms which can be applied to this content type are 'referee' and 'trainer'.

I also have content type 'team' where I want to be able to select players for this team. I have used an entity reference field for this which refers to content type 'Person'. But now I can select all persons, so also referees and trainers.

What I did now was create a View with content type=person, term=player and saved this as an entity reference display. I can now select 'Views: filter by an entity reference view' in the reference field in Teams. This all works fine.

The problem however is, I'd like to quickly add a new player if the player isn't in the database yet. I installed the References Dialog module, which adds buttons to an entity reference field to add or edit nodes you're referring to. This module only works when you select the Simple entity reference and not the Views entity reference.

Any solution for my problem?

Here, start with creating a new view and be sure to select taxonomy terms.

In short:
- Add new view
- Select: Show Taxonomy Terms
-> Save & Continue
- Fields: Entity Reference View Widget Checkbox: Taxonomy term
- And ofcourse Taxonomy Term

Go back to your contenttype page and be sure to select the right view with your entity referece field.

Cheers,


How to allow anonymous comments on one content type, but not all I would like anonymous visitors to be able to comment on my 'Blog' content type, but only registered users comment on my 'Forum' content type.

It seems that if anonymous users have permission to comment, this applies to all content types with commenting enabled.

Am I missing a setting somewhere, or would I need to look at hiding/disabling the comment form if content type is 'Forum' and user is anonymous?

Check out the Allow anonymous comments per node type


How can I submit a list of flagged nodes to the admin user? I'm using the Flag module to make a list of items that a user would like more information on. The user flags each node and those are added to a flag list. I would like to allow the user to submit this list to the admin user somehow but have not yet found a way of doing so. I'm using Drupal 7.

Thanks kindly in advance!

I actually think you are trying to make this too complicated based on your feedback. The simplest way in my mind would be to have a view (using current userid as a contextual filter) that displays the items the user has flagged. This opens up a lot of nice possibilities such as being able to remove flags before submitting, sort, filter, table view etc etc. Then quite simply have a button in the view header/footer that "submits/emails" the view url and user id to the admin. The admin can have the same view just with an extra box for userid (or exposed filter or whatever you want).


Form displays without  after page renders everyone!

I'm trying to embed custom form (only file upload item, will attach the code below). But I see only inner stuff like divs and inputs. No form tag at all.

In page callback I use function that calls theme. here's hook_menu() and page callback

    $items['invite/%'] = array(
      'page callback' => 'invite_page_content',
      'page arguments' => array(1),
      'access callback' => 'invite_check_access',
      'access arguments' => array(1),
    );

    $output = array(
      '#theme' => 'invite_view',
      '#type' => 'markup',
      '#content' => array(
        'g_id' => $g_id,
        'g_name' => $g_name,
        'user' => $user,
      ),
    );

    return $output;

In theme file I have call of the form

    $attachment_form = drupal_get_form('invite_attachment_form');
    echo render($attachment_form);

Here's form function

    function invite_attachment_form($form, &$form_state) {
      $form['attachment'] = array(
        '#type' => 'managed_file',
        '#name' => 'upload_attachment',
        '#title' => t('Attach additional file?'),
        '#upload_location' => 'public://email-attachments/',
        '#upload_validators' => array(
          'file_validate_size' => array(2 * 1048576),
          'file_validate_extensions' => array(
            'png gif jpg jpeg mp4 ogg avi mov wmv flv ogv webm txt pdf zip rar',
          ),
        ),
      );

      return $form;
    }

Any help appreciated!

UPDATE

I've found what was the reason for such behavior. There is some script in my site that deletes first form element. So if I add  before my form render - everything will be ok. Need to find what is it.

$attachment_form = drupal_get_form('invite_attachment_form');
echo drupal_render($attachment_form); //That should work

see https://api.drupal.org/api/drupal/includes%21form.inc/function/drupal_get_form/7.x


Bypass customer profile duplication How do you bypass customer profile duplication when editing a profile that has already been referenced on a few orders.

I know it is a design feature to protect historic data as mentioned
here
I am editing the profile trough the ui

Is there a easy way to achieve this without module editing?

Since you've already linked my article on the topic, I'll just answer definitively here that there is no way to do this through the user interface. The code I show in that article is the only way to bypass customer profile duplication, but if you wanted to you could apply it to a user interface in a custom module. Just be careful you don't give administrators more control than is safe for your historical order data.


Do I need to clone a webform? I have created a webform a few days back. Now I want to re-use the webform which I created earlier with other results, so to save my time and energy I just want to clone that webform and reuse for a different purpose.

Note: previous webform has some result. However I do not want to have this result in the exported webform, I only need the form.

Use Webform Share(https://www.drupal.org/project/webform_share) module to export & import

Example usage 1: Prepopulated webforms

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


Display all menu levels I'm trying to output a menu with all of its submenus into a template file, currently I'm using the code below. The problem is that it only displays the top level links. If I pass the second $level parameter into menu_navigation_links it'll then only display that one level, not any of the others above or below.

How can I display all the different menu levels & still have the ability to add classes to the  as below? The title isn't really that important as I can 'hard code' that tag into the template file.

print theme('links__menu_top_page_navigation', array('links' => menu_navigation_links('menu-top-page-navigation'), 'attributes' => array('id' => 'main-menu', 'class' => array('main-menu', 'list-menu')), 'heading' => array('text' => t('Main menu'),'level' => 'h2','class' => array('main-menu-title'))));

The closest thing I've found so far is to use menu_tree_all_data() & menu_tree_all_output() but I cannot see how to edit the  class using that.

I've managed to find an answer in a Stack Overflow answer https://stackoverflow.com/a/30570027/1094862

For completeness I've copied the relevant code below:

$main_menu_tree = menu_tree_all_data('menu-name', null, 3);
render_menu_tree($main_menu_tree);

function render_menu_tree($menu_tree) {
  print '
';
  foreach ($menu_tree as $link) {
    print '
';
    $link_path = '#';
    $link_title = $link['link']['link_title'];
    if($link['link']['link_path']) {
        $link_path = drupal_get_path_alias($link['link']['link_path']);
    }
    print '' . $link_title . '';
    if(count($link['below']) > 0) {
      render_menu_tree($link['below']);
    }
    print '
';
  }
  print '
';
}


Where to find the html.tpl.php $head variable content generation I'm looking for a way to edit the $head variable of the html.tpl.php.
Where exactly is this variable composed and set?

The most common way to add information to the <head> is using  drupal_add_html_head().

If the data you want to alter was added using that function, you can alter it by implementing hook_html_head_alter() within a custom module. Using the alter hook requires that you know the $key of the data that was added during drupal_add_html_head().

If you want to alter CSS or JS, use hook_css_alter() and hook_js_alter() respectively.


How does generateFromLink work? How the generateFromLink method works ? And how to use it in the render array.  What is the difference between this method and the other methods used to generate link ?
$url = new Url('test_route_1');

$link = new Link('Test', $url);

$generated_link = \Drupal::service('link_generator')->generateFromLink($link);

You shouldn't use this service because it is marked as internal and you shouldn't use any other method to generate links in custom code. Generating a link is like early rendering. See https://www.lullabot.com/articles/early-rendering-a-lesson-in-debugging-drupal-8
Instead add the link as render element to the build array.
Like this examples which also demonstrates how you can build nested render elements, here an image as link title:
      $link_title = [
        '#theme' => 'image',
        '#uri' => $image,
        '#alt' => $label,
      ];
      $image_link = [
        '#type' => 'link',
        '#title' => $link_title,
        '#url' => Url::fromUri($link_href),
        '#options' => [
          'attributes' => ['class' => ['feed-image']],
        ],
      ];

      $build[$id]['image'] = $image_link;

Example from /core/modules/aggregator/src/FeedViewBuilder.php


Can't get values from $form in submit handler? Using Drupal 7 and a custom form generated with the Webform module, I'm trying to get info from the submitted form to save in additional SQL tables.

I know my submit handler is being called because putting dpm('This is great news, our submit handler is being called!'); inside the submit handler gives the expected output. So does dpm($myvariable); (after setting a value for $myvariable).

But dpm($form); not only doesn't return anything, but also seems to preven the other dpm() functions from working. There are no errors logged, and the page loads otherwise normally.

I should also mention that if I put the dpm($form) in the hook_form_alter() function instead of the submit handler, it does show up, but all values appear to be default or empty, after the form is submitted.

Please check your submit handler signatures once ... Ideally submit function should be something like below... You can try using drupal set message for same like code given below !

function form_example_tutorial_7_submit($form, &$form_state) {
  drupal_set_message("I am inside submit handler. Printed form values below");
  drupal_set_message("
" . print_r($form_state['values'], 1) . "
");
  // $form_state['values'] is used to extract submitted values !
  drupal_set_message("Printing Form Structure Below !");
  drupal_set_message("
" . print_r($form, 1) . "
");
}


How to add a custom class or id to a menu I have several menus that I want to use, and theme differently. I'm looking into different ways to theme them and it appears that the most elegant way would be to use the template.php file with menu tree. I'm not quite sure how to set different conditions for different menus in this file however.

Menu Attributes is definitely a way to do this.

This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
You should use this module when

You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
You want to give a menu item an ID so you can easily select it using jQuery
You want to add additional classes or styles to a menu item

The module currently allows you to set the following attributes for each menu item:

Id
Name
Target
Rel
Class
Style
Accesskey


How to cancel an order transition if failure is detected in Commerce 2 / State Machine I'm trying to plug into order transitions in order to send my order to a custom fulfillment system.

I have a transition called "send_to_fulfillment", and order states "reviewing" and "sent_to_fulfillment".

I'm hooking into the commerce_order.send_to_fulfillment.pre_transition event. What I can't figure out is how to cancel the transition if the process fails. I can certainly just throw an exception and let the site die, but I'd prefer to be able to elegantly stop the transition and inform the user of the error.

Any tips? I've tried WorkflowTransitionEvent::stopPropagation which didn't do it, and I can't seem to find it documented anywhere.

We don't have a "cancel" or "reverse" feature right now, but it would be worth a feature request in the State Machine queue. The main thing you / we'll need to overcome is what to do in the event a transition in progress has already saved data, triggered 3rd party services, etc. Presumably, there are certain things that should prevent a transition from being reversed (e.g. I've refunded a payment card and therefore must move the order to a canceled or at least unpaid state). However, other things may fall somewhere in the middle ... be allowable and not prevent reversal.

Lisa had a great idea, too, in that you could define the reverse transition explicitly yourself and trigger it in the event that you had a failure condition in your active transition. That would allow you to encode your own logic for checking / reversing transition side effects.


Overwrite an empty field value on node / rendered entity I have a text field in a media image type (for a photo caption) - I'd like to output a default value whenever it's empty.

I tried using HOOK_preprocess_field, but that hook isn't reached if the field of the node is blank.

It's being inserted in a View, but it's more than one field (a display mode of a Rendered Entity showing a photo thumbnail and the caption) and therefore as the photo is present when the caption isn't, I can't use the No results behaviour.

I also tried HOOK_preprocess_node and HOOK_preproces_content_field, neither of those seem to be called at all in the view.

Is there anywhere else I can edit it?

You might consider overriding an appropriate Twig template, something along the lines of {% if content.field_caption %} {{ content.field_caption }} {% else %}} default text {% endif %}


Apply custom date formats to reporting for specific webforms and fields I realize that similar questions have been asked multiple times, but find that either the answers aren't what I am looking for or the specifics of the question aren't the same.

I want to create a custom date format for two different date fields within a specific Webform (not globally). The first date field is the submission date and the second is a date of birth field that we added.

I have created the desired custom date formats in admin/config/regional/date-time/formats let's call them A and B. Then I created custom date types using those formats in admin/config/regional/date-time.

I cannot find where to apply date type "A" to submission dates for the webform and I cannot find where to apply date type "B" to my custom date of birth field within the webform.

Submission Date:

Format A: Y-m-d - H:i
This appears to be an internal field, as it doesn't show up in my list of webform fields. I checked form settings and in advanced form settings as well as in form components.

Date of Birth Date:

Format B: Y-m-d
This is a custom field. When I click "edit" for this field, I don't see where to specify how the date format will be recorded.

Furthermore, it isn't important to me how these dates look when viewed on the survey or on the screen but they need to be recorded so that they are in the downloaded data in the specified format.

It seems that the only way to make this happen was to reset the system's Short Date Format to my custom format A. Thankfully, the webform custom DOB field uses a similar format (the same thing but without the hour and minutes.)

If anyone knows a better way where I could have done this on a "per form" and "per field" basis, please add your answer as the one I am providing now isn't really what I was looking for.


Slideshow browse button doesn't work I'm trying to setup a slideshow on my site using the Slideshow setup that is currently used on D7. I click on the Slideshow option and the following screen shows up. Then, I enter the name, and then I tried to browse the image. Somehow I can't seem to browse for the image (let alone attach it).

Is there a reason why? Is there something that I need to install?

I found out what was wrong. There was a missing JS file. Installed the missing JS file and now it is working.


why "errors validating the config synchronization" when UUID's match? I'm moving a d8 config from dev to stage and I have edited system.site so that the primary UUID on the stage system is identical to the dev system; and yet drush still reports: "There were errors validating the config synchronization."

This is an initial import; so it wants to replace almost all the objects on the stage site with objects from dev which differ only by UUID. There is almost no data (just site name, etc.) This used to work fine under 8.0.0-beta12; but I recently updated to 8.0.0-beta15 (which may or may not be significant). I'm using drush tag 8.0.0-beta14.

# grep uuid configs/from_dev/system.site.yml
uuid: c3b4a4a7-e8ab-44d2-b349-73dc5a8dea63
# drush8 @iron.stage cget system.site | grep uuid
uuid: c3b4a4a7-e8ab-44d2-b349-73dc5a8dea63
#

I checked the whitespace and rebuilt the cache.

# drush8 @iron.stage cim from_dev
 Collection  Config                                                Operation
             system.menu.account                                   create
             block.block.bartik_breadcrumbs                        create
             block.block.bartik_content                            create

       blah.. blah.. blah..

             block.block.bartik_breadcrumbs                        delete
             system.menu.account                                   delete
Import the listed configuration changes? (y/n): y
exception 'Drupal\Core\Config\ConfigImporterException' with message      [error]
'There were errors validating the config synchronization.' in
/usr/local/www/d8_iron_stage/d8/core/lib/Drupal/Core/Config/ConfigImporter.php:730
Stack trace:
#0
/usr/local/www/d8_iron_stage/d8/core/lib/Drupal/Core/Config/ConfigImporter.php(517):
Drupal\Core\Config\ConfigImporter->validate()
#1
/usr/local/www/d8_iron_stage/d8/core/lib/Drupal/Core/Config/ConfigImporter.php(464):
Drupal\Core\Config\ConfigImporter->initialize()
#2 /usr/local/src/drush/commands/core/config.drush.inc(622):
Drupal\Core\Config\ConfigImporter->import()
#3 /usr/local/src/drush/includes/drush.inc(719):
_drush_config_import(Object(Drupal\Core\Config\StorageComparer))
#4 /usr/local/src/drush/includes/drush.inc(705):
drush_call_user_func_array('_drush_config_i...', Array)
#5 /usr/local/src/drush/commands/core/config.drush.inc(600):
drush_op('_drush_config_i...',
Object(Drupal\Core\Config\StorageComparer))
#6 [internal function]: drush_config_import('from_dev')
#7 /usr/local/src/drush/includes/command.inc(359):
call_user_func_array('drush_config_im...', Array)
#8 /usr/local/src/drush/includes/command.inc(210):
_drush_invoke_hooks(Array, Array)
#9 [internal function]: drush_command('from_dev')
#10 /usr/local/src/drush/includes/command.inc(178):
call_user_func_array('drush_command', Array)
#11 /usr/local/src/drush/lib/Drush/Boot/BaseBoot.php(62):
drush_dispatch(Array)
#12 /usr/local/src/drush/drush.php(70):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#13 /usr/local/src/drush/drush.php(11): drush_main()
#14 {main}

If you set the uuid to null into shortcut.set.default.yml it will also works ok.


Programmatically disabling webform component - Drupal 7 According to hook_form_alter doc for webform, I can target the component's properties using $form['submitted']['component_name'], etc. This works fine for altering title, weight, description. The form structure of webform looks something like:

Array
(
  [#tree] => 1
  [component_email] => Array
     (
       [#type] => webform_email
       [#title] => Email
         .
         .
       [#webform_component] => Array
         (
           .
           .
           [extra] => Array
             .
             [disabled] => 0

Simply changing the disabled property to true or 1 doesn't disabled the component. I have also tried the $form['#node']->webform path.

I have never had luck trying to set the disabled flag via a FormsAPI hook using the array indexes.  Looking at the code above, it would also seem that you are setting the incorrect 'disabled' for the form array - #disabled is what is checked during the rendering process.

But, like I said, never had much luck with it anyway.  What you may end up needing to do is set the #attributes array for the form element, specifically identifying the disabled property as in the html element tag:

<input type='text' disabled />
// becomes
$form['element']['#attributes'] = array('disabled' => '1');

obviously with the form indexes specified as needed.


Possible to add form elements via js? Is it possible to add/remove form elements with clientside js? I am using ajax, but it is a bit too slow for the kind of dynamic elements I need.

You can hide and unhide form elements with js. For example you can prepare a popup and deliver it with the main form and then trigger it in js.

You can't generate new elements, because they will be ignored when submitted.

You could build your own form solution with custom js and php code. But this is probably not the best way on the long term.

The best answer to your question, how to build dynamic form solutions, is to investigate, what you can do with a js framework and Rest API.


Adding a "processed" flag to a Drupal Webform, that admins can use to indicate whether or not they've dealt with a particular submission? We're using a Drupal Webform to accept customer requests for a free "kit" that we will mail them.

This works fine on the submission side, but we'd like a simple way to look at the submissions and tell which ones have been fulfilled, and which have not.

So far, I haven't been able to come up with a field that is visible and editable by administrators viewing the results, but not also shown to the customer when they are filling it out.

I realize I could put a checkbox on the form for "fulfilled", and then hide it from the customer with CSS... but I'm hoping there's a better way. Is there?

We have a similar thing where two fields are marked as Private and these are only seen by admins.

We also only allow authenticated users to submit these type of forms.


How to recalculate uploaded files' sizes in KB and update the values in the database? I use a shell command to look for all uploaded JPEG files above 500 K.B. (originals) and do JPEG compression on them. They get smaller in size, but Drupal still shows the originally uploaded file size. How to force a recalculation and update the database accordingly after JPEG optimization?

In Drupal 7 managed files have their filesize property updated upon saving in the file_save() function. So you can just load/save each resized files to have it updated in the DB accordingly.

//@TODO: Get list of $fids corresponding to resized-files
foreach ($fids as $fid) {
  $file = file_load($fid);
  // $file->filesize reflects old size
  file_save($file);
  // $file->filesize now reflects new size
}


Defining a PHP variable using a field Is is possible to define a PHP variable using a field?

eg. In the field a contributor would enter [ABC]

which would translate to: <?php $VARIABLE = '[ABC]'; ?>

which would be repeatedly used in the node as:

<img src="http://www.example.com/<?php echo "$VARIABLE"; ?>/image_01.jpg/>
<img src="http://www.example.com/<?php echo "$VARIABLE"; ?>/image_02.jpg/>

etc

You could create a simple text field to store the string, and then a custom formatter to render it as an image. Then under "Manage display" for the content type, you choose the formatter you just created.

If you don't want to create the custom formatter programmatically, you could use the Custom formatters module.

If you want to use the value of the text field for more than one output element, you could create Display suite custom fields using this value e.g. as a token.


Show or hide custom data set I'm using CIVCRM module in Drupal, and I have created multiple custom data sets for Drupal registration form.

Now problem is that I have 4 membership levels and each level have custom data set so I need to hide other data set and show only those related to selected member level.

Is there a way to do that through administration.

Thanks in advance.

Some forms in CiviCRM (ex: contribution/membership) may have some show/hide options, for, say, organisational memberships, but in general, it's not possible to do it using the admin interface, and doing it programmatically with jQuery is recommended.

Another option, is to use the webform and webform_civicrm Drupal modules to create a custom form. The latest version of webform_civicrm makes it possible to pretty much rewrite most of the contribution/membership forms. Webform has ways to show/hide fields conditionally.

If you want to do it the jQuery way, depending on whether it is a Drupal form (ex: user registration form), or a CiviCRM form (contribution/membership form), you can put the javascript snippet in your Drupal theme, or in a CiviCRM template.

For example, if it's a Drupal form, you can put it in the equivalent of sites/example.org/themes/mytheme/js/custom.js :

/**
 * Show/hide the appropriate custom fields for a membership level.
 */
Drupal.behaviors.myThemeToggleMembershipFields = {
  attach: function (context, settings) {
    $('#my_membership_type_input').change(function() {
      var v = $(this).val();

      if (v == 1) {
        $('..fields for type 1..').show();
        $('.. other fields..').hide();
      }
      else if (v == 2) {
        // etc.
      }
    });
  }
})(jQuery);


Get views contextual filter's argument value in thousand I have a Civicrm set up in Drupal 7. I am showing Civicrm data using two different views.

In one of the view I have set contextual filter to get the contact IDs. From another view I am passing contact IDs as the contextual argument.

Now the issue is, the filter is not working for those IDs which are in thousand. For e.g. 1,223.

Further, when i used the Views php module to pass php value to remove that comma, it is creating Ajax internal server error.

Below is the code, I used in views php field.

<?php echo str_replace(',', '', $row->contact_id); ?>

I have checked below link, but that is also not working in this case

Thousands separator (comma) in term id

Please suggest a solution which will work without any ajax issue.

/**
 * Implements hook_views_data_query_alter().
 *
 * @param $view
 *   Information about Views' tables and fields.
 *
 * @param $query
 *   Information about query used in this views.
 */
function my_module_views_query_alter(&$view, &$query) {
  // Only edit your view whose contextual filter need to be edited.
  if ($view->name == 'your_view_name'){

    // Get your contextual filter field and use your code to strip comma.
    // str_replace(',', '', $row->contact_id);
  }
}


How can I get a list of all available entity view modes? I need to have a list of all available view modes for an entity type so I can use it as the #options in a select field.

Any ideas?
Thanks

I think you are talking about view modes for entities.

$entity_info = entity_get_info('node');
debug(array_keys($entity_info['view modes']));

It would result as

array (
  0 => 'full',
  1 => 'teaser',
  2 => 'rss',
  3 => 'search_index',
  4 => 'search_result',
)


How to import nodes with entity reference field through feeds? At the moment i have 2 content types.
The first (Target Communities) is a kind of category listing. These nodes already exist.

The second (Areas, many more nodes) shall be created from a csv import.

The Areas content type has a entity reference field set to the Target Community content type.

I assumed that i just attach the Target Community titles to the Area in the csv, but after import and node creation, the reference field is still empty.

Then i tried the import with the Target Community node id instead of the title, but this doesn't work eather, the entity refernce field in the created nodes remain empty.

So now, I'm quite clueless about what else to try or what other settings I may have missed.

The feed mapping is correct, all other fields work, including term references etc.

Take a look at this answer:

https://drupal.stackexchange.com/a/22043/4134

At the moment there is a very active thread on d.o about adding this functionality.


Get link for same page in different language I want to display a link to the spanish version of a page in my template, but another module is removing the language option on my link function:

l('Visit this page in Spanish', "node/{$node->nid}", array( 'language'=>'es' ));

I have the general routing set up the way I want; most of the time I want links to target the current language.  Except this time - now I really want that link in spanish : )

How do I force l() to keep the language I specify?  Or should I use another function?

It should work when using this function: https://api.drupal.org/api/drupal/modules!translation!translation.module/function/translation_node_get_translations/7

This will return all the translations of a given nid, when an ES translation is given you can print your l().


How to add two extra buttons in a form to do extra actions with form data I have a simple custom form with 3 submit buttons - one that calls the default hook_form_submit and generates a table. The submit as the rebuild as TRUE:

$form_state['rebuild'] = TRUE;

that shows the complete form with the 3 buttons and the tables.

I need the 2 extra buttons to call different functions but I need inputs from the form itself or the table array.

At the moment, with the code I have, I can't access the form data and also, the tables created by the main submit disappear when I click the 2 extra buttons.

My code:

function MYMOUDLE_form($form, &$form_state) {
    $form['container']['submit'] = array(
        '#type' => 'submit',
        '#value' => t("Submit Form"),
    );

    $form['container']['export_1'] = array(
        '#type' => 'submit',
        '#value' => t("Export - 1"),
        '#submit' => array('MYMOUDLE_export_1'),
    );

    $form['container']['export_2'] = array(
        '#type' => 'submit',
        '#value' => t("Export - 2"),
        '#submit' => array('MYMOUDLE_export_2'),
    );

    return $form;
}

function MYMOUDLE_form_submit($form, &$form_state) {
    # do my stuff - generate tables
}

function MYMOUDLE_export_1($form, $form_values) {
    dpm($form_values);
    $someData1 = MYMODULE_handleFormData1($formValue1, $formValue2, $formValue3);
    drupal_set_message('Action for export 1 was done successfully.');
}

function MYMOUDLE_export_2($form, $form_values) {
    dpm($form_values);
    $someData2 = MYMODULE_handleFormData2($formValue1, $formValue2, $formValue3);
    drupal_set_message('Action for export 2 was done successfully.');
}

Rather than write submit function for each button use $form_state['triggering_element']. This will provide you the which button is clicked with form data in default hook_form_submit


How to allow a client to do specialized styling for a single node? I'm working on converting an existing website to Drupal, and I'm looking for best practices for creating specialized styling on specific nodes. I have a page that looks like this (baconized for your viewing pleasure):

Can someone advise me as to the best way to accomplish styling a node this way - specifically in a way where the content can be managed by the client?

I've had a few different ideas as to how to accomplish it, but I'm not sure which is best.

Write raw HTML as the content and add CSS in the template?
 - The downside with this is that I'd prefer my client not have to mess with raw HTML when managing the content, if at all possible.

Create a custom content type that has fields for each snippet which I can style within the theme?
 - This seems like a reasonable course of action, except that I'll be creating a one-off content type for a single node, and that seems less than optimal.

Do something with Views?
 - Views is always an option, but I don't know if it's the right one here. Would I create a separate node for the intro snippet, the 3 blockquotes, and the rest of the page, or something else? I'm not sure.

Do something with Panels?
 - I'm still figuring out how to use Panels, and it seems like a possibility here, but an overly complicated one. Additionally, how will the client manage it?

Any insight or advice here would be immensely helpful. Thank you!

If it is a page with unique structure and no other pages will have same structure, I usually do this by creating an empty page (not a node, just a page - an item in drupal menu system).

You can create a page in your module like so:

function YOUR_MODULE_menu() {
    $items = array();
    $items['your-page-url'] = array(
        'type' => MENU_NORMAL_ITEM,
        'title' => t('Page title'),
        'page callback' => 'your_callback_function_name',
        'access callback' => TRUE
    );
    return $items;
}

function your_callback_function_name() {
    return '';
}

the code above will provide an empty page. If you need custom page structure for this page you can always declare a template specifically for this page just put:

page--your-page-url.tpl.php

to your theme template folder.

Then you can create blocks for each piece of content and assign them to proper regions. Your users will be able to edit content through blocks edit while all styling and layout tags will be built into template file.


Views 2 - How to show exposed filters when results list is empty? I have a page that displays all events after the current date. It has an exposed filter where you can set the date - all events after that date will be shown. This all works fine.

However, if there are no results on the initial page load (i.e. no events listed that are after the current date) then the exposed filter isn't shown (so you can't set the date to some time in past and view past events).

I found the relevant view theme template and over-rode the If($exposed) conditional but this did not do it - obviously the decision to show filters or not is made before the template but I haver no idea where.

Please could somebody enlighten me?

Thanks

Ok. The ominous non-sound of tumbleweed lol

Well, after a bit of faffing and a >slap forehead< "D'Oh" moment I sorted it.

I added some text in the "Empty text" setting (under "Basic Settings") and the exposed filters now show when there is no result.


How to translate menu items with migrate? I'm importing menu items from CSV using migrate, migrate_tools, migrate_plus and migrate_source_csv.

This is an example of how I'm doing it for the original language:

source:
  plugin: csv
  path: 'private://init/links_gl.csv'
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
  column_names:
    0:
      id: id
    1:
      source_id: source_id
    2:
      parent_id: parent_id
    3:
      menu_name: menu_name
    4:
      weight: weight
    5:
      title: title

  constants:
    path: 'entity:node/'

ids:
  id:
    type: string

process:
  title: title
  menu_name: menu_name
  nid:
    plugin: bbaa_migration_lookup
    migration: init_contents_gl
    source: source_id
  'link/uri':
    plugin: bbaa_concat
    source:
      - constants/path
      - '@nid'
  parent:
    plugin: menu_link_parent
    source:
      - parent_id
      - '@menu_name'
  external:
    plugin: default_value
    default_value: 0
  expanded:
    plugin: default_value
    default_value: 1
  enabled:
    plugin: default_value
    default_value: 1
  langcode:
    plugin: default_value
    default_value: 'gl'
  weight: weight

destination:
  plugin: entity:menu_link_content
  bundle: menu_link_content
  no_stub: true

It's working but now I need to import another CSV file with translated menu items.

I created another migration configuration for the translated language and I tried adding this code:

  id:
    plugin: migration
    source: id
    migration: init_links_gl
  content_translation_source:
    plugin: default_value
    default_value: 'gl'
  langcode:
    plugin: default_value
    default_value: 'es'

destination:
  plugin: entity:menu_link_content
  translations: true
  no_stub: true

But it doesn't work.

How can I translate menu items with migrate?

I don't see anything obviously wrong in your code, but it would have been a better idea to post the 2 full examples (and ideally, you should try first a simple example that can be imported without custom plugins)

Note that for the second YML file (the translation) you don't need to import most of the stuff: you basically need to process the id, the parent, and the title, no need for nid or 'link/uri'.

As the documentation for this is scarce, I'm posting a working example (using JSON, not CSV).

YML for the first migration:

id: menu
label: JSON feed of menu links
migration_group: menu
source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls:
    - modules/custom/migrate_custom/artifacts/menu_en.json
  item_selector: data
  fields:
    -
      name: mlid
      label: 'Unique Id coming from API'
      selector: id
    -
      name: country_migration_id
      label: 'Unique Country Id coming from API. Used to create the relation with the nodes'
      selector: country_migration_id
    -
      name: name
      label: 'Country name'
      selector: name
    -
      name: parent_id
      label: 'Parent menu link id'
      selector: parent
  constants:
    path: 'entity:node/'
  ids:
    mlid:
      type: string
process:
  menu_name:
    plugin: default_value
    default_value: 'main'
  nid:
    plugin: migration_lookup
    migration:
      - country
    source_ids:
      country:
        - country_migration_id
  title:
    plugin: get
    source: name
    language: 'en'
  'link/uri':
    plugin: concat
    source:
      - constants/path
      - '@nid'
  parent:
    plugin: menu_link_parent
    source:
       - parent_id
       - 'main'
  external:
    plugin: default_value
    default_value: 0
  expanded:
    plugin: default_value
    default_value: 0
  enabled:
    plugin: default_value
    default_value: 1
  langcode:
    plugin: default_value
    default_value: 'en'
destination:
  plugin: entity:menu_link_content
  bundle: menu_link_content
  no_stub: true
migration_dependencies:
  required:
    - country
dependencies:
  enforced:
    module:
      - migrate_custom

YML file for translation:

id: menu_ca
label: JSON feed of menu links (Catalan)
migration_group: menu
source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls:
    - modules/custom/migrate_custom/artifacts/menu_ca.json
  item_selector: data
  fields:
    -
      name: mlid
      label: 'Unique Id coming from API. Used to match the original language of the menu links'
      selector: id
    -
      name: name
      label: 'Country name'
      selector: name
    -
      name: parent_id
      label: 'Parent menu link id'
      selector: parent
  ids:
    mlid:
      type: string
process:
  menu_name:
    plugin: default_value
    default_value: 'main'
  id:
    plugin: migration_lookup
    migration:
      - menu
    source_ids:
      menu:
        - mlid
  title:
    plugin: get
    source: name
    language: 'ca'
  parent:
    plugin: menu_link_parent
    source:
       - parent_id
       - 'main'
  external:
    plugin: default_value
    default_value: 0
  expanded:
    plugin: default_value
    default_value: 0
  enabled:
    plugin: default_value
    default_value: 1
  langcode:
    plugin: default_value
    default_value: 'ca'
destination:
  plugin: entity:menu_link_content
  bundle: menu_link_content
  no_stub: true
  translations: true
migration_dependencies:
  required:
    - country
    - menu
dependencies:
  enforced:
    module:
      - migrate_custom

menu_en.json:

{
    "data": [{
        "id": "1_CHE",
        "country_migration_id": "CHE",
        "name": "Switzerland",
        "parent": 0
    }]
}

menu_ca.json:

{
    "data": [{
        "id": "1_CHE",
        "country_migration_id": "CHE",
        "name": "Suïssa",
        "parent": 0
    }]
}


How to overwrite the add content page I created a content type "test", and I want to overwrite the add "test" content page (http://www.example.com/node/add/test); for example, I want to show something on the right part of the page. How can I do it?

the following is i want to do:

i used garland theme as my site's admin theme and my custommed theme company as my site's template. i created a content type named "hello" this content type is used for anonymous to submit content, the page's layout is (header, left, right, footer) some static content and the site navigation locate on the header. the left part is the form which is used by the anonymous to submit content. the right part will be put into some blocks which are generated by the views module. now the default create hello content page for the anonymous is garland theme's create content page. how to change the page shows like the above layout as what i said. thank you.

Maybe implement hook_theme() in your template.php and add an extra template for the test_node_form:

return array('test_node_form' =>
    array('arguments' =>
        array('form' => NULL), 'template' => 'test-node-edit'
    )
);

Now you can write a test-node-edit.tpl.php for the form. But that's only for the form, not the whole page.


How to compare nodes of different types but same fields? Is there any way to compare nodes of different types but with the same fields?

I have 2 content types: Flats to rent and Flats wanted
Both types have the sames fields: rooms and city
In a view I have a list of the Flats wanted and each one has a button: find flats
When you click the find flats button I need to show all the flats to rent that have the same values for: rooms and city  than the clicked flat wanted

I already get it working by creating a View using $_GET variables in the url and arguments.
But I need to use clean urls, then$_GET must go out.

Is there any way to do this in a cleaner way? I need to do it using View because I need to be able to apply bulk operations in the resulting list.

Maybe a module could do this??

Thanks

I would create a custom field handler. This gives you full PHP power about how the link of the "find flats" button will look like.

Writing your own handlers for views maybe looks difficult at the beginning. Once you understand it you will use it a lot. Here I found a how to about how to do that (it's for views 2). You'll find a lot of real world examples in all modules that do support views. Look for code like MYMODULE_views_handlers .


Change formset default from collapsed to exanded? I'm working with the Support Ticketing System module in Drupal 7. My clients would like to be able to see at a glance who is subscribed to notifications on a ticket. The Subscribed field is collapsed by default, meaning the client has to click on the Subscribed link to expand the field to see the users subscribed.

How can I change this so that the field is expanded when the page loads, and save my clients a click?

EDIT: The node is variable--when creating a new support ticket, it will be /node/add/support-ticket. After the ticket has been created, it could be anything.

But the particular fieldset I want to target will always have the id "edit-subscribed".

A simple hook_form_BASE_FORM_ID_alter() invocation can alter the default properties of the form. If you inspect the form array you'll see that the fieldset is stored in $form['subscribe']['subscribed']. By setting the #collapsible element to FALSE, the or #collapsed element to FALSE (if you want to retain collapsibility), the default behavior will be to keep the fieldset open.

For example:

function MYMODULE_form_support_ticket_node_form_alter(&$form, &$form_state, $form_id) {
  // Replace #collapsible with #collapsed to retain collapsibility.
  $form['subscribe']['subscribed']['#collapsible'] = FALSE;
}


Service is being instantiated during installation with unknown entity type call I have a module that defines two services. Service A has service B as dependency.

Service B has some dependencies, one of which is entity type manager.

In the constructor of the service B an entity storage is being called for entity type that is defined by this module as well

public function __construct(AccountProxy $user, EntityTypeManager $entity_manager, QueryFactory $entity_query) {
    $this->user = $user;
    $this->storage = $entity_manager->getStorage('entity_type_name');
    $this->query = $entity_query->get('entity_type_name');
  }

During installation I get error about unknown entity and the installation breaks. I have tried to backtrace the cause of this but so far it looks like everything is in order. The container is only parsing the service definitions and instantiates them when needed. What I think might be the issue is the order in which the entity definitions are processed and service definitions parsed.

I do not want to add any condition into service B constructor to check if installation is in progress. I think this should not be happening.

What would be a proper workaround?

While it will require an additional call when you require it, you could just store a reference to the entity type manager only.

Especially for entity query, you must not do it like this anyway. A query object is not re-usable. You can't execute multiple queries from a single instance.

Additionally, you can simplify your dependencies if you call $storage->getQuery() instead of using the entity query for that (which does the same internally).


Why would an error persist after after uninstalling the module? I created a module for Drupal 8 and when I try to add it to the menu it throws this error

 Uncaught PHP Exception Twig_Error_Runtime: "An exception has been thrown during the rendering of a template ("Route "hello_world.content" does not exist.") in "core/modules/toolbar/templates/menu--toolbar.html.twig" at line 36."

everything fell apart after this.  All of my site was unreachable because of an error page.

I tried removing the module and clearing the cache and the error is still there.  What do I have to do to fix this error?

This is 'normal' as your Twig files are being cached by Drupal. The easiest way to fix the issue is to run $ drush cache-rebuild (with Drush 8 which is the only release compatible with Drupal 8) which will handle all cache rebuild, including Twig cache. Alternatively, under sites/default/files/php you can safely delete the twig directory. If you're not in a multi web server environment, you can delete the php directory altogether, which will both delete the Twig cached files and the Service Container.


Sensible way to rewrite a field for all views in Drupal 8? In Drupal 8 seems one has to create 2 or 3 files plus folder structures to do even the simplest of tasks. So I am trying to figure out how to do a simple hack without all the overhead.

I have a node type for which I attached images. There is a parent node for which I want to display one of the images from the children. I created an Image field for the parent.

So literally, all I need to do is query the database, grab a child's image at random (in every view, each time the parent is viewed, I want the image re-assigned randomly), and rewrite the parent's image field accordingly. This was so easy in Drupal 7...

Does anyone have an idea of how to do this in Drupal 8 in the simplest possible manner, ideally editing just one file?

Thanks!

You can use hooks the same way as in Drupal 7, if you want to change the content of the node before rendering, you can put a hook in your module or theme:

module/theme_preprocess(&$variables, $hook) {
   if ($hook == 'node') {
      ...

check if you are in the right node and change it.

The simplest solution for your problem would be to put all children images in the node display and then hide the images you don't want:

hide($variables['content']['field_image_?']);

So you don't need to lookup the children image yourself.


In a managed_file upload field, how do I prevent an overflow with long file names? I have a form using the field type of managed_upload. Things are working fine accept when the file name is long.

Given the snippet of code, below. Might there be a way to override CSS or inject any CSS to keep the fieldset or this span from overrunning the sidebar_second region?

  $form['file_fs'] = array(
    '#type' => 'fieldset',
    '#title' => t('Files'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );

  $form['file_fs']['file'] = [
    '#title' => t('Documents'),
    '#type' => 'managed_file', ,
    '#upload_location' => 'private://',

  ];

I would suggest adding a class to the fieldset and adding a class to the css file of your theme.

Add something like this to the fieldset.

'#attributes' => array('class' => array('my-fieldset'));

And then something like this to your css file

.my-fieldset {max-width: 100%;}


Add content to a render array in a content type from my custom module I created a content type that is used to display a list of videos hosted on brightcove. I have a module that is setting a cookie for the anonymous user when they watch one. My end goal is to display a viewed/unviewed icon for the user on the list.

I have all the data I need in the cookie. I just need to create a module that reads the cookie data and edits the render array for the content type. The issue is I am not sure how to add new values to that content type's render array. Is there a hook I can use to get access to the specific content type to add a key/value for viewed/unviewed? This is for drupal 7.

Thanks for the help.

hook_node_view() was made for exactly that:

  Act on a node that is being assembled before rendering.

e.g.

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'my_type' && $view_mode == 'full') {
    if (in_array($node->nid, $_SESSION['viewed_videos'])) {
      $node->content['viewed'] = array(
        '#markup' => t('You have viewed this video'),
        '#weight' => 10,
      );
    }
  }
}


Drop-down menu that shows the average of multiple rating criteria on Fivestar I am working on customizing the Fivestar module, to allow the rating of multiple criteria.

The Fivestar rating should show a drop-down menu, in which the user could rate the object on 4 different criteria. The resulting rating should be the average value of those four criteria.

Can anyone point me in the right direction on where to start on this?

edit: i am running drupal 6

This problem has been solved: I wrote the code to paste in the template, and added a module to sort by votes.

See Dropdown menu that shows average of multiple rating criteria.


customize shopping cart I'm just looking for a module in drupal to make a shopping cart customizable. I mean that there will be no products, I just need that people put the amount of money they need to pay and just click proceed to checkout and goes directly to the payment gateway with the amount written. I've been looking to Commerce and Ubercart but I couldn't figure out if there is this option.
Can you help?

It looks like you need Donation functionality, may entitled as something else.

Following modules might help you.

https://www.drupal.org/project/commerce_donate
https://www.drupal.org/project/paypal_donations
https://www.drupal.org/project/donate

Or a custom form which interacts with https://www.drupal.org/project/pay


How to show link upload option on statuses updates form which converts to embedded content? I am using Statuses (Social Microblog) module to allow users to post status updates like other social networks. To enable users to upload photos and videos, there is a module called Facebook-style Micropublisher, which allows users to upload links, photos, videos and documents. The problem with this is that all photos and videos will be saved on my server and for a community site, it is an expensive thing.

To counter that, I installed the great oEmbed module. When the oEmbed input filter is turned on in any of the text formats, It allows users to share a url of the video or photo and it embeds it into the statuses update a user shares. The oEmbed filter is working perfectly, but when a user shares a url of a video or photo with text before or after the url, the content is not embedded and it simply shows a link in the status update.

Now there are few ideas I have in my mind, but I do not know whether those ideas are possible or not. I guess it's a challenge.

Here are the ideas:

IDEA 1. The Facebook style micro publisher (fbsmp) module allows to attach a link with the status update. It is designed to work as I want, it is not working as it should. If you install and see this module, i think you will get the idea of how it works.

I have read some where that the statuses module's api is flexible and customizations can be done. I am using the dev version of the statuses and flag 2.

Important note: It is not necessary that the answer is restricted to my ideas. Anything which solves my problem will do.

So do you want it to act like Facebook aka pulling in content from the link automadgicly?
If so then I did have some success with a alter / Ajax callback and then file read contents and pulling in an image tag at appropriate size was not the best solution but look in to https://stackoverflow.com/questions/6476212/save-image-from-url-with-curl-php

And file_get_contents()


db_affected_rows in Drupal 7 for db_query I just noticed that @Berdir was so nice to remove db_affected_rows from Drupal 7. I'm now wondering what the best practice is now to detect if the query you ran changed anything in the database.

A typical usecase would be to.

db_query(...);
if (!db_affected_rows()) {
  db_query(...);
}

I took a look at the query object returned from db_query, but it didn't seem like much help.

Update:
I see I was a bit unclear as to what circumstances I needed the info.

My current use case, is a quite simple one. I have a table for a node type with a nid column and some data columns. I have a form an upon submitting the form, I want to either insert or update the row in the db.

The problem with db_update/db_insert is that, if I use update first, and insert if update returns 0, I wont catch the condition, where the form was submitted with the value in the db. If I use db_insert first, that will raise en error if there already is a row in the db.

I suppose I in this specific condition could insert a blank value when the node is created and then only use update, but for some cases that might not be possible, if I needed to store info that was keyed to an external database. I would also like to avoid having to depend on database values for my code to function.

My usual strategy for such cases, has been to do a

db_query("INSERT IGNORE INTO ...")
if (!db_affected_rows()) {
  db_query("UPDATE ...");
}

Doing this is both simple and error free no matter what condition the db is in. The best option I can see right now, would be to handle it with SQL and do this:

db_query("INSERT ... ON DUPLICATE KEY UPDATE");

But I was hoping that the db API would be able to handle this.

That information is directly returned by the execute() method of Delete/UpdateQuery, see for example: UpdateQuery::execute().

<?php
$affected = db_update('some_table')
  ->fields(array(
    'some_field' => $value,
  ))
  ->condition('another_field', $id)
  ->execute();
?>

And InsertQuery::execute() returns the last insert id.


Can I force cron to process all of my queued tasks? My D7 module uses hook_cron to mirror a big external datasource locally. For each new or updated row, $queue->createItem() schedules a task requiring several external API round trips to build the locally mirrored row.

I might queue 750 tasks but Drupal only runs 50 on a cron. How do I make all queued tasks run on each cron?

Please note:

There are no errors reported in /var/log/apache2/error.log
The latest message in admin/reports/dblog reports "Cron run completed." (looks successful)

Basically PHP has memory and execution time limitations, so if you try to do a huge import of an external database you'll run out of runtime if not memory.

So the solution is to spread it out over many http requests, each doing a smaller chunk of the job.

For this, Drupal has the Batch API, which you can call from cron as needed.

Here's the Examples project's Batch example (with tests!) to guide the way. And a decent explanation with some code samples.


Render a CCK field with only the node object in Drupal 6 If I have a node object and would like to render just a given CCK field, how would I do so? I don't mean on a node template page or in a nodeapi hook, just in general.

My custom CCK field's theme_mymodule_formatter_default function takes an $elements array - when this function is called on the node page, $elements is an array with keys including the following:

#formatter
#node
#field_name
#theme
0
1

...where 0 and 1 point to arrays of values in the multi-valued CCK field.

Now if I want to render this field, and all I have is my formatter function and a node object, how do I format it? If I call theme('mymodule_formatter', $node->field_my_cck_field[0]), what gets passed to the $elements array of my formatter function is an array with only the following keys

0
1

But rather than even having to call the theme() method, I'd like to call something like drupal_render() that will pick the default theme formatter function. I imagine there's a way to do something like this, I just don't know how.

In D6, you can render CCK fields with:

content_format

e.g:

print content_format('field_my_cck_field', $node->field_my_cck_field[0], 'default', $node);

See also content_view_field for an alternative option.

If you're in a node template and the field is set to display, you can also just go:

print $FIELD_NAME_rendered // where $FIELD_NAME is the field name


Drupal Commerce "add to cart" form with complicated attributes I'm creating a Drupal Commerce based solution with 2 product types. One product has a constant price; it will be added to the cart, and that's all. The other product has many attributes (more complicated than color and size), and usually price depends from the selected attributes. Prices for various attributes are set by the administrator users. These prices are then multiplied by various other attributes, and added to the product price. For example:

additional price = some attribute unit price * customer entered width
complete product price = customer entered width * customer entered height * product default price + additional price

First attribute is width and height, which is entered from the customers before adding to the cart; the default value is 1x1.

More complicated attributes contain checkbox. If customers check it, the radio buttons becomes visible (first selected by default with no price; if customers select a different radio, they will enter a custom value). Another complicated attribute is price set individually for taxonomy term. I have colors, and for each color I can set the price for the current product. Thus I can't set price as a field of taxonomy term.

Now I'm trying to accomplish this with the Commerce Option and the Commerce Product Attributes modules.
Is there any simpler way to get the result?

The biggest problem is that the Drupal Commerce module adds to cart products with different attributes as a single product. So administrator Commerce/Order, or even customers viewing the  cart don't really know what was added to cart.
Is there any simple way to distinguish the same product (ID) but with different attributes?

The biggest problem is that the Drupal Commerce module adds to cart
  products with different attributes as a single product.

Have you tried unchecking the option to: "Attempt to combine like products on the same line item in the cart."

It's on the "Add to cart" product reference field formatter settings on the product display content type

e.g: admin/structure/types/manage/product-display/display


Drush unable to find settings.php I have a unique problem, for which I am unable to find the reason and thus not an inch closer to solution since 4 days.

Drush is taking a separate settings.php file instead of the correct one.

Check only the settings files link found on the link marked [2] in both the settings.

So in dev environment, drush takes the following config:

[vagrant@frontier www]$ php ../bin/drush.php core-config
Enter a number to choose which file to edit.
 [0]  :  Cancel
         -- PHP ini files --
 [1]  :  /etc/php.ini
         -- Drupal --
 [2]  :  /var/www/sites/$DRUPAL_ROOT/cnf/settings.php
 [3]  :  /var/www/sites/$DRUPAL_ROOT/www/.htaccess

But on the deployment server, drush takes up the following config:

/var/www/frontier/www
devtools(pabetadfsp01p):php ../bin/drush.php core-config
Enter a number to choose which file to edit.
 [0]  :  Cancel
         -- PHP ini files --
 [1]  :  /etc/php.ini
         -- Drupal --
 [2]  :  /var/www/$DRUPAL_ROOT/www/sites/www/settings.php
 [3]  :  /var/www/$DRUPAL_ROOT/www/.htaccess

Now, I create a symlink at $DRUPAL_ROOT/www/sites/default/settings.php which refers to $DRUPAL_ROOT/cnf/settings.php. So drupal picks up the correct settings while drush doesn't.

I really don't have any idea as to what could cause this mis-configuration. Please let me know any remedy.

Also I don't create a www folder in the sites folder at $DRUPAL_ROOT/www/sites/ which is displayed on drush settings on deployment server.

First off, you should not call drush.php directly; use the drush script instead.

Regarding site selection, Drupal looks up the site to use based on the domain name in the http request, which is passed in via the HTTP headers.  When you are using Drush, there is no web browser involved, so Drush needs to generate equivalent HTTP headers and select the appropriate site based on information that is provided either explicitly (via commandline options) or implicitly (via the current working directory).

If your cwd is inside your Drupal root, then Drush will, by default, look for the settings.php file inside the 'default' folder.  You can change this default by setting your cwd to the folder that contains the settings.php file that you want, or by passing in --uri=mydrupalsite.com as a commandline option (or -l mydrupalsite.com).  You might also want to read up on Drupal site aliases, which are an even more convenient way to tell Drush which Drupal site you'd like to use with your command.


How to change images without removing and re-uploading via GUI back end? I have some images I need to change in batches on the website.

For example, I want to replace all color header images with grayscale images.

What I did was subsitute the old images with the new ones in folder:

C:\patch\sites\default\files\styles\slideshow_1920_x_700_scale\public

Now the problem is that after doing this, even if I restart the computer(using aquia dev desktop), clear all caches ect...

The color images still show up on the website, even if the grayscale ones are in the folder.

The only way to get the grayscale images to show is to go in the content item, remove the image, and reload the identical grayscale one.

Is there a way to batch do this WITHOUT having to manually remove and re-upload?

What if I had to change 1000 images...?

Derivative images (the files that result from using Image Styles) are auto-generated; you need to replace the original image file, then flush the images already created for the style(s) you're interested in, so the derivatives be re-generated next time they're requested.

For the example path you've given, the originals will be in the root of the public file system (/sites/default/files), so just replace those with the new images, and flush the styles that use them.

Probably the easiest way to do the last part is to install the Image style flush module.


Drupal way to edit site variables what's the best way to go about to hacking core variables? I need to edit a few values in Drupal core's common.inc, for instance:

  'name' => 'Generator',
  'content' => 'Drupal ' . $version . ' (http://drupal.org)',

and also in user.pages.inc

$timeout = variable_get('user_password_reset_timeout', 86400);

but if I update drupal core, these values will return. Is there a "Drupal way" of editing these values so that I don't have to do that every time?

Thanks.

You should not edit core code, ever.

For variables (set with variable_set) can try using something like strongarm module, or you can override using $conf in settings.php:

 /**
 * Variable overrides:
 *
 * To override specific entries in the 'variable' table for this site,
 * set them here. You usually don't need to use this feature. This is
 * useful in a configuration file for a vhost or directory, rather than
 * the default settings.php. Any configuration setting from the 'variable'
 * table can be given a new value. Note that any values you provide in
 * these variable overrides will not be modifiable from the Drupal
 * administration interface.
 *
 * The following overrides are examples:
 * - site_name: Defines the site's name.
 * - theme_default: Defines the default theme for this site.
 * - anonymous: Defines the human-readable name of anonymous users.
 * Remove the leading hash signs to enable.
 */
 $conf['site_name'] = 'My Drupal site';
 $conf['theme_default'] = 'garland';
 $conf['anonymous'] = 'Visitor';

This documentation is from default.settings.php.


Add administration menu item for one role only I have a module that has configuration pages in the administration side. I want to have one role that's just for administrating that module, but doesn't have any other administrative privileges.

I can give this role access to the path admin/settings/module/configuration and they see the form, but since they can't see see the administration menu, they can't navigate to it. They have to paste the URL to it.

I would like to have that path show up as a link in their black admin menu bar at the top. But I don't want it to show up for any other admin, just the Module Administrator role, to keep that bar uncluttered. I can get a custom menu item showing up in the admin bar, but how do I get it to redirect to another page, and how to I stop users without the role from seeing it?

I can get a custom menu item showing up in the admin bar, but how do I get it to redirect to another page, and how to I stop users without the role from seeing it?

You can set the page callback to drupal_goto, pass the redirect path and other arguments as page arguments, and use the access arguments to set permissions.

I love admin menu, but I'm not sure it's something I particularly like putting in the hands of the clients. It's easy to find yourself giving too many perms to the client, and you can't use the menu module to add items to it. I've not used it yet, but on my next project I'm going to try something like SimpleMenu.


How to show each type of content-types just one time? I have news content type and it has title, body, image and type. The type is a list(text) and have these values:

sport
Economy
Health
...

And now I need to have these types in a view (block). in view module the field is type (means the news type) I just want each of them shows one time not showing by each published news content.

For example: in that block that I made I have 3 sport news and 2 health news and one Economy!

I hope I understand your question. Do you want to use the Type of the node as header for a collection of nodes?
So:

Sport
Node 1
Node 2
Node 3

Health
Node 4
Node 5

Economy
Node 6

What I would do is use the Views field view module. First make a view for all three groups, so you have three views one for Sport, one for Health and one of Economy. Give them all a header with the Type name. Then add all these views to one view with this module.


Sort a view by country - according to the translated countries I have a view displaying some nodes of a content type. Each node has a location assigned (with the location module).

I want to group and sort the results by countries. The grouping works fine, and the sorting is almost fine too.

It does sort by country, but it does it using the english countries' names.

However, my website is in french, so I want it to sort using the french countries' names.

Most of the countries are fine, but some are not the same. For example: South Korea is Corée du Sud in french, so it's not the same order.

Views uses the english name to sort, I want it to use the current language (here french, but it's a multilingual website, so also english when it is).

Your problem is that views uses SQL to sort, since that is a lot easier and faster and it otherwise would be required to load all the records and sort them with PHP, before selecting which to show, which is a massive resources waste if you have a lot of records and use paging.

A simple solution to this problem, is to create a work around. Since the country names is stored in english, you can create a field that you hide from the user where you store the French country name. You can then in your view use this field when sorting. You would need to write a bit of code - in a custom module you create - to hide the field in the UI and automatically set the correct value based on the country the user selected in the interface. This can all be done with hook_form_alter.


Change default format for date field on user register form I'm new to Drupal 8. In the user registration form, i've added a Date field via manage fields in user account settings. However, I need to customize this field and change its format. I tried 'manage display' but it's not taking effect. Is there something I'm missing. (Ideally, it should look and behave just like field datetime in Drupal 8 webform)

Appreciate any help given.

Thanks

You can implement template_preprocess_field() and alter the markup of the date field.

function MY_THEME_preprocess_field(&$vars) {
  if ($vars['field_name'] === 'field_custom_date_field') {
    $date_format = 'short'; // You need to provide the machine name of the format you want.
    $timestamp = strtotime($vars['element']['#items']->value);
    $markup = \Drupal::service('date.formatter')->format($timestamp, $date_format);
    $vars['items'][0]['content']['#text'] = $markup;
  }
}


Entityform (block) redirect not working The redirect field within entityform doesn't seem to have any effect. I'm using the entityform block module, if it makes any difference.

I have also tried using hook_form_alter to copy to default submit action and hardcode it in, which also doesn't work:

function custom_edit_form_submit(&$form, &$form_state) {
   $form['actions']['submit']['#submit'][0] = 'custom_edit_form_submit';
}

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

$entityform = entity_ui_controller('entityform')->entityFormSubmitBuildEntity($form, $form_state);
  // Add in created and changed times. This must be added before preview to get time.
 if ($entityform->is_new = isset($entityform->is_new) ? $entityform->is_new : 0) {
global $user;
$entityform->created = time();

$entityform->uid = !empty($user->uid) ? $user->uid : 0;
}

$entityform->changed = time();
$entityform->draft = $form_state['clicked_button']['#entityform_draft'];
// Save the entityform and go back to the list of entityforms.
$entityform_type = entityform_type_load($entityform->type);
if (!empty($form_state['clicked_button']['#entityform_change'])) {
$form_state['entityform_preview_entity'] = $entityform;
$form_state['rebuild'] = TRUE;
drupal_set_message(t('Re-enter'));
return;
 }
else {
// If this entityform type has preview mode and we are in submit store preview.
if (empty($form_state['clicked_button']['#entityform_after_review'])
     && !$entityform->draft
     && !empty($entityform_type->data['preview_page'])
     && $form_state['entityform_form_mode'] == 'submit') {
  $form_state['entityform_preview_entity'] = $entityform;
  $form_state['rebuild'] = TRUE;
  return;
}
}

$entityform->save();
if ($form_state['entityform_form_mode'] == 'submit' || !user_access('edit any entityform')) {
if (empty($entityform->draft)) {
  $redirect_path = $entityform_type->get_path_property('redirect_path', $entityform);

  if (!empty($redirect_path)) {

    $form_state['redirect'] = 'my/path/here';
    // print_r($form_state); die(); This fires which shows that the function is being called
  }
  else {
    global $user;
    if (empty($user->uid)) {
      // For anonymous users we must store the id of their submission in the session.
      drupal_session_start();
      $_SESSION['entityform_submission'] = $entityform->entityform_id;
    }
    $confirm_path = entity_ui_controller('entityform')->confirm_path($entityform->type, $entityform->entityform_id);
    $form_state['redirect'] = array($confirm_path[0], $confirm_path[1]);
   }

  drupal_set_message($entityform_type->get_prop('submit_confirm_msg', $entityform));
  }
  else {
  // Saving a Draft.
  $form_state['redirect'] = $entityform_type->get_path_property('draft_redirect_path', $entityform);
  if (empty($form_state['redirect'])) {
    // Redirect to standard draft page.
    drupal_set_message(t('Your draft submission has been saved.'));
    $form_state['redirect'] = entity_ui_controller('entityform')->draft_path($entityform->type);
  }
  else {
    // Redirecting away from standard draft page. Show text as message.
    drupal_set_message($entityform_type->get_prop('draft_save_text', $entityform));
  }
}
}
else {
$info = entity_get_info('entityform_type');
$form_state['redirect'] = $info['admin ui']['path'] . "/manage/{$entityform_type->type}/submissions";
drupal_set_message($entityform_type->get_prop('submit_confirm_msg', $entityform));
}
}

In addition to this code, you must use this code.

function custom_edit_form_submit(&$form, &$form_state) {
   $form['actions']['submit']['#submit'][] = 'custom_edit_form_submit';
}

whenever a submit is to be altered, we need not to override the index of default submit functionality instead we create a new one to perform a functionality on submit.

I hope, it will work for you!


How anonymous users are able to complete survey, even when webform is set only for registered users I have used Webform module for gathering user data before accessing the content.
Only authenticated users can access the webform, but in the webform submission reports there are some user names with name as anonymous who submitted the webform.

Admin menu --> webform --> Choose one of your webform and click component--> form setting

Under SUBMISSION ACCESS untick anonymous user.


can't save search box configuration under themes>config I made a custom theme based on Zen. In my custom theme (and under stock Zen theme as well) there is a problem with enabling my search form. When I tick the checkbox that says "search" box under admin>theme>customtheme>config>Toggle Box and click save, the page refreshes and I notice that the checkbox at "search box" is unticked again. Obviously this results in me not being able to show the search form.

Here's the code from my page.tpl.php file.

<?php if ($search_box || $primary_links || $secondary_links || $navbar): ?>

        <?php if ($search_box): ?>

              <?php print $search_box; ?>

        <?php endif; ?>

I had the same problem - answer: Search module is not enabled by default! So

go to admin/build/modules, scroll down to 'Search' and tick the checkbox.
Then go to admin/user/permissions, scroll down to 'Search module' and set permissions for Anonymous and authenticated user (and any other type of users you might have configured and want to give this permission to).
Finally, go over to admin/build/themes/settings/[your-theme-name] where you will find that the 'Search box' checkbox is now tickable.

You should now see the search box - if you don't , flush caches!


Random::string deprecated? I'm using Random class to generate a password for a new user in my custom module.

I added the namespace in my module controller: use \Drupal\Component\Utility\Random;
And I am using it like this:

$user = User::create();
$user->setPassword(Random::string());

Problem is this function seems to be deprecated, however I found it in the Drupal API documentation.
Here is the error I get:

  Deprecated function: Non-static method Drupal\Component\Utility\Random::string()

Did I use it wrong or do you know a better way to generate a random string ?

Drupal version: 8.4

Random::string isn't a static function, so you can't call it statically.

Well, you can (PHP is, erm, interesting like that), but it will throw a fatal error in future versions of the language, hence the warning now. To clarify, you're not being warned that Random::string itself is deprecated, just the method you're using to invoke it.

Get an instance instead and use that:

$random = new \Drupal\Component\Utility\Random();
$string = $random->string();


Customise message notifications in Drupal 7 I'm using organic groups with Drupal 7 and members receive email notifications when new content is posted to their group.

However I can't find a way to modify:

Email subject: New post in group
Email message: Hello [user], There is a new post called...

Which template or database entry do I need to modify?

OG7 Uses the Rule module for sending email notifications. See admin/config/workflow/rules/reaction/manage/rules_og_group_content_notification


cache_clear_all() doesn't seem to work I have a block with a few CCK fields. In this block I have a link to an action that changes the value of the fields in that block.

The code is the following:

db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=%d", $nid);
cache_clear_all();

After reloading, the old value still appear. I have to manually clear the cache to see the current value.

Check which cache is relevant (e.g. cache_content, cache_views_data) for this content and clear this cache explicitly. If you call cache_clear_all() without parameters you "only" clear the page and block cache. Take a look at the code of cache_clear_all() to see the details.


How do I cache my custom entities using entity api with entitycache? I have implemented custom entites, extending on Entity API. This is essentially identical to what the Model module does with a few extra customisations (fields, solr/facet integration etc).

I want to cache my custom entities using the Entity Cache module to get fast loading of entities when using Views and Apachesolr along with automatic cache updating when my entities are updated.

What do I have to do to implement this?

You can achieve this quite easily with a few hooks and additions to your existing hooks.

Define the cache table in your hook_schema() implementation in your module's .install file:

// Optional cache table for entitycache support.
$schema['cache_entity_my_entity'] = drupal_get_schema_unprocessed('system', 'cache');
$schema['cache_entity_my_entity']['description'] = 'Cache table used to store my_entity entity records.';

This adds a db table that can be used to store your cached entities.

Add an update hook to create the table:

function my_entity_update_700X() {
  if (!db_table_exists('cache_entity_my_entity')) {
    $schema = drupal_get_schema_unprocessed('system', 'cache');
    $schema['description'] = 'Cache table used to store my_entity entity records.';
    db_create_table('cache_entity_my_entity', $schema);
  }
}

Enable entitycache in hook_entity_info(). Add this near the bottom before return $info;

if (module_exists('entitycache')) {
  $info['my_entity']['field cache'] = FALSE;
  $info['my_entity']['entity cache'] = TRUE;
}

Implement hook_flush_caches() in your .module file:

/**
 * Implements hook_flush_caches().
 */
function my_entity_flush_caches() {
  return array('cache_entity_my_entity');
}

And that's it! Entity API takes care of the interactions and things like load() and resetCache() (I found you have to implement those functions when adding entitycache functionality to non-entityapi entities)


colorbox content wrong size I created a page in Drupal 7 using two pictures and would like to display them with color box. The link: http://quaaoutlodge.com/content/salmon-run now two problems: There for some reasons seem to be 4 pictures in the group, two of which are totally out of size and get stretched to 650 x 800 px but I just want them to show in their original size. How can I get rid of the stretched ones?

In ur html rel="gallery-all" is available which means you allow to load all the images in the galery or page, for resolving your issue (for single load) remove this rel attribute.

The rel attribute specifies the relationship between the current document and the linked document.In colorbox "gallery-all" means it will load all images to colorbox. For eg here load 4 images, perhaps select "single" load the main image


Adding token in the views header and footer I have created webform and displaying the webform submission data using views. In above the submission data, I mean in the header, I want to display the data from the webform body field. I tried using adding the "Global: Unfiltered text" and placing the token of the body field. But when I view the page, it is not showing the body content instead of showing the token itself.

Please tell me how to use token of the webform body field in the header without using "Global: PHP"?

The "Use replacement tokens from the first row" checkbox is essential. It works with either the "Global: Text Area" option or "Global: Unfiltered text." Here is a screenshot of both working: