Automatically downloading libraries for a module I have a small module on drupal.org.  Among a few other things, my module adds support for a third-party PHP library to Drupal.  Users are expected to download the module to .../libraries/ and the module provides helper functions, etc.

A few days ago I had a feature request come in.  Essentially, a user is asking for a way to automagically download the PHP library to .../libraries/ for use by the module.

Before I stamp this request as denied, I was curious whether there is a decent method to do this, and if there are any existing modules that already to this (so I can look at them for inspiration).

You can use drush make to do this, but that will only work if the person downloading the module is using drush make.

In your modulename.make file:

libraries[foolib][download][type] = "get"
libraries[foolib][download][url] = "http://path.to/file/or/tarball.gz

This is only advisable if you are grabbing libraries. Adding dependent modules here currently can cause version conflicts (although many modules supply this info via a modulename.make.example file).


Ajax %-wildcard URL giving 404 error when setting a parameter I have a page with a dropdown. When you click on that dropdown that content is loaded by Ajax. I would like to do the same for the Breadcrumb, so I created an Ajax-URL in my module:

function selectexamfeature_menu() {
  $items = array();
  $items['selectexamfeature/ajax-replace-breadcrumb/%'] = array(
      'title' => 'Ajax-Callback for replacing breadcrumb',
      'page callback' => 'selectexamfeature_ajax_callback',
      'page arguments' => array(2),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK,
  );
  return $items;
}

function selectexamfeature_ajax_callback($url){
  $commands = array();
    // later on the $url will be used here for generating the breadcrumb html
  $ret = $url;
  $commands[] = ajax_command_html('.page-breadcrumb', $ret);
  $page = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($page);
}

and in my Javascript code I have:

  var custom_settings = {};
  custom_settings.url = '/selectexamfeature/ajax-replace-breadcrumb/SOMELINKASSTRING';
  custom_settings.keypress = false;
  custom_settings.prevent = false;
  Drupal.ajax['custom_ajax_action'] = new Drupal.ajax(null, $(document.body), custom_settings);

  Drupal.behaviors.selectexamfeature_ajax_replace_breadcrumb = {
    attach: function (context, settings) {
      $( "#edit-field-text-grade-tid" ).change(function() {
        // the event...
      });
    }
  };

So at the end I want to get the SOMELINKASSTRING in my $ret variable. But for now I just get a 404 error all the time:

  An AJAX HTTP error occurred.
  HTTP response code: 404
  Debugg information follows: /selectexamfeature/ajax-replace-breadcrumb/SOMELINKASSTRING Statustext: Not Found...

I believe the issue is in the wildcard section. Somehow it does not replace it correctly.

If I leave the % away and also the SOMELINKASSTRING it works without issues. But I for sure need the parameter to know which page is requested.

Also watch this awesome article but it did not help either.

If the form is part of a standard Drupal form, you can use Drupal's built in AJAX system. There is a detailed explanation here: Ajax Forms in Drupal 7. Basically it should look like this.

function hook_some_form($form, &$form_state) {
  // Create a frop down
  $form['some_select'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => $default,
    '#ajax' => array(
      'callback' => 'some_ajax_callback', // This is the php function to be called
      'wrapper' => 'some_wrapper', // The javascript #id to put content in.
      'method' => 'replace', // Content placement option
    ),
  );

  // Result contents container
  $form['some_wrapper'] = array(
    '#type' => 'item',
    '#id' => 'some_wrapper',
    '#tree' => TRUE,
  );
}

And for the PHP callback

function some_ajax_callback($form, $form_state) {
  // Fetch the value AJAX gave us.
  $value = $form_state['values']['some_select'];

  // Recreate the wrapper as we overwrite the old one.
  $form['some_wrapper'] = array(
    '#type' => 'item',
    '#id' => 'some_wrapper',
    '#tree' => TRUE,
  );

  // Append the value of the drop down to it.
  $form['some_wrapper']['value'] = array(
    '#type' => 'item',
    '#markup' => check_plain($value);
  );
  // Return everything to Javascript.
  return $form['some_wrapper']
}

This allows you to pass form values to PHP for processing.


How to change an image field to a certain fid programatically? Specifically, every time a comment is saved, I'd like to programatically change a comment field 'Picture' to an image field from the user who wrote the comment. I have the following custom module:

function MYMODULE_comment_presave($comment) {
    $user = user_load($comment->uid);
    $uid = $user->uid;

    $comment->field_picture['und'][0]['fid'] = $user->field_picture['und'][0]['fid'];
}

This doesn't work correctly, because the field_picture_alt, field_picture_width, field_picture_title and field_picture_height columns in my database don't get a value (they're NULL).

I've also tried

function MYMODULE_comment_presave($comment) {
    $user = user_load($comment->uid);
    $uid = $user->uid;

    $comment->field_picture['und'][0]['fid'] = $user->field_picture['und'][0]['fid'];
    $comment->field_picture['und'][0]['width'] = $user->field_picture['und'][0]['width'];
    $comment->field_picture['und'][0]['height'] = $user->field_picture['und'][0]['height'];
    $comment->field_picture['und'][0]['alt'] = $user->field_picture['und'][0]['alt'];
    $comment->field_picture['und'][0]['title'] = $user->field_picture['und'][0]['title'];
}

and that works perfectly.

However, I was wondering whether I always have to set the 'alt', 'title', 'width' and 'height' values manually as above.

Is there another faster way to inherit these caracteristics from the referred image? Can I for example inherit the 'height' and 'width' from an image style?

You can do this in the comment tpl file. Add something like this:

$img_array = array(
    'style_name' => 'thumbnail',
    'path' => $user->field_picture['und'][0]['uri'],
    'width' => '',
    'height' => '',
    'alt' => $user->field_picture['und'][0]['alt'],
    'title' => $user->field_picture['und'][0]['title'],
  );

$img = theme('image_style', $img_array);

You can then add <?php print $img; ?> where you want the image to appear.


Geofield Map - Filter attachment result by clicking marker I'm facing a problem with geofield map and I can't find a solution. So I have a view with a geofield map format. There I show all nodes from one node type as markers.
Under my map I have an attachment also with all nodes, but as a list with more details.

Now the problem: I want to filter the attachment when I click on a marker from the map. For example - I have 10 markers on my map. These 10 markers represent 10 nodes which are also shown in the attachment beneath. When I click on one marker on the map I want the attachment to show only one node in the results. It would also be great if the result would be updated via ajax.

I hope somebody can help me. :)

So You have 2 views on the Page
1 view is the Map
and another view is the "attachment"

You need to look in to how to use Contextual filters look at the Url Arguments in A view (see https://www.youtube.com/watch?v=aVwclF9TfBo | and https://www.youtube.com/watch?v=zbdQghFj0lU)

A Very Quick Way to get this done is, in your Map View
add 2 new fields Content id and a Global: Custom text field
then in your new custom field view add

 Quick View

where /map is the path to your map page,

Then open your Map FORMAT Settings and scroll until you see

"MAP MARKER AND INFOWINDOW"
in Marker Infowindow Content from select your new field

Then save the map view.

Open Your "attachment" view and add a CONTEXTUAL FILTERS

selecting "ID" in the Content Category.

config like

tick Provide default value

Type = Query parameter

Query parameter = show

this will give you

this is not 100% exactly what you want but then you can start to add a  custom js file to target the marker click event and auto trigger the window link - good luck !


Search results replace & with & When, for example, I search for Eat & Drink, the search results show &amp; instead of &.

Is there any way to avoid this?

Got it! Used the below code and everything works fine.

filter_var($snippet, FILTER_SANITIZE_STRING);


AJAX Views with filter as path component I have a view of Commerce products of type Print. The product type Print has a reference on a Taxonomy called Category. I setup the Category field as an exposed filter (dropdown) for my View page. The View uses AJAX and the URL is /prints.
If I want to load my View with a preselected category, I can go to http://d8.local/prints?category=1 which displays the View already filtered and with the corresponding category selected in the dropdown.
I could setup a contextual filter and a relationship on the View and set the path to prints/% so that I could filter and access it as http://d8.local/prints/landscapes where landscapes is one of the vocabulary terms, which feels better than ?category=1.
When I do so however, going to http://d8.local/prints/landscapes then using the exposed filter, it will filter the already filtered results. Also going to /landscapes doesn't select the option in the dropdown.
Is there a way to combine the 2 functionalities?
Edit:
To summarize the functionalities I am after:

I should be able to filter the products by category by adding the vocabulary term name as a path component, ie. /prints/landscapes.

When accessing the View with the category as the path component, the appropriate category exposed filter dropdown option should be selected, ie. Landscapes should be selected in the dropdown if accessing /prints/landscapes.

I should be able to filter the View using AJAX when manually selecting another category from the exposed filter dropdown.

The main page title must be updated based on the category whichever way the view was loaded (page load and AJAX reload)

Ideally, I would update the URL when manually selecting a category from the dropdown, but I suppose that's a separate question and it shouldn't be too hard to handle.

There are many ways to solve this, you can take different approaches to the filtering part, the URL part, and the contextual part, and how they play together to get you to your goal. Here's one of the possibilities, probably the easiest route:

This is solved by adding a Relationship for the category field, and then adding a Term "Name" Contextual filter (it will automatically use that Relationship). Be mindful how you configure the spaces/dashes options. This will give you the term name in the URL instead of the term ID.
To get the Exposed filter to match the Contextual you need to use the Views Filter Harmonizer module. There's no workable D8 version yet, you can try and help there, there is an issue open for it.
If you've set up the Exposed filter properly, and turned Ajax on, it should work without a page reload. The "harmonizer" module also claims to play well with that.
I might be missing something here, I wouldn't expect that the Addressbar updating without a page reload is easy, but again the "harnomizer" module claims to do just that, so it seems you're covered if you can get that module to D8.

Another module that might be relevant in another approach: (also no D8 yet) Query Parameters To URL , but similar outcome can be done through your server configuration.


How to get the count on the select list in views? For example, I have a content type with field. The field is select list. The select list has four default values as well as it is required.

I want the output of a view as:

Provincial (2)
Federal (6)
Institutional (3)
...
Value (#)

where # is the number of nodes with this value

How can I accomplish this?

Assuming Drupal 7 and Views 3:

Create a view based on your content type with a page or block display
Add a contextual filter, based on your select field
Under "When the filter value is NOT available" select "Display a summary"
Configure the summary as you like, with "Display record count with link" enabled


Why does composer remove a folder it doesn't manage I have the gesso theme installed in themes/contrib, and since I have not subthemed, all my components and templates live in within its folders. For that reason, I do not manage it with composer.
I needed to install a contrib module, and when I ran composer require, the first thing it did was remove gesso.
Why would this happen, and is there a way to tell it "hands off" ?

It isn't Composer, per se, that's removing your hacked gesso theme. Drupal uses the composer/installers Composer plugin to move different Drupal components (e.g. modules, themes, profiles) to the dir where Drupal needs them.
Once Composer has retrieved the drupal/gesso package, composer/installers will place it the contrib theme path in extra.installer-paths, thus overwriting your pre-existing hacked theme.
If you don't want Composer & the installers plugin replacing your hacked gesso theme, you could do a couple of things:

Remove drupal/gesso from Composer management so it never tries to update or manage the theme again and add the hacked theme back to its previous location.
Use the cweagans/composer-patches Composer plugin to patch the drupal/gesso theme with your component/template hacks so they're added with every update.


Trim whitespace from Float fields before validation I have a content type with a Float field. When my users accidentally enter (or copy/paste) a value with trailing whitespace (e.g. "11 "), drupal gives them the ugly error message:

  Only numbers and the decimal separator (.) allowed in Weight.

But this should be a very easy thing to solve and is not something to bother the user with. However, I can't seem to figure out how to interject code from my module at the right place in order to trim() the value before drupal does its field validation.

Help?

Add the following to a custom module:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  //dpm($form_id);
  if ($form_id == 'BUNDLE_NAME_node_form'){
    $language_float = $form['MACHINE_NAME_FIELD']['#language'];
    $form['MACHINE_NAME_FIELD'][$language_float]['#after_build'][] = 'MYMODULE_field_float_rectify';
  }
}

function MYMODULE_field_float_rectify($element, &$form_state) {
  $children = element_children($element);
  foreach($children as $child){
    $element[$child]['value']['#value'] = trim($element[$child]['value']['#value']);
  }
  return $element;
}

I would think you can also add it to your admin theme's template.php file, but it seems to be more appropriate to add it to a module.


How to programmatically get the field cardinality Is there any way to get the number of paragraphs' repeating limit for the entity's field which those paragraphs depends on?

I'm writing a code which creates paragraphs according to the data taken from a CSV data and and insert their target ID (and target revision ID) into user fields programmatically.

The repeating limits of paragraphs for each user field differs.
Some user fields allow paragraphs to repeat only a few times and others expect them to repeat 10 times.

So if my guess was correct it would be useful if I can get the number when collecting data from CSV and that's why I'm asking.

Thanks for the comments, I figured out a way to get the number(cardinality). Hope it helps someone.

(array) $user_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user');

foreach ($user_fields as $user_field_name => $user_field_definition) {
    (array) $cardinality = $user_field_definition->get('fieldStorage')->get('cardinality');
}


Profile2 with Display Suite I am using profile2. In main profile type I have created some fields. Now according to my project need I want to use display suit for manage display. I followed instruction according to link, but no effect. If I do some changes in manage field it is showing but if I do any changes in manage display it is not effecting.For example in my first screen shot designation is above full name that i have set by manage display but in front end full name is above

Please help me if some one sort out this issue.
Thanks in advance

A nice way to deal with that is to temporarily get out of profile2 rendering way. What I explain here works also for the input form.

1 - Enable the field_collection module.

2 - Create your fields collections.

3 - Then you can arrange the field collection display, including for the form.

4 - You replace your fields in profile 2 with the field collections.

5 - Enable the overlay module (not mandatory), at the bottom of each field collection you can now see add and edit buttons.

Now your fields collections are rendered as you wanted, including for profile2 form.

This is a "good to go" workaround as can be seen on the screenshot.

OR

profile2-display-suite-forms


Contextual filter with multiple entity reference fields Troubles with displaying content in a sidebar block with a View.
Actually, the website is in Dutch, so I'll replace the names of Content Types with something easier, like A, B, C, D.

I have 4 entity types: A, B, C, and D. These are articles referencing each other. So, a node for entity type A on the screen, has additional relevant information in B, C, and D.
While the node from entity type A is on the screen, I want to display the links to the different nodes in B, C and D in a sidebar block.

So in each entity type, I have Entity Reference fields, for example a node from type A has fields  refB and refC and refD.

All working fine, with the links being correctly displayed within the node display, and I can jump between content from each entity type using the Entity Reference fields.

So, for the sidebar block, I created a  View that contains the refB and refC and refD fields, and added a relationship (just for refB initially, to reference the content in entity type B), and a contextual filter on the Nid, getting the value from "Entity from URL".

Nothing gets displayed in the block however.
When I remove the contextual filter, all possible values for the entity reference fields are displayed.  So either I'm getting everything or nothing, but not the relevant entity reference fields from the node in entity type A only.

Articles on this subject explain the Relations and Contextual Filter configuration, but can't get it right apparently.

I think it's because you did not select a Relationship in your field.

Example: Title field (By the way, field_test is my entity ref field name)

Also make sure your contextual filter does not have a relationship


Importing and filtering RSS feeds into nodes I'm looking for the best way to import a feed, say BBC News, and filter through all the content so only articles containing a keyword are stored in the database. I'd like each item to be shown as a node of a specific content type and for it to be updated every given time interval. Is there a straightforward way to do this? I don't have much experience in PHP at all, so please be specific.

The friendliest UI driven way to do this is probably with the Feeds module. Make your content type(s) using Drupal Fields and use Feeds to ingest the content via Cron or job_scheduler module. You might still need to code a simple module to do some things ... but it would require little coding I think.

The less friendly way would be the Migrate module (has a status-indicator UI, but no helpful UI for creating/moving fields). You'd end up coding alot of php to rip through XML and create X nodes in some content type. But, you'd still get a way to import/update/rollback items from RSS. They do have XML "News" examples I think in the Migrate modules example folder in the project.

I'd go with Feeds if you're new to this and stumble your way through that ... I haven't used it. I can only recommend it.


Disable /Enable a multivalued paragraph field on Ajax calls I have 2 fields in a form. One select list and another entity reference field referring to a Paragraph type (multivalued).
The on-change event should trigger an ajax callback which will disable some of the fields in the paragraph type.
I managed to achieve this on ajax callback. Now, the problem is when I add more values to the paragraph the previous disabled field goes back to the default state.
Any suggestions /examples will be helpful. Below is my code.
Thanks.

    function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      //Ajax callback on change event
      if (isset($form['field_link_type'])) {
        $form['field_select_sample']['widget']['#ajax'] = array(
        'callback' => '_my_ajaxcallback',
        'event' => 'change',
       );
      }
     }

    function _my_ajaxcallback(array $form, FormStateInterface $form_state) {

      $response = new \Drupal\Core\Ajax\AjaxResponse();

      //disable field_htext of paragraph field
      $response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.field--name-field-htext input', 'attr', array('disabled', 'disabled')));

      return $response;
    }

Updated code -
In my callback -

    echo 'disabled - ' . $form_state->get('field_header_disabled');`
    $form_state->set('field_header_disabled', TRUE);`
    echo $form_state->get('field_header_disabled');
    return $response;

The output is something like - disabled - 1 on both first and second callbacks. On second callback I'm expecting the output to be something like disabled - 11

Your issue arises, as the paragraphs widget(s) itself do a lot of Ajax calls and you disable the field(s) in your browser only. So your paragraph form will be reloaded and re-rendered without knowing that the field has been disabled before.

To have the field(s) disabled on consecutive reloads, you need to make your changes more permanent.

You could e.g., save a flag to the $form_state using the FormStateInterface::set() method:

  FormStateInterface
  [...] it may be used to store information related to the processed data in the form, which will persist across page requests when the 'cache' or 'rebuild' flag is set.

This means, after you stored a custom flag in the $form_state and an ajax request to reload this form is made, it will be available within the $form_state of your hook_form_alter() implementation as well.

So all we have to do now, is checking for this flag in hook_form_alter() using the FormStateInterface::get() method and ensure the field will be disabled, if it has been set before.

A less abstract example:

/**
 * Callback for disabling field_htext.
 */
function _my_ajaxcallback(array $form, FormStateInterface $form_state) {
  $response = new \Drupal\Core\Ajax\AjaxResponse();

  // Disable field_htext of paragraph field.
  $response->addCommand(new \Drupal\Core\Ajax\InvokeCommand('.field--name-field-htext input', 'attr', array('disabled', 'disabled')));

  // Set a 'disabled' flag in form state.
  $form_state->set('field_htext_disabled', TRUE);

  return $response;
}

And in your form alter:

/**
 * Implements hook_form_alter().
 */
function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Better use the form ID here and check, if you are at
  // your form in question, or even use a more specific hook as
  // hook_form_BASE_ID_alter() or hook_form_FORM_ID_alter().

  // Check our custom disabled flag.
  if (
    !empty($form_state->get('field_htext_disabled'))
    && isset($form['field_htext'])
  ) {
    // Set the 'disabled' attribute.
    $form['field_htext']['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
  }

  // Add ajax callback on change event.
  if (isset($form['field_link_type'])) {
    $form['field_select_sample']['widget']['#ajax'] = array(
    'callback' => '_my_ajaxcallback',
    'event' => 'change',
   );
  }
 }


Module/code to automatically generate an id number for title of page I want to automatically generate a project id. (To go where the title would go on a drupal webpage)

I am guessing this might be possible with php? But i don't know whether it is possible to do it for a title because I have only managed to acheive php in the code.

I want the title to identify a project and each project to have sub cases (also with unique identifiers).

I don't want the number to be randomly generated but rather it have some attributes that can be used to determine characteristics about the project.

Ideally, I want t end up with an id which is something like this eg

 Ldn101201

where
ldn is the city 10 is the start month 12 is the start year and 01 is the project number.

Ldn will be inserted because the user opening the project is based in london
1012 will be inserted because this was the date when the project was made
and the last number will be the generated number tagged on.

I really would be happy if I can at least get an ascending ids for when projects are created but if anyone has ideas about the more complicated part that would be great help also.

Hope that makes sense.

Have you seen the Automatic Nodetitles module? From the description:

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

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).

  Advanced users can also provide some PHP code, that is used for
  automatically generating an appropriate title.


What is the best way to forward visitors to my homepage to an external site but leave the backlinks accessible? Maybe not distinctly a Drupal question, I have an older Drupal 7 site that I want to leave up for backlinks, but any new visitors I want to redirect to a new external website.  So domain.com would redirect to newdomain.com but domain.com/node/6 is still accessible.

Update: Server is nginx and I don't have access to server settings and routes.

It sounds like one thing you could do is edit the themes template.php file and do something like:

/**
 * Implements template_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {
  if (drupal_is_front_page()) {
    $url = 'http://newdomain.com';
    drupal_goto($url, ['external' => TRUE], 301);
    // perhaps alternatively you could use header();
  }
}

Outside of doing this at the web server level, it might be the smallest change to do it.


creation token rest post via postman Access Denied I added drupal module "Oauth2" in order to test access by tokens. I created a consumer and got his uuid and client_secret by which I tested, using postman post method, the genretation of my first token,but it failed by 403 access forbidden(see the capture bellow):

I tried to test a simple connexion (by admin account) to my user login using the post method, but it failed as well (see the capture bellow):

Seems like there is an issue with the post method

PS: I've already enabled POST for my endpoint at /admin/config/services/rest.

Thanks in advance!

I eventually figure out what the problem was after many many attempts.

There was actually an issue with postman access to Drupal, it's because Drupal was configured in services.yml to allow access only to Angular API (for my project) by:

Configure requests allowed from specific origins.

allowedOrigins: ['http://localhost:4200']

I changed it to test with postman by:

Configure requests allowed from specific origins.

allowedOrigins: ['*']

Consequently, my token was created in postman with post method which means: bye to 403 error!!!

Hope that can help someone :)

Thank you!


A page to display various membership types to choose from? I am completely newbie to Drupal, currently using Drupal 7.x

Though I am experience hard-core IT professional, I am trying to learn Drupal.

I have a simple requirement to display a page when user clicks on "Create new account".

The page should display three columns giving details of  three types of memberships, basic, premium and enterprise. Three memberships should be display in three columns and at the bottom of column there should be button "Register" which should take user to fill registration details.

Please could you guide me how to do that.

Regards
TD

You will need to create a custom module to do it exactly as you desire, and you probably won't find anyone here to do it for you, so you need to do more research if you go that approach.

A simpler approach does not require a custom module:

create a block with the three "tables" as images (to be prettier in my opinion)
add that block to the content-top of whichever theme you have
restrict the content to only show on the user/register page
under admin/config/people/accounts/fields add a new field of type list(text) that includes the three types of account, required at registration
if desired - set a Rule to act on new account registration to take care of role changes or other account differences based on the value of the drop-down selection

This will show the three options at registration and require the user to choose one of them - the Rules will then act on that choice to change the account as desired


How to remove a fieldset from around a Mailchimp Subscription field? I have added a Mailchimp Subscription field to an entity form using the Mailchimp module. I'm having difficulty in removing the fieldset around this subscription field.

I have installed the Devel module and used the dpm function to display info on the form. But I can't seem to find what theme function I need to override to remove the fieldset.

I have an existing form alter applied to this form, what would I need to add to my existing form alter to remove the fieldset around the field?

You need to use YOURTHEME_form_alter of YOURMODULE_form_alter https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7

there you can alter that form. dpm or print_r $form and see where that fieldset is defined and you can unset it

you will see something like

array(
   'some_field' = array(
    '#title' = 'some title',
    '#type' = 'fieldset',
  )
)

then you can do

unset($form['some_field']['#type'])

that should do the job


Cannot change CSS after CSS/JS aggregation I'm using D7, recently I checked all the bandwidth optimization option in admin/config/development/performance, I wanted some change-back in CSS afterwards, which now I can't with the bandwidth optimization being checked. I tried unchecking that bandwidth optimization, then it accepts the new change. But when I check the bandwidth optimization again, it takes me to an older version of CSS, Please let me know how to update the CSS as well as checking all the optimized radio buttons.

CSS/JS aggregation's purpose is to bundle all your non-external css/js files into a single file. This way instead of requesting multiple files and requiring multiple connections with the server, the client only has to download the unified css/js file once. However, this specific file is not re-created every time you make a change to your css or javascript. You will have to manually do it. Here is how:

In Drupal 7 go to:
Administration > Configuration > Development > Performance (admin/config/development/performance)

and click the "Clear all caches" button. Notice that this will clear all caches of your site.

The method that I use more often though is to clear all the caches through Drush (if you do not know what Drush is, you should really check it out since it's a real life saver). Instead of navigating to the URL and clicking the button, you can just write the simple command:

drush cc all

in your command line and all caches will be cleared.

Keep in mind, that if you are still theming/developing your site, you should disable CSS/JS aggregation. If you don't, you are adding more workload to the server that is rebuilding the unified css/js files every time that you press the "Clear All Caches" button. The specific option should only be turned on on production sites where css/js files have been finalized.


addClass in Twig with if statement in item-list.html.twig I try conditionally add a CSS class to a
 element in item-list.html.twig.

{%- for item in items -%}

    {# check if is facet li #}
    {% if item.attributes.hasClass('facet-item') %}

{{ item.value }}

    {% endif %}

{%- endfor -%

When I add the if statement like above, I don't get any output at all. If I remove the if statement I get correct output like:

            <input type="checkbox" class="facets-checkbox" id="contactvoorkeur-email" data-facetsredir="/search-person/cards?f[0]=contactvoorkeur%3Aemail">
            E-mail (2)
            E-mail (2)

        <input type="checkbox" class="facets-checkbox" id="contactvoorkeur-post" data-facetsredir="/search-person/cards?f[0]=contactvoorkeur%3Apost">
        Post (1)
        Post (1)

I might be wrong here, as we do know know what problem you are having...

But {{ item.attributes.addClass('list-group-item') }} will add the list-group-item class to the item-element. (It does not print this class.)

Because of the surrounding code: {% if item.attributes.hasClass('facet-item') %} ... {% endif %}, I feel you want to add a class to the childs of item, not to item itself.

Why not output this instead?

{{item.value}}

So the condition becomes:

{% if item.attributes.hasClass('facet-item') %}

{{item.value}}

{% endif %}


Add slideshow option to 'link image to' in Views I have created a View that displays images uploaded on my website as thumbnails and in a grid style. However when I click on an image I would like some slideshow function to show so the user can click 'left' and 'right' to scroll through the images.
How can I add this functionality to 'the Link Image to' setting?

I assume you already have a Gallery or Slideshow working (otherwise check other modules, e.g. Juicebox). If you want the image to link to a specific path you need to choose the option Rewrite Results > Output this field as a link. You can use tokens if you want to change this path dynamically according to other fields in the View.


Managing backward compatibility It seems (correct me if I'm wrong) that there are some classes or services that must be used in relevant cases in Drupal 9 that are not present in Drupal 8.
For example, New in Symfony 4.3: Simpler event dispatching Symfony\Component\HttpKernel\Event\RequestEvent in place of Symfony\Component\HttpKernel\Event\GetResponseEvent.
Same with temporary session storage and more.
This means that if these features are used in a module, the module can only be compatible with one of these core versions; but it seems like a complete waste to manage two codebases at this point, since the versions are still very similar.
What is the correct way to manage this compatibility in one module, and has this question been addressed by the Drupal 9 release team?

Yes, this has been addressed by the core maintainers. You are safe if your module doesn't use any APIs deprecated until Drupal 8.8/8.9:

Drupal 8.8 was the final release to introduce new deprecations that will be removed in Drupal 9

A quote from the Drupal release team: https://groups.drupal.org/node/535670
You should wait to remove deprecations introduced in Drupal 9 until you prepare for Drupal 10 and don't need Drupal 8 support any longer.
So beginning with Drupal 8 you can manage compatibility for two Drupal versions  at the same time.


Add custom text as a label in front of RSS feed icon I want to change the label from "Subscribe to News" to "Subscribe to News Feed" displayed with RSS icon in drupal8. Also I need to open a popup window on clicking icon.

Attaching the screenshot:

Any help to figure this out?

You can see feed-icon.html.twig

you need copy feed-icon.html.twig in core/modules/system/templates/feed-icon.html.twig to themes/yourtheme/templates/feed-icon.html.twig

in file themes/yourtheme/templates/feed-icon.html.twig

{#
/**
 * @file
 * Default theme implementation for a feed icon.
 *
 * Available variables:
 * - url: An internal system path or a fully qualified external URL of the feed.
 * - attributes: Remaining HTML attributes for the feed link.
 *   - title: A descriptive title of the feed link.
 *   - class: HTML classes to be applied to the feed link.
 *
 * @ingroup themeable
 */
#}
<a href="{{ url }}"{{ attributes.addClass('feed-icon') }}>
  {{ 'Subscribe to News Feed'}}
</a>


Can't find migration when running drush migration:status I'm trying a tutorial to migrate users data from a CSV file.
From here: https://u.group/thinking/drupal-8-csv-migration/
I've created a module as suggested. Here is the code:
/config/install/migrate_plus.migration.demo_user_migration.yml
id: demo_user_migration
langcode: en
dependencies:
  enforced:
    module:
      - user_migrate
label: 'User migration from CSV'
source:
  plugin: csv
  track_changes: true
  path: /config/users.csv
  header_row_count: 1
  ids:
    - Uid
destination:
  plugin: entity:user
process:
  name: Name
  mail: E-mail
  field_last_name: First Name
  field_first_name: Last Name
  status: Active status
migration_dependencies:
  required: {  }
  optional: {  }

user_migrate.info.yml
name: User Migrate
type: module
description: Custom Migrate of Users using a CSV file
core: 8.x
package: Migration
dependencies:
    - migrate_source_csv
    - migrate_plus
    - migrate_tools

user_migrate.module
<?php

/**
 * @file
 * Contains teacher_migrate.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function user_migrate_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the custom_user_migrate module.
    case 'help.page.user_migrate':
      $output = '';
      $output .= '
' . t('About') . '
';
      $output .= '
' . t('User Migrate') . '
';
      return $output;

  }
}

/**
 * Implements hook_migration_plugins_alter().
 */
function teacher_migrate_migration_plugins_alter(&$definitions) {
  $definitions['demo_user_migration']['source']['path'] =
    drupal_get_path('module', 'user_migrate') . $definitions['demo_user_migration']['source']['path'];
}

I've enabled the module from the Extend page.
However, when I run drush migration:status the migration I've created is not found. This confirmed by executing drush migrate:import demo_user_migration
Do you know where the problem can be?

Did you try clearing drush cache with drush cr drush?
Also, the correct notation for checking the status is drush migrate-status demo_user_migration


How to save uploaded image in an content type to picasa? I am uploading an image in a content type and I want that image to saved in picasa web albums.

While showing that node, I want the image to be displayed from picasa. Is there any module available for that or how do I achieve this?

Picasa Node Album module provides gallery support in the form of
  associating Picasa albums with nodes.

Features

Link any public Picasa album to a node
Thumbnail view with a template you can override
Lightbox2 support already in the default template
Select albums of the current Picasa account with autocomplete
Supported node types configured via admin settings
Define if thumbs should show on teasers and/or page views
Define how many images in the gallery should be displayed on teasers/page views
Define the sizes of thumbnails and images to request from Picasa
Define whether you want an Albums tab on the node or not
Image data results cache with a defined expiration
Restrict what picasa accounts content can come from
Restrict how many albums a user can upload per node


force a different page template based on node id? Is it possible provide a page with an alternate template suggestion for a certain page?

e.g. i have a landing page. I have the node id. I would like to switch the page template if the node id is a certain number.

If it is how would you go about that in the theme preprocess function?

This ought to do it:

function MYTHEME_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    $vars['theme_hook_suggestions'][] = 'page__node__' . $node->nid;
  }
}

And then call your template file page--node--123.tpl.php


Conditional based field security Is there any condition based field security in Drupal? E.g. An administrator can only edit user details users who are from the same Country?

You can implement complex field access conditions fairly easily with:

hook_field_access


Is there a theme equivalent of hook_install()? I want my theme to control certain block settings, like which elements of the system branding block are enabled. To me it makes sense for that to be code in the theme, not a module, because at the moment the only way I've found to access the config programmatically involves using the theme name.

/** @var Drupal\Core\Config\Config $config */
$config = \Drupal::service('config.factory')->getEditable('block.block.my_theme_branding');
$config->set('settings.use_site_logo', false);
$config->save();

Since this is a one off config change, I think it should only happen when the theme is installed/activated. It there a theme function/hook that behaves like hook_install does for modules?

You may provide configuration via YAML files as part of a module, profile or theme install by adding them to the config/install directory inside the respective project. So, for example, a file block.block.my_theme_branding.yml would install the branding block into the specified region. This would then contain the setting to disable the site slogan by default. Take a look at block.block.bartik_branding.yml in the standard profile as a starting point.

If the specific block is provided by another module, then it should probably be placed in the config/optional directory.


How to manage programmatically the access of a content node type? From a custom module, I created a new type of content type via the drupal api (using the hook node_info). Thanks that, I can create node of this content type.

I would like allow access to nodes of this content type only for his author. And I want the author have only access to the view page of the node (edit page denied). How can I do that?

In Short:
In my custom module, how allow only access to the view node page only the author of the node?
The author can only access to the view page of a node created by the author. And, edits pages aren't be accessible for all non-admin users.

We need to set permission for doing this. Permission can be done specific to a Role not to a User. Please use below codes. Please update your role name instead of 'New Role' and machine name of your content_type instead of 'your_content_type'.

$role_name = "New Role";
$role_permissions = array(
  'create your_content_type content',
  );

$role = user_role_load_by_name($role_name);
user_role_grant_permissions($role->rid, $role_permissions);


Building views relationship with location I have an article and food content types. I use location module fields in both content types. So for example, when I write an article about restaurants in New York, I choose article's location as country: US, state: NY and city:New York. Now, I want to be able to show related food items in view with same country, state and city. Now, how do I display food items matching with article's location.

Sibling items are usually displayed with the help of two Relationships and one Contextual filter.

Create Food item Views.

You first add the Relationship for your Location field, it introduces info about the Location.

Then you add the reverse Relationship to the first one, it will use the first Relationship. The second one points back to the content that is using that Location field.

Add the Contextual filter for Node ID and make it use the second Relationship. Set it the usual way, default value and ID from URL, validate against Article Content type.

I haven't tried this with the Location field but the logic should be the same.


Change the site slogan on certain pages I have a Drupal 8 site with a content type called Landing Page.  I'm using the bootstrap theme and I have the block showing the brand info (including site slogan) in the navbar.

I want some of the landing pages to have a different site slogan (shown in the navbar).  How can I do that?

What I tried

I thought of adding a text field custom site slogan to my Landing Page content type and then using a twig template (content type node template) to show the slogan, but the slogan is printed in the header, and the template comes after that.

I could also make a different branding block for each page I need to change the slogan on and manually change the text in a twig template, but that seems like a very horrible, labor intensive way to do it.

Ok, thanks to the hint from @Hudri, here's what I did.

In mycustomtheme.theme:

function MYCUSTOMTHEME_preprocess_block(&$vars) {
  if ($vars['configuration']['id'] === 'MYMODULE_site_branding_nolinks_block') {
    $site_config = \Drupal::config('system.site');
    $vars['site_slogan'] = $site_config->get('slogan');
    $vars['site_name'] = $site_config->get('name');
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $type = $node->getType();
      // For landing pages, set the site slogan to the value of the slogan field.
      if ($type === 'landingpage') {
        $node = \Drupal::entityTypeManager()->getStorage('node')->load($node->id());
        $slogan_field = $node->get('field_slogan')->getValue();
        $slogan_field = $slogan_field[0]['value'];
        $vars['site_slogan'] = $slogan_field;
      }
    }
  }
}

But, we're not done yet, because the block (provided by my custom module) is cached the same for every page; it needs to be cached per URL, since it might be different for each landing page.

To fix that, in mymodule/src/Plugins/Blocks/myBlock.php, add this code:

  // Caching must be added here:
  // https://drupal.stackexchange.com/questions/223376/what-is-the-correct-way-to-set-cache-contexts-on-custom-blocks
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), ['url.path', 'url.query_args']);
  }


inserting content into node using field I am really stuck and need some advice, I'd like to know how I can go about doing this, simply put:

A website contributor enters a value into a field which is placed into the html.

eg. I have say two fields that will determine an image name and the file type. In field 1 the user enters [ABC], in field 2 the user enters [123].

The output of this would be <img http://www.example.com/[ABC].[123] />

I have never worked with my own custom modules/fields etc before, a point in the right direction would be a big help.

To do this in a template,
1. create a file inside your /sites/all/themes/YOURTHEME folder, called node--CONTENT_TYPE.tpl.php.
2. copy the contents of node.tpl.php into that file.
3. add something like the following to the template file, where you want to print the image:

<img src="http://example.com/<?php
    print $node->YOUR_FIELD_1[$node->language][0]['value'] .
    '.' .
    $node->YOUR_FIELD_2[$node->language][0]['value'];
    ?>
 alt="..." ... >

Another possibility (probably better), would be to use the filefield sources module, and let the users upload the image to your drupal site by pasting the url.


Price field with Currency outside of commerce and ubercart For a real-estate (realty) website I need to store and display the price, but the best D7 module for this is the price component of Commerce module. Is there a Price/Money field on D7?

I have found the following modules:

Measured Value Field - Cool idea spans a lot of value types - D6
only
Units API - Really more for measurement, integrates with MVF
Format Number - Most recent dev version but not sure how rough this version is

I'd go with Commerce Price (part of Commerce). You don't need to enable the rest of Commerce.
The price module itself is relatively small (while giving you price calculation, and Rules integration for free, if you need it), and the rest of Commerce won't be loaded, taking only space on your hard drive, which probably doesn't concern you much.

That's the beauty of Commerce separation, you can use only a few modules that give you exactly what you need. I've seen that happen in many projects.


Custom ajax widget can't save generated value to database - $item always zero I'm currently working on a custom module that communicates with a REST API. It is implemented as a new field type with a custom widget. The entire communication with the API works fine. The thing is that I'd like to save one part of the response in the database and I can't get it to work.

My code is here:
https://github.com/stopopol/b2share/blob/master/b2share.module

Basically, I only need the information of one textfield ( $form['b2share_fieldset']['pid_button']) to be saved in the database, but the save function doesn't seem to be called.

I tried following this tutorial: http://getlevelten.com/blog/ian-whitcomb/defining-custom-field-types-drupal
but I had no success yet.
Maybe it's also important to mention that this field will be embedded in a content type together with plenty of other fields, therefore the communication with the rest api is done via ajax, but the values I get from the API should be stored together with the regular fields in the node form.

I only need someone to tell me what's missing from being able to save it. I've been stuck for days and can't figure it out.

Thanks.

EDIT: Ok. I narrowed it down and it seems like the problem is that

foreach ($items as $delta => $item)

never runs because the size of $items is always 0. I haven't found the reason yet. But will post my insights here.

EDIT2: Thanks for the helpful comments. I used hook_submit and was able to save values in the database, but drupal is complaining about the entity_Id and delta.

Example code I found suggests a function like this:

 function b2share_form_alter(&$form, &$form_state, $form_id) {
   $form['actions']['submit']['#submit'] = array('b2share_form_submit');
   return $form;
 }

 function b2share_form_submit($form, &$form_state) {
 drupal_set_message( 'submit handler is called' );

 $values = array(
   'url' => $form_state['values']['b2share_fieldset']['url'],
   'pid' => $form_state['values']['b2share_fieldset']['pid']
 );

 $insert = db_insert('field_data_field_b2share')
   -> fields(array(
    'field_b2share_url' => $values['url'],
    'field_b2share_pid' => $values['pid'],
    //'entity_id' => 1,
    //'delta' => 0,
    //'language' => 'und',
))
->execute();
}

But apparently the functions needs to give more info or I am missing something somewhere else.

EDIT 3: Calling b2share_form_submit breaks the node form. The error message says: "The requested page "/.../node//current-revision" could not be found."

Logs say :

"Warning: Missing argument 3 for b2share_form_submit(),"

"Warning: Missing argument 4 for b2share_form_submit()"

EDIT 4: As described here in a comment (Do something after submit the form at hook_form_alter) this is the correct way to write the form_alter function:
function b2share_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][]='b2share_form_submit';
  return $form;
}

I found multiple examples on how to write your a custom submit handler, but most of them had a flaw in it. They were either always or never called. Sometimes I couldn't access the node_id, which was crucial for me.

I ended up using this:

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

function seal_the_deal($form, &$form_state, $entity_id, $entity_type, $form_id) {
 $values = array(
  'url' => $form_state['values']['b2share_fieldset']['url'],
  'pid' => $form_state['values']['b2share_fieldset']['pid']
 );

 if ( (empty($values['url'] == false) || (empty($values['pid']) == false)) ) {

    $insert = db_insert('field_data_field_b2share')
     -> fields(array(
        'field_b2share_url' => $values['url'],
        'field_b2share_pid' => $values['pid'],
        'entity_id' => $form_state['node']->nid,
        'entity_type' => 'node',
        'bundle' => $form_state['node']->type,
        'delta' => 0,
        'language' => 'und',
     ))
    ->execute();
     }
   }

Details can be found here:

Custom submit handler is also called when deleting a node

http://atendesigngroup.com/blog/form-altering-node-addedit-forms

Drupal 7 custom form submit handler is not being called


Why form redirects to encoded url when having GET params? I have a simple form with 1 select and I want it after the form submit to redirect to the same URL, but with added GET params.

So in a form submit I added:

$form_state['redirect'] = url(arg(0).'/'.arg(1).'/'.arg(2), array(
  'query' => array(
      'brand' => $state['values']['brand'],
      'categ' => arg(2)
)));

Which redirects to wrong encoded url:

  /produkty/vlasy%3Fbrand%3D118%26categ%3D27

But It works well when I use drupal goto (this is not recommended):

  drupal_goto(arg(0).'/'.arg(1).'/'.arg(2), array(
      'query' => array(
          'brand' => $state['values']['brand'],
          'categ' => arg(2)
  )));

  /produkty/vlasy?brand=118&categ=27

Why is it so?

You just need to adjust the param value from a string to an array for $form_state['redirect']

It is in the documentation for drupal_redirect_form

  $form_state['redirect'] determines where to redirect the user. This can be set either to a string (the path to redirect to), or an array of arguments for drupal_goto().

Example:

$form_state['redirect'] = array(
  arg(0) . '/' . arg(1) . '/' . arg(2),
  'query' => array(
        'brand' => $form_state['values']['brand'],
        'categ' => arg(2)
  )
);


LDAP module + Windows AD I have a large AD setup which has not been configured in the ideal fashion, the base DN:

dc=davinci,dc=mydomain,dc=local

Now the existing structure of our AD looks something like:

@ 1122 Logan
  Accounting
  Aquarius
    Alejandro
    Mike
    Justin
  Aerospace
  Distribution
  Engineering
@ 2150 Logan
  Uniflyte
@ 1480 Church

Trying to test the authentication of the user Alejandro (old network guy was being funny when he gave me a user name).

Here is my Server Property Dump:

Server Properties:

sid = Davinci
numeric_sid = 1
name = Employees
status = 1
ldap_type = ad
address = davinci
port = 389
tls = 0
followrefs = 0
bind_method = 2
basedn = Array ( [0] => dc=davinci,dc=cadorath,dc=local )
binddn =
user_dn_expression = cn=%username,%basedn
user_attr = samaccountname
account_name_attr =
mail_attr =
mail_template =
picture_attr =
unique_persistent_attr =
unique_persistent_attr_binary = 0
ldap_to_drupal_user =
testing_drupal_username = Alejandro
testing_drupal_user_dn = cn=Alejandro,ou=@ 1122 Logan,dc=davinci,dc=mydomain,dc=local
grp_unused = 0
grp_object_cat =
grp_nested = 0
grp_user_memb_attr_exists = 0
grp_user_memb_attr =
grp_memb_attr =
grp_memb_attr_match_user_attr =
grp_derive_from_dn = 0
grp_derive_from_dn_attr =
grp_test_grp_dn =
grp_test_grp_dn_writeable =
search_pagination = 0
search_page_size = 1000

I enter in my password for non-anonymous search (Windows login password)...

Testing Drupal DN:

  cn=Alejandro,ou=@ 1122 Logan,dc=davinci-1,dc=cadorath,dc=local

Drupal logs report:

LDAP bind failure for user userdn=, pass=XXX.

Where does the userdn get constructed???

I still cannot login to drupal with Windows login details...D7 is running in the same domain as Davinci so I assume I missing something in the syntax of connection string???

The ldap config page for users and fields has a user_dn entry you can set.


Taxonomy term View Customization on a website I'm working this period i have this problem with Taxonomy term View:
My scenario is like this : I've created a vocabulary with terms and sub-terms for my products categories. So for example there is a structure like this:

First Category: Computing-->Laptops (Apple, Acer, Dell)-->
 Desktops (CPU, RAM, Hard Drives, VGA)--> Servers (HP, Dell, Cisco, IBM)

Second Category:Peripherals--> Monitors (Samsung, LG,Dell, Asus)-->Keyboards (Logitech, Microsoft)--> Printers (Epson, HP, Samsung)

I'm using taxonomy term view to make the taxonomy term page to show the products in a grid using fields. Everything works fine, when i click for example on Dell i see XPS14, XPS14Z, XPS15 etc in a grid format with a thumbnail picture and the title below it. (I' created a field for thumbnail for every product).

What i want to do is when i click on Computing for example, to show only Laptops, Desktops and Servers with a thumbnail for each one and not all the products for Computing term ( Apple,Acer,Dell,CPU,RAM,Hard Drives...etc) as it happens now. I've tried to put some contextual filters from the view but i didn't figured out how to accomplish it yet.

I'm assuming you are using the "Taxonomy term" view that comes with drupal.

Edit that view and:

Edit the contextual filter for "Content: Has taxonomy term ID (with depth)"

Set the depth option as high as you need to cover the number of levels in your vocabulary.


Add multiple nodes at the same time? I've got a requirement to allow Users the ability to create multiple nodes within a single experience.

All this content the Users are adding share much of the same data, so the idea is to give them a more convenient way to add multiple nodes without all the Save and Add Content clicking.

They don't necessarily need to be able to edit the nodes in the same single experience.

Any modules, and/or case studies you recommend?

Maybe the Multi Node Add will cover what you require :

  This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes.
  It is designed to create multiple nodes in one round, it's possible to add more node input rows on-the-fly.

See if it does it for you. But also beware that it's a beta release.


Uncaught TypeError: Cannot read property 'fn' of undefined This occur after I added a Photobooth plugin in my hook_init function:

function myid_init() {
    drupal_add_js(drupal_get_path("module", "myid") . "/photobooth-js-gh-pages/photobooth_min.js");
    drupal_add_js(drupal_get_path("module", "myid") . "/photobooth-js-gh-pages/website/js/script.js");
}

This needs JQuery(1.11.2) to work, but Im assuming that Jquery has already a default Jquery. So why does it doesn't work?

I had installed JQuery Update Module and finds out in the Configuration Settings was only limited upto Jquery 1.10, which is not sufficient for my Jquery Plugin. How will I update the Drupal's default JQuery library to 1.11.2?

Check out the drupal.org document on using new versions of jQuery for a few solutions. One good solution is the JQuery Multi module that lets you target multiple versions of jQuery via its hook_jqmulti_libraries() hook (its README explains how).


Proper way to cache custom entities with Entitycache? I am trying to figure out how to cache custom entities with Entitycache module. As I know Entitycache module doesn't support custom entites created with Entity API, that's why I'm doing like this:

created cache table for own entity: cache_entity_carroza_user

created own controller, extent EntityCacheDefaultEntityController, implemented EntityAPIControllerInterface:

class CarrozaEntityController extends EntityCacheDefaultEntityController implements EntityAPIControllerInterface {
  ...
}

implemented hook_entity_info, specified entity controller:

$return = array(
  'carroza_user' => array(
    'label' => t('Carroza User'),
    'controller class' => 'CarrozaUserEntityController',
....

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

created CarrozaUserEntityController:

class CarrozaUserEntityController extends CarrozaEntityController {
  public function __construct($entityType) {
    parent::__construct($entityType);
  }

  public function resetCache(array $ids = NULL) {
    EntityCacheControllerHelper::resetEntityCache($this, $ids);
    parent::resetCache($ids);
  }

  public function load($ids = array(), $conditions = array()) {
    return EntityCacheControllerHelper::entityCacheLoad($this, $ids, $conditions);
  }

  public function create(array $values = array()) {
    $values += array(
      'carroza_uid' => '',
      'is_new' => TRUE,
      ...
    );

    $carroza_user = parent::create($values);
    return $carroza_user;
  }

  public function save($carroza_user, DatabaseTransaction $transaction = NULL) {
    return parent::save($carroza_user, $transaction);
  }
}

I'm doing everything Entitycache documentation says, but can't see any records in cache_entity_carroza_user table. Am I missing something else?

entitycache.module and entity.module integrate, so that just just work.

All you need to do is make sure that the cache table for your entity table exists and set the keys in hook_entity_info() as you already do.

Not sure why it doesn't work, but I'd start by removing the custom controller and rely on the default one from entity.module.


How to apply focus for specific tab in quicktab I have used quicktabs to search my channels and profiles.I have set default tab "Channels/Videos" in quicktabs setting.When a user enters the text and selects "Profile" tab the focus automatically reverts back to "Channels/Videos".What I want want is,it should remain on the option whichever is been selected("Channels/Videos" or "profile").How can i do this? I also checked by setting the default tab as"none" in quicktabs setting but when a user search for "Channels/Videos"(or "Profile") focus on tab( which is in blue color ) disappears. How can i fix this problem?

You can alter the search form hook_for_alter using form id.

Add a hidden field name it 'mytab' whose by default value will be channel and on click of tab its value will be toggled between channel and profile.

So when we submit the form to search the content, it will look this way ?title=hello&mytab=channel

Now on in your hook_form_alter inline js code to select the default tab based on the mytab value that you can get using $_GET.

Let me know if it works for you.


Best way to unpublish a node, given the nid, while bypassing any node update hooks? To unpublish a node, I set status=0 and call node_save(). Unfortunately, this invokes the Geocoder module and it sends a request to the Google API for a geocode that I already have. There is apparently no way to turn this off.

I am looking for an alternative to node_save() that does not trigger this behavior or any other hooks, for that matter.

(btw, for fields I am achieving this with field_attach_update, but to unpublish I need to update the node itself)

If you have an array of nids you could just run this piece of code

example will unpublish the nodes with nid 1,2,3:

$nids = array(1, 2 ,3);

foreach($nids as $nid) {
    db_query("UPDATE {node} SET `status` = '0' WHERE `nid` =:nid ;"
,array(':nid'=> $nid));
}

entity_get_controller('node')->resetCache($nids);


In using the rule "OG new content notification," (rules_og_new_content) how can I insert the group name in the outgoing email In using the rule OG new content notification (admin/config/workflow/rules/reaction/manage/rules_og_new_content) for a site using Organic groups. However, I'd like add in the name (and URL) of the parent group. However, I'm not seeing these options in the tokens ("replacement values").

The Content Type in question has the field og_group_ref for which I'm trying to target.

What I've tried so far (update):

On a dev instance, as per Pierre's recommendation below, I've added the following 'fetch entity' to the rule.

But the email comes in blank, without title on the subject line

Add Action >> Get group members from group audience >> node

Add Loop >> node:og-group-ref

Add Loop inside loop >> group-members >> rename list_item to list_item2

Add Action >> Fetch entity by property >> User >> Mail >> list-item2:mail
Add Action >> Fetch entity by property >> OG Memembership >> field_name >> list-item:title >> rename entity_fetched to entity_fetched2
Add Action >> Send Mail >> list-item2:mail >> list-item:title

End Result:

(click image to enlarge)


drupal 7 parent menu item will not hide for authenticated user Could any one give me some ideas on what i need to check please?

I wish i could just show the site, but of course it' for my company, so I can't,  but I have a menu bar at top of my page home, contact, meet the authors, books;

Under "Meet the authors", i have several authors, I created an authors content type and have one for each author. When you hover over "Meet the Authors" you see the drop-down list/sub-menus of the authors - only five of them now.

so using panels and views, when you click of "meet the authors" you see a list of the authors on the page and can click in for more detail.

Using the access control module, I only want this link to appear for anonymous users, once logged-in, this link should disappear but the link will not hide itself after login, but here is what's really odd, the sub-links which are the authors, those links/sub-menu do/does hide when the user logs in and only displays for the anonymous user

so for example, this enable menu should appear for the anonymous user

Meet the authors
 - ----Kim Fields
 - ----Tony Bruewer
 - ----Harris Carlton
 - ----John Brown

and should be completely hidden for the authenticated user, but what is happening though, upon login, the user sees the parent menu:
Meet the authors

but the sub menus have hidden themselves as they should, i just can't get the parent menu to hide itself.

I have checked the access control to make sure I have selected things properly.  I even created test content type and menus to test and everything worked, so I assume there is something different, but I just can't see what and where.

Any ideas and guidance would be greatly appreciated. Thank you.

Notes: the parent menu about [Meet the authors] is pointing to a panel page that contains a view to display the list of authors.  I do not have access setting on the panel.

More Information:
So for my own sanity, I slowly created another content type, a view for that content type and a panel page.  Saved, cleared cache, ran cron.  Change settings in control access module.  Here is what I now see-- The sub-menus of the parent menu [Meet the authors]are following the authentication rule, the top menu just displays all the time.  I create this mention from the Structure->Menus navigation.  So the top menu item is pointing to the panel whereas the sub-menu items are actually the content types.

Still more Info:
Here is what I think the issue that I still have not found a way around.  I create the view, create the panel, place the view in the panel, give the panel page a normal menu entry.  So that is my menu item that appears.  If I click on that top parent link, it takes me to the panel with my view, but the menu item won't display/hide as needed.  So i realized that the menu I am creating in the panel has nothing to do with the content type and the content type is needed to manage the access control module.  So I go into my content type, change one of it's types and change the menu to point to the panel url I created.  Well when I do that, that url is assigned to that content type node, not panel, but the menu item does, now, display/hide based on the selection from the access control module.

Can anyone give me a way around this?  What i think I need is a way to point one of my node content types to the panel.  Does this make sense.  I love Drupal, but sometimes...

The easiest way with the least amount of programming would be do it with css:

body.logged-in .my-menu-name-or-css-class {
  display:none;
}

The most standards compliant way would be to use hook_menu_alter and unset the menu if $user->uid returns true: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu_alter/7

However, in this case you're probably looking at maybe saving 10kb of bandwidth by unsetting the menu vs. just using CSS to hide it.


Overriding data in a block I have a block manually created through the drupal admin panel.

I would like to override it in order to implement in it an array of data with it's corresponding html.

Is there an easy way to do this?

I also could create the block programmatically with the hook_block instead of using the admin panel.

I don't mind doing it either way, which way do you recommend?

you can use array in static block(created through admin panel) also by choosing text format to "php Code". What exactly, you want to achieve ?


Backup and Migrate exclusion recommendations? When doing database backup using Backup and Migrate, what is the reasonable table exclusion strategy?

My first guess was:

Exclude the following tables altogether - leave that listbox with no selection
Exclude the data from the following tables - select all tables that include "cache" word, such as cache_block or ctools_css_cache.

Any comments, any considerations, any recommendations?

I have following tables to exclude data (not to exclude the table altogether):

all cache_* tables
ctools_views_cache
ctools_object_cache
flood
history
queue
semaphore
watchdog
search_index

Usually search_index saves a lot of database size.


Why is the "My account" link shown even if it is disabled? In "Administration > Structure > Menu," I disabled the "My account" link, but the theme is still showing it.

I took the screenshot after disabling the link, closing the overlay, and clicking the "reload" button of the browser; still the link is show, even if it is disabled.
Why is it happening?

If I disable the "Log out" link that doesn't appear anymore.

Why is the "My account" link so special? More importantly, how can I disable it?

This is a known bug and is already discussed a lot:

http://drupal.org/node/1092866

http://drupal.org/node/1197622

Quick fix would be to create a new menu and add that in your template.


Redirect user to prefered language after login After any user logs in, I want to show all users the same page, but in their prefered language. So, I want to redirect the user to the page URL with the language appended, like http://example.com/pt or http://example.com/en.

What is the best way make this redirect?

You can use the hook_user_login which is called after a user successfully log in to the website. This hook passes the user object as an argument that you can use to retrieve the user language.

For the languages, you can make use of the language_list, which returns an array with the defined languages in your Drupal website. And for the redirect, drupal_goto does the job.

Here is some sample code that could help you further:

function YOURMODULE_user_login(&$edit, $account)
{
    // retrieve user language
    $user_language = $account->language;

    // don't do anything if no language is defined
    if (!$user_language) {
        return;
    }

    // verify if language exists
    $languages = language_list();
    if (!isset($languages[$user_language])) {
        return;
    }

    // verify if language is enabled
    if (!$languages[$user_language]->enabled) {
        return;
    }

    // redirect to preferred language homepage
    drupal_goto('<front>', array(
        'language' => $languages[$user_language],
    ));
}


Resizing the Height of 2 blocks to always be the same depending on block with most content I have two blocks based off views on the home page of my site:

block-views-featured-resource-block
block-views-featured-resource2-block

I want them to be the same height as each other on the home page ALWAYS. They are both drawing from nodes. The nodes for each has a description field. And it varies depending on which node is set for the home page, so the length of the description for each changes regularly.

I want each block to expand in size to fit whatever contents are in the description field (might be one sentence or multiple paragraphs) for the node, and I want them both to resize based on whichever of the two has the most characters of content to the same size (one might end up having a bunch of white space below it, but that's ok.

Right now I have them set like so:

block-views-featured-resource-block,
block-views-featured-resource2-block {
    min-height: 350px;
    position: relative;
}

But of course this only resizes each to fill whatever contents are in each block separately...so if the content takes up more than 350px of space one might be larger than the other. I also tried adding clear: both to the above and overflow: auto but neither of those seemed to help.

Anyone know of a way to do what I want with css?

There's plenty of equal height jquery plugins out there.

jquery-match-height and jQuery.equalHeights are two plugins that you can use, but there's others just google it up and you'll see for yourself.

Beyond that it's just a matter of integrating the plugin to your theme.


Exclude the current node in a view with related items in case of multiple contextual filters Excluding the current node from a display with related items is fairly straight forward. However, in my case there's already another contextual filter (NID) in the game for other purposes.

Adding the exclude functionality on the existing contextual filter isn't working, so I guess an extra contextual filter should be applied in this case. However, simply adding another contextual filter (NID) that's configured to exclude the current node results in no items at all (that moment when you're confronted with the lack of grouped AND or NOT filters for contextual filters).

This situation doesn't feel very unusual to me, so I guess there must be a correct approach for this. My guess is that something must be done with the already existing contextual filter, but can't seem to figure out what exactly.

Can anyone help?

What are the "other purposes" of the first nid contextual filter? Are you taking in the current nid in order to build a relationship to something like a taxonomy term to then get other nodes in the same term?

If so, then the contextual filters should be using different relationships.


Create a Json view of the user, with the format of the user/login response I'm in Drupal 8.
After activating the module rest, and try and receive a response from the route /user/login?_format=json I get this:

{
    "current_user": {
        "uid": "4",
        "name": "cravushedal"
    },
    "csrf_token": "49TlM-VLnQcErR1W5vW7losJPLHXPpqE2UpLh9_bZzg",
    "logout_token": "fkBNWh8iLoTbXPO4Elha86PVe_0I8L1JKIxXQ2KemMo"
}

Now I want to craete a view with all the users, but something like this:

{
    "current_user": {
        "uid": "3",
        "name": "blablabla"
    }
}
{
    "current_user": {
        "uid": "4",
        "name": "cravushedal"
    }
}

In my rest view, I have the name, uid, and a Global custom text. The name and the uid are hidden, and I am calling both fields in the global custom text.
This is my result:

[{"current_user":"1josue"},{"current_user":"2slucuthivili"}]

It doesnt recognize the label, so I had try to include them manually, but the json add \n or \what ever and that destroy my json.

Any idea about how can I achieve this?? thanks!

When you query /user/login it defaults to currently logged-in user.

I suppose you need to create a view with a "REST export" display. The view defaults to "Entity" row style, change it to "Fields".

In "Fields" settings, you can rename the labels that are output in "Alias" fields:

In this "REST Export" view you will have set a path. i.e. /rest/people

Querying /rest/people?_format=json should output something like this:

[
  {
    "user_name": "admin",
    "user_id": "1",
    "user_customtext": "Custom text"
  },
  ...
]

You can use the Global - Custom text field to concat multiple fields as tokens, then hide those fields from being displayed:


How can I copy block placements and settings between themes? How to copy blocks placement and settings between themes? suggests that, in Drupal 7, I could run the following two SQL queries to copy block placements and settings between themes.

DELETE FROM block WHERE theme = 'NEW-THEME'

INSERT INTO block (module, delta, theme, status, weight, region, custom, visibility, pages, title, cache, i18n_mode) (SELECT module, delta, 'NEW-THEME', status, weight, region, custom, visibility, pages, title, cache, i18n_mode FROM block WHERE theme = 'OLD-THEME')

What is the equivalent query/method I could use to achieve the same task in Drupal 8?

Drupal 8 block settings are in configuration files.  It is possible to transfer them but takes a bit of editing / file renaming.

You first have to do a complete export of the configuration files.  In this, the ones you are looking for have names like block.block....yml, e.g.: block.block.old_theme_main_menu.yml

First step is to rename these to block.block.new_theme...yml, e.g : block.block.new_theme_main_menu.yml.  Generally a quick bit of editing to create a script to do the renaming is the easiest.

Next, you need to change the internal theme references to the old theme to the new theme.  E.g. the old theme yml file will look like:

langcode: en
status: true
dependencies:
  config:
    - system.menu.main
  module:
    - block_class
    - system
  theme:
    - old_theme
third_party_settings:
  block_class:
    classes: ''
id: old_theme_main_menu
theme: old_theme
region: navigation_collapsible
weight: -34
provider: null
plugin: 'system_menu_block:main'
settings:
  id: 'system_menu_block:main'
  label: 'Main navigation'
  provider: system
  label_display: '0'
  level: 1
  depth: 2
visibility: {  }

A good editor should be able to do a replace in files to change old_theme to new_theme.  Double check that your theme names are unique in these files.

If the new theme does not have the same regions, then you will need to figure out how to change the region: setting to match your new theme.

In your new theme, create a config directory in the root and then an install directory under it.

Put all the yml files in the install directory.

Uninstall / re-install the new theme to import the settings here.

This assumes the same site with the same code / custom blocks.

If you are going to use this theme in a new site, you will have to make sure the site will provide the blocks defined in the yml config.  Generally, the install directory is used to place system level blocks (e.g main menu) that core provides.  But if you set up a system with a distro or manually to provide other blocks, this works as well.

There may be some minor gotcha's like visibility settings using the wrong node id and the like.


Node reference solution for a content type which referenced to two fields. (company, product & review) My website has three content types: company, product & review.

1). The product has a field referenced to a company node using Node URL Reference module.

2). The review has two fields, one referenced to company node, another referenced to product node.

The question is how to implement the item 2) following the behaviours described below:

While creating review node from company node, the product field should be updated to the products which belongs to that company.
While creating a review from product node, the company & product fields should be auto-filled.

Could you help me? I research this issue for several days but haven't resolved completely. Thanks a lot.

Try entityreference_prepopulate

This will allow you to create a link with query string to pre-fill selections on an entity reference form field.


Multiple Themes per site I want to include a whole new theme into a site to run along side the existing site on new pages (which make up another 'site' on this installation)
.
I have thought that I could just create new page templates prefixed with the new site name within the existing theme and it would all be seperate, but I didn't think about the stylesheets and scripts in the theme.info file.

I want to use completely new html, js, and css as the current stuff is horrible (I can just not render the current scripts and css, but I am wondering if there is a better way.). I also want to avoid unnecessary impact to the current installation as there are already 3 sites running on it.

Is this the best way to add another simple site to an existing Drupal installation?

The ThemeKey module may be able to accomplish what you're looking to do.

The granular control it gives you as to when to show a specif theme is very impressive.


Run DB query and fetch fields in block--block--ID.tpl.php I need to run Database query and fetch the fields in my block named block--block--45.tpl.php.

How can I get subdomain table field values to my block tpl(block--block--45.tpl.php) file?

I tried this code in my block tpl file and its not working : $subdomain = db_query("select subdomain from {subdomain} where sid = :sid limit 0, 1", array(":sid" => $node->uid))->fetchField();

So anyone suggest an easy way to get subdomain table field values to my block tpl file.

It sounds like you want to enable Tokens on your site and use a token to show the subdomain name in your block, after adjusting the Input Format for the block.

There really isn't coding involved, unless the subdomain module does not provide token support (then implement hook_token_info).


"Undefined index: #parameters" and other error in custom module Original question at the bottom. Quick summary, I needed a way to remove the comma character from views exposed filter queries. Below, I was given an example of custom module to do this using validation, which I used and barely modified. However, I'm getting the errors:

Notice: Undefined index: #parameters in search_helper_form_alter() (line 6 of /Applications/MAMP/htdocs/drupal-7.12_old/sites/all/modules/search_helper/search_helper.module).

Notice: Trying to get property of non-object in search_helper_form_alter() (line 6 of /Applications/MAMP/htdocs/drupal-7.12_old/sites/all/modules/search_helper/search_helper.module).

Since I've never written a module before, I'm not sure how to interpret these errors. I'd really appreciate any suggestions. Here's the code.

<?php
function search_helper_form_alter(&$form, $form_state, $form_id) {
    switch($form_id) {
        case 'views_exposed_form':

        if ($form['#parameters'][1]['view']->name == 'views_exposed_form_address_search_page') { // name of the view
            // display array, you have to enable devel module
            //$output .= dsm($form);

        $form['#validate'][] = 'no_commas';
   }
  break;
 }
}
function no_commas($form, &$form_state) {
  $form_state['values']['d'] = preg_replace(",", ' ', $form_state['values']['d']);
}
?>

Original question: I've been trying to set up a location search using views exposed filters and various methods of storing information. The problem inevitably arises that users obviously will want to search for a location using a comma (San Diego, CA or Portland, OR), but the comma isn't stored with the locations anywhere. So, if they search for San Diego or they search for California it works fine, but when they search for both using comma separation, they query returns no results. Is there a way to remedy this? The best way to do this, it seems, would be to ignore the comma within the query somehow. It's been driving me crazy for quite some time now how to get this working. Any help would be appreciated.

You could write a small custom module that -

Form alters views exposed filter form of the particular view in question
Add a new validate function to the form above (validate function is called before the actual form submit function is called and allows you to manipulate values)
Then in the validate function you could edit the particular exposed filter form field replacing commas with nothing.

Here is a sample code that I found on Googling around - http://drupal.org/node/716420#comment-2634540

Hope this helps.


Views with tables have different column width with same setting I'm having problems with drupal views. I used a table to make a list of items with an image, a title and a body each. The first time I tried it it worked perfectly, each column only taking the necessary space but when I tried to recreate it, the title column is very wide. I check all the settings in both the views and the content and they are the exact same.

Here is the first table

And this is what the new ones look like

Do you know why that could be?

Thanks in advance!

I think it is html table generic behaviour, as browser's determining widths of individual table cells are a complicated matter.  You would get the same widths if your columns had the same contents inside but since some columns are different you are getting different column widths.

Drupal views table display style outputs generic tables without any width specified.  You can influence widths by using something like the following in your theme's css

table.views-table td:nth-child(2) {
  width: 150px;
}

Above specifies width for the 2nd TD tag of a views table. Change position of TD and width to your liking.


When should I create a service or a utility function? I had this question in mind along all the last week: When I should create a service or an utility function?

In the Drupal Core we have both Services and Utility functions, but I can't find the distinction between them (when I need to create a service or when I need to create an utility function).

I will take as example the Modules Weight module where I have the InternalFunctions class.

<?php

namespace Drupal\modules_weight\Utility;

class InternalFunctions {

  public static function prepareDelta($weight) {
    $delta = 100;

    $weight = (int) $weight;

    if ($weight > $delta) {
      return $weight;
    }

    if ($weight < -100) {
      return $weight * -1;
    }

    return $delta;
  }

  public static function modulesList($force = FALSE) {
    $modules = [];
    $installed_modules = system_get_info('module');

    $config_factory = \Drupal::service('config.factory');

    if ($force) {
      $show_system_modules = TRUE;
    }
    else {
modules.
      $show_system_modules = $config_factory->get('modules_weight.settings')->get('show_system_modules');
    }

    $modules_weight = $config_factory->get('core.extension')->get('module');

    foreach ($installed_modules as $filename => $module_info) {
      if (!isset($module_info['hidden']) && ($show_system_modules || $module_info['package'] != 'Core')) {
        $modules[$filename]['name'] = $module_info['name'];
        $modules[$filename]['description'] = $module_info['description'];
        $modules[$filename]['weight'] = $modules_weight[$filename];
        $modules[$filename]['package'] = $module_info['package'];
      }
    }
    uasort($modules, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);

    return $modules;
  }

}

In this class I have two static functions but they are both utility functions or prepareDelta() is an utility function and modulesList() should be in another class and have a service?

The only difference that I found at this time is that inside the namespace Drupal\Component\Utility (where you will see a lot of utility fucntions) none of them use inside a service and usually a service use another services inside (I don't have review all the services to validate this).

So, when I should create a service or an utility function?

Ken Rickard from Slack Drupal #contribute channel says: "I would
  create a service if you expect other modules (or other developers) to
  interact with that code. Utility methods are just private shortcuts
  for yourself."

Yes, a cool thing about services is that anyone can overwrite them. So if you want to give other people the ability to customise a particular piece of code.
See Altering existing services, providing dynamic services.

In addition, you should make it a service if you need to do Mock test for PHP Unit testing. See Services and dependency injection in Drupal 8, see Unit testing more complicated Drupal classes.

Q & A:

Service unit test

Writing unit tests for a method that calls static methods from another class


Remove facets from breadcrumb I'm using FacetAPI-SearchAPI and I notice that, on every view based on search api in the breadcrumb there is the "all items" link and, when I add a facet to the search, the facet value is added to the breadcrumb.

Is there a way to remove "all items" and other facets elements from the breadcrumb?

In /sites/all/modules/facetapi/plugins/facetapi/url_processor_standard.inc there's a function setBreadcrumb() (around line 61).

Simply comment it out or put a return; on line 62.

A better way is to create your URL Processor which implements FacetapiUrlProcessor::setBreadcrumb()


How to put icon in field label? Is it possible to add an icon in front of a field name?

I have a field name called Tel and would like to put a phone icon in front of it?

I've searched for a while and can't seem to find an answer to this.

Use Font Awesome classes to add the icons for the field label.


"Undefined index: preview_image_style" I have this error message, which I know is related to the multiupload_filefield_widget  module. If I disable this module, the message disappear.

  Notice: Undefined index: preview_image_style in image_field_widget_process() (line 381 of /Applications/MAMP/htdocs/my-site.com/modules/image/image.field.inc).

I found this issue]2 which mention this message but isn't fixed yet.

How can I solve this?

The error message doesn't show up if you go to the image field settings and, under Image preview style, select a value that actually exist or None.
For some reason, there are several values in that field that don't match with any file in the filesystem; when the code checks this, it finds no such version of the image and emits an error.


how to specify which region of panelpage can be displayed with php I am using a page--front.tpl for my frontpage.

It overrides a panelpage whice i use for my frontpage.

I can display the content of my panelpage with <?php print $content; ?>

Is it possible to specify which region of my panelpage i can print with php?

Yes, $page['content'] is an associative array. You can pick, which parts of the array you'd like to display. However, I think calling print directly is not the right way. Call the render() function instead:

<?php print render($page['content']['your_section']); ?>


Dynamic footer link based on current url I've got a link to the mobile version of my site in the footer, but I need this link to be dynamic based off the page that the user is currently on.

Shown below are the options I have for the link.

Under the path there is this help text

The path for this menu link. This can be an internal Drupal path such as node/add or an external URL such as http://drupal.org. Enter <front> to link to the front page.

What I need is similar to the ability to use <front> to signify the homepage. I'd like to be able to use something like http://m.example.com/<node> so that this link will always go to the mobile version of the page that I'm currently on.

Is this possible? Or is what I want to do more complex than just using a keyword for the path?

The default menu system won't let you do that...but if you install the Menu Token module you should be able to use a path similar to the following to get what you need:

http://m.example.com/[current-page:url]


Custom formatter for a multi-valued field I have a multi-valued image field and I'd like to use its delta value with the Custom Formatters module. What I want to do would be really simple with html+tokens if it were to work:

However, I don't see the option for the delta value available in the list of tokens available, and using that code would just end up with [node:field_image:0] and [node:field_image:1] being replaced as src=""

Could you please advice me on how to do this? I think I need to use php but I don't know how. Thank you very much!

here a sample for rendering (image) fields but you can easily access to other fields of entity:

$output = '';
foreach ($variables['#items'] as $item) {
  $output .= theme('file_link', array('file' => (object) $item));
}
return $output;

Another line example for manual image rendering:

$output .= '<img typeof="foaf:Image" src="'.image_style_url('YOUR_IMAGE_STYLE', $your_entity->your_field['und'][0]['uri']).'" alt="'.$your_entity->your_field['und'][0]['alt'].'"/>';


How do I set cron using performance page? I am not able to set up the performance setting for cron duration, and automatic cache clearing setting in admin performance page.

I am not able to find the exact issue. I am clearing the cache manually everyday currently.

Can anyone provide better solution for this?

I changed the settings, and clicked on the save button of the form,but settings are not saved. This happen with both cron and cache duration settings.

Please go to Cron Settings (http://example.com/drupal7/admin/config/system/cron) to set it, default is 3 hours.


What is module dependency? I see that modules can have dependencies on other modules.

Why is this, and how might I use this in my own custom module development?

Module dependency can be defined as follows.

If a module A requires that module B to be enabled before the module A is enabled then, module A is dependent on module B.

In other words, if module A uses some of the functions that are available or defined in module B then it becomes mandatory to enable module B prior to enabling of module A, as not doing so may result in a "call to undefined function error"

Dependencies are very useful as it may save lot of your development time by allowing you to use functions that are already available in other modules, instead of rewriting the function in your module.

A module's dependencies are mentioned in the module's .info file. Following is an example from the forum module

name = Forum
description = Provides discussion forums.
dependencies[] = taxonomy
dependencies[] = comment
package = Core
version = VERSION
core = 7.x
files[] = forum.test
configure = admin/structure/forum
stylesheets[all][] = forum.css

The lines :

dependencies[] = taxonomy
dependencies[] = comment

declare or make the forum modules to be dependent on the 'taxonomy' and 'comment' modules. We can also say that the 'taxonomy' and 'comment' modules are the dependencies for the forum module.

In your module A you can add dependencies for module B and module C by adding the following lines in the a.info file of your module A .

dependencies[] = b
dependencies[] = c


How do I check the logged-in user username/password/role using a function to validate them? I am allowing users to register an account on my site. They get a specific role using user_save().

When they log in for the first time, I have to verify the login credentials.

Is there a function to verify the login credentials?
Is there a function to get the user roles?

To check login credentials in Drupal 6&7:

$uid = user_authenticate($username, $password);

In Drupal 8:

// Inject user.auth service..
$uid = $this->userAuth->authenticate($username, $password);
// or
$uid = \Drupal::service('user.auth')->authenticate($username, $password);

To check roles:

/**
 * Check User roles
 * @param $role
 * @param null $user
 * @return bool
 */
function user_has_role($roles, $user = NULL) {
  if ($user == NULL) {
    global $user;
  }
  if (!is_array($roles)) {
    $roles = array($roles);
  }
  if (count(array_intersect($roles, $user->roles))) {
    return TRUE;
  }
  return FALSE;
}


Parse REST Json replay I  create a views with REST export display, result are serialized with Json,

In my formBuild method  I want to parse JSON and Convert it to array and use it in select option

    $host = \Drupal::request()->getHost();
    $response = \Drupal::httpClient()
        ->get($host.'/get/slider' );

    $json_string = $response->getBody()->getContents();
    kint($json_string);

I see Symfony serialize class and find Deserialize method with this example

 $person = $serializer->deserialize($data, 'Acme\Person', 'xml');

According to this,I guess maybe I should something like

     $results = $serializer->deserialize($json_string, '???', 'josn');

but what I should write in second param(???)?
I try

    $serialize = new Serializer\Serializer();
    $json_string = $response->getBody()->getContents();
  $entity = $serialize->deserialize($json_string, '\Drupal\node\Entity\Node::class', 'json')  ;

but face me with error Symfony\Component\Serializer\Exception\UnexpectedValueException: Deserialization for the format json is not supported in Symfony\Component\Serializer\Serializer->deserialize().

And if you have better solution  tell me
How Can I deserilized views REST results?

update
Also,I tried

    $json_string = $response->getBody()->getContents();
    $serializer = \Drupal::service('serializer');
    $deserialized = $serializer->deserialize($json_string, \Drupal\node\Entity\Node::class, 'json');

but Symfony\Component\Serializer\Exception\UnexpectedValueException: A string must be provided as a bundle value. in Drupal\serialization\Normalizer\EntityNormalizer->denormalize()

Drupal has a service for serialisation, pre-configured with the normalisers and encoders you need. The error you currently have is because you're not setting up the instance of the serialiser with the Symfony\Component\Serializer\Encoder\JsonEncoder, but you'll also need, for example, the Drupal\serialization\Normalizer\ConfigEntityNormalizer normaliser.

This code works well for me:

$serializer = \Drupal::service('serializer');
$node = \Drupal::entityTypeManager()->getStorage('node')->load(1);

$output = $serializer->serialize($node, 'json');
$deserialized_node = $serializer->deserialize($output, \Drupal\node\Entity\Node::class, 'json');

As always, inject the services if possible.