How to customize the data retrieved by a REST call? I've enabled the REST server (plus services) and can retrieve user profile data at www.example.com/endpoint/user/123

How can I customize the data that's being retrieve? I want to not include the email address and add a couple of other fields.

When I make a login request at www.example.com/endpoint/user/login I would like to have those additional fields included as well.

All you need is to define your Resource, take a look at files in site/all/module/services/resources, you can find some examples, but for simplicity I will take you and example:

endpoint_user moduel:

endpoint_user.info file:

name = endpoint_user
description = endpoint_user
core = 7.x

endpoint_user.module file:

<?php
function endpoint_user_services_resources() {
  $endpoint_user_resource = array(
      'endpoint_user' => array(
          'retrieve' => array(
              'callback' => '_endpoint_user_resource_retrieve',
              'args' => array(
                  array(
                      'name' => 'uid',
                      'optional' => FALSE,
                      'source' => array('path' => 0),
                      'type' => 'int',
                      'description' => 'The uid of the endpoint_user to get',
                  ),
              ),
              'access callback' => '_endpoint_user_resource_access',
              'access arguments' => array('view'),
              'access arguments append' => TRUE,
          ),
      ),
  );
  return $endpoint_user_resource;
}

function _endpoint_user_resource_access($op = 'view', $args = array()) {
  return TRUE;
}

function _endpoint_user_resource_retrieve($uid) {
  $endpoint_user = user_load($uid);
  $endpoint_user->custom_field = 'Mohammad Ali Akbari';
  if ($endpoint_user) {
    $uri = entity_uri('user', $endpoint_user);
    $endpoint_user->path = url($uri['path'], array('absolute' => TRUE));
    // Unset uri as it has complete entity and this
    // cause never ending recursion in rendering.
    unset($endpoint_user->uri);
  }
  return $endpoint_user;
}

then create new Service in admin/structure/services and select endpoint_user.

open your browser and go to your service URL, like endpoint/endpoint_user/1

you will see:

<custom_field>Mohammad Ali Akbari</custom_field>

This result comes from $endpoint_user->custom_field = 'Mohammad Ali Akbari'; in _endpoint_user_resource_retrieve


How to use Views Isotope in Commerce Kickstart? I want to do the same as what is shown in the video about the Views Isotope module, but within Commerce Kickstart (CK).

Gareth Hall, shows us how to drupal 7. I've done the same for CK, but I can not get that purpose, that is, not filtered. I click on the tags and does not give any effect or filter.

I thought it might not be compatible with CK or perhaps is making a conflict with some jQuery or something out there.

Please any suggestions?

Update:

I installed the module View Isotope
I activated "Isotope Example" and "Views Isotope" modules
I created two views (and filter for content) as explained in the video.
I have also used the version "Isotope Example", for that I have added content in "tags" and "articles".

And still the same. does not filter anything.

Now, also I have since only a new version of Drupal 7 (without CK). For this I needed to install/activate other modules, such as: Features (enabled), Image (enabled), File (enabled), Field (enabled), Field SQL storage (enabled), Taxonomy (enabled), Options (enabled), Views (enabled ), Chaos tools (enabled), Views Isotope (enabled), jQuery Update (enabled), Libraries (on)

And still the drawback.

I am convinced that something is missing but I do not know why.

Any help?

Views Isotope works fine with Drupal commerce. (I'm using it now =-)

Make sure you have the isotope .js file in the correct location within libraries: sites/all/libraries/jquery.isotope/jquery.isotope.min.js

also when creating the View make sure (as the above video briefly covers) that the 'Taxonomy Term: Name' in the Views Isotope filter block has the 'link this field to its taxonomy page' option turned off (5:25 time in the YouTube tutorial you posted). If it is on the links wont work.

And of course as video stresses in the main Isotope View, make sure the last field in the list is the taxonomy field that is linked to the header block. IF you need to display that taxonomy also create two fields in the view and make sure one of them is last with the correct CSS overwrite styling as the video tutorial states.

Oh and lastly, make sure your Views' Ajax option in the advanced tab is turned off. It conflicts with Isotope and wont work.


Author image in comments twig I succesfully get user name, surname and date to render in comment.html.twig like this

function MYTHEMENAME_preprocess_comment(&$variables) {
    $comment = $variables['comment'];
    $variables['user_name_comment'] = $comment->getOwner()->field_first_name->value;
    $variables['user_surname_comment'] = $comment->getOwner()->field_last_name->value;
    $variables['created'] = \Drupal::service('date.formatter')->format($variables['comment']->getCreatedTime(), 'conference_date');
}

In node template i got field_picture to render like this

$variables['author_picture'] = $node->getOwner()->field_picture->entity->url();

But i can't get my field_picture from user to render in comment twig file. I try to show the author's picture of every comment.

Any ideas?

When you want to display an entity field based on the "Manage Display" settings, you should go just {{ content.my_field }}. If you "kint" content (var dump it) you can see that each content field element has also "theme" key/property, which tells twig how to render that field


How to edit live theme .info file (localhost) I'm currently building a custom theme from the ground up on drupal on localhost.

At the moment I've managed to add my theme and run my custom templates succesfully. However I can't get it to pick up my CSS or JS files.

These were the lines in my .info file

stylesheets[all][] = /css/main.css
scripts[] = javascript/javascript.js

However I got an error in the console saying:

'GET http://localhost/drupal/css/main.css 404 (Not Found)'

So I modified the path of the css and js files to something like this:

stylesheets[all][] = sites/all/themes/THEMENAME/css/main.css

Yet it still can't find it. I'm not sure what's going on. Has the .info file been cached?

May be the problem is of / present at the starting in your first attempt(/css/main.css), try once with:

stylesheets[all][] = css/main.css

Note: Clear the cache and check if it works.

Also you can check the following links if it helps:
https://drupal.org/node/171205
https://drupal.org/node/171209


How to truncate a given menu setting an expanded menu item as the root menu in drupal 7? In my template preprocess html and page hooks, I test the current page of being a certain kind of node, set by the menu structure. Given such a menu:

main menu

link 1
link 2 (specials)
> link 2.1
> link 2.2
link 3

Every node which menu's link has the menu parent link 2 gets a treatment. On those nodes, I also want to only show all links inside link 2 menu, so start the main menu from that, so basically the main menu would then consist of link 2.1 and link 2.2. How would you do that?

function mytheme_preprocess_html(&$vars) {

    $special = is_special_page();

    if ($special) {
        // alter menu
    }
}

function mytheme_preprocess_page(&$vars) {

    $special = is_special_page();

    if ($special) {
        // alter menu
    }
}

function is_special_page($node) {
    $breadcrumbs = drupal_get_breadcrumb();
    $businessMatch = preg_grep("/(specials?)/i", $breadcrumbs);

    return (count($businessMatch) > 0);
}

I've figured it out myself, felt like sharing:

<?php
function _themename_submenu_tree_all_data($menu = 'primary-links', $mlid, $subonly = false) {
    $tree = menu_tree_all_data($menu);
    $childtree = null;

    /*
        thanks Jari http://stackoverflow.com/questions/19112294/how-to-extract-an-array-that-has-a-given-structure-and-whichs-key-value-matc/19112508?noredirect=1#comment28260688_19112508
    */

    function recursiveSearch($array, $key, $value){
      foreach($array as $sub){
        if ($sub['link'][$key] == $value)
          return $sub ;

        if (!empty($sub['below'])){
            $returned = recursiveSearch($sub['below'], $key, $value);
            if ($returned !== null)
                return $returned ;
        }
      }

        return null ;
    }

    $childtree = recursiveSearch($tree, 'mlid', $mlid);

    if ($subonly && $childtree != null) $childtree = $childtree['below'];

    return $childtree;
}

/**
 * Implements hook_preprocess_page().
 */
function themename_preprocess_page(&$vars) {
    if (arg(0) == 'node' && arg(1)) {
        $nid = arg(1);
        $node = node_load($nid);

        $vars['type'] = $node->type;

        // your internal check to see if the menu needs to be truncated

        $isbusiness = _themename_is_business_page($node);

        if ($isbusiness) {
            $trail = menu_get_active_trail();
            $mlid = $trail[ count($trail)-1 ]['mlid'];

            $sub = _themename_submenu_tree_all_data('main-menu', $mlid, true);
            $sub = menu_tree_output($sub);

            $vars['page']['main_menu']['menu_block_2']['#content'] = $sub;
        }
    }
}
?>


Drupal Commerce: how to add "Middle name" field to the "Address" pane? Currently for "Address" pane (field named "commerce_customer_address") available two options:

1) Name (First name, Last name)
2) Name (single line)

In my country middle name is very important. How to add this as separated field from custom module?

To Rayan: By the way, does it make sense to include this option in the Commerce core?

You can add the field under store -> customer profiles -> profile types -> Billing Information -> Manage Fields (Or go to admin/commerce/customer-profiles/types/billing/fields)

You can add any additional fields there. You can't add any fields directly to customer_commerce_address, but if you add any fields under the Billing Information they will show up during checkout.


Create two nodes from webform submission I have webform with many fields.
And I need to create two nodes after webform submission.
First node would have some values from the webform.
And second node would have other values from the same webform.

How can I do this?
(rules? hooks?)

Would be using Webform Default Fields or Webform report the right solution?

I would recommend Rules.

Here's a link. Using webform rules to create node after webform submission

Hope that helps.


Code inside attached behavior not executed I nested jQuery code inside a behavior. I don't understand, why the code does not execute. I would be appleased if you could give me a hint on what I probably did wrong.

My code:

   $(function (){
    Drupal.behaviors.block_sidebar_register_buttons = {
        attach: function (context, settings) {
            var element = $('#block_register_buttons');
            //...
        }
    };
});

Drupal disables the $ namespace for jQuery, to avoid potential conflicts with other libraries. Therefore the wrapping $() DOM-ready-function will neither be executed, nor can the $('#something') selector be used inside. Wrap your behavior with this instead:

(function ($, Drupal) {
  //inside the wrapper you can use the usual jQuery $ notation
  Drupal.behaviors.block_sidebar_register_buttons = {
    attach: function (context, settings) {
      var element = $('#block_register_buttons');
      //...
   }
  }
}(jQuery, Drupal));


How to direct user to a custom path after executing a Views Bulk Operations action? I have created a custom action as described at https://www.drupal.org/node/2052067. My question is how to direct the user to a custom path after executing the action?

Its like altering normal form using hook_form_alter:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_MYVIEW_page') {
    $form['#action'] = '/my/target'; // the url that is displayed when in VBO multistep

    if (!empty($form['actions']['submit']['#submit'])) {

      if (in_array('views_bulk_operations_form_submit', $form['actions']['submit']['#submit'])) {
        $form['actions']['submit']['#submit'][] = 'MYMODULE_vbo_redirect';
        $form['actions']['cancel']['#href'] = 'my/target';
        $form['actions']['cancel']['#options']['path'] = 'my/target';
        dpm($form);
      }
    }
  }
}

function MYMODULE_vbo_redirect($form, &$form_state) {
  $form_state['redirect'] = array('my/target');
}


create two different registration form with same fields without using profile2 I have already setup account fields, and I have two roles (A) and (B)
I need to create a page with two button links :

register as (A)
register as (B)

when the user choose one of these two links, he will go to the registration page
and after filling the form, he will be registred and automatically get the role (A) or (B) pursuant the link chosen above

the problem is: how can I pass the info of what choice the user has chosen (first or second link) to the registration form.

I thought to pass it inside the request URI and then get it via $_GET but Is there another solution wihtout showing any query to the user in the URL ?

Thanks in advance.

Well you can make small form with 2 submit buttons (Register as A, Register as B) and post that data on register form, in this way you can hide it from url

OR

The other way which is more complicated, using ajax, when link is clicked and based on the clicked link you create the $form_state and set the flag then you call the register from using drupal_get_form and you pass the argument

OR

Just create boolean field in user, and put the option (Register as A, Register as B) and make it required to be listed in register from


Migrating multiple values into a single file field in Drupal 7 with Migrate 2.2 I have a file field that can have multiple downloadable files for an image node type. These images will have several versions (psd, jpg, eps) that will be downloadable. I would like to be able to append multiple values to this field. How would I do that when they are coming from multiple source columns (i.e. eps_filename, jpg_filename, psd_filename)?

I found related documentation here: http://drupal.org/node/1012810 But that documentation is for taxonomy terms where the details of the value can simply be a string with a separator. For this I am using MigrateFileFieldHandler::arguments(), so I can't just give it a separator.

Further what I would like to do is also be able to come back later and append more files to the migrated nodes. This is because the larger files will take longer to get on the server, so their smaller counterparts (jpg, png, etc) will be loaded first and then adding the eps files later. Now I already figured out how to update the previously migrated nodes using systemOfRecord. But I am not sure how to append to a multi-value field.

I am using Drupal 7 and the Migrate module version 2.2. Here is some sample code I am using for migrating the data initially into the file field.

$jpg_arguments = MigrateFileFieldHandler::arguments(NULL,
  'file_link', FILE_EXISTS_RENAME, 'en', array('source_field' => 'jpg_name'),
  array('source_field' => 'jpg_filename'), array('source_field' => 'jpg_filename'));

$this->addFieldMapping('field_file', 'jpg_uri')
     ->arguments($jpg_arguments);

I suspect the trick is using the prepareRow() function. But so far I have not been able to get that to execute yet.

Any ideas? I really appreciate any help.

Thanks!

I think what you need is prepareRow. Here is code from the migrate baseball example where multiple fields are merged into a single array field.

 function prepareRow($row) {
    // Collect all the batters into one multi-value field.
    for ($i=1; $i <= 9; $i++ ) {
      $key = "visiting_batter_$i";
      $visiting_batters[] = $row->$key;
      $key = "home_batter_$i";
      $home_batters[] = $row->$key;
    }
    $row->visiting_batters = implode(',', $visiting_batters);
    $row->home_batters = implode(',', $home_batters);
    $row->title = "$row->home_team vs. $row->visiting_team. " . gmdate('M d, Y', strtotime($row->start_date));
  }

(from the file migrate_example_baseball.migrate.inc)

However I have been having mixed results with prepareRow in my own code, so while this looks straight forward I can't guarantee that it will work.


datetime field default gets truncated I have a datetime field on a custom entity defined in baseFieldDefinitions().
This has set a default, which should be now.
But when saving the entity, i get following error:

  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'date' at row 1: INSERT INTO {sale} (uuid, langcode, user_id, name, status, created, changed, date, price, party) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 3e25c5cb-0092-42dd-914b-4e4b91bdcf19 [:db_insert_placeholder_1] => en [:db_insert_placeholder_2] => 1 [:db_insert_placeholder_3] => Jupiler [:db_insert_placeholder_4] => 1 [:db_insert_placeholder_5] => 1516504047 [:db_insert_placeholder_6] => 1516504047 [:db_insert_placeholder_7] => 2018-01-21 04:07:06 Europe/Brussels [:db_insert_placeholder_8] => 2 [:db_insert_placeholder_9] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->doSaveFieldItems() (line 878 of /var/www/drupalvm/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

This is my field definition:

$fields['date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Sale date'))
  ->setDescription(t('The date that the sale took place.'))
  ->setRequired(true)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'date',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setDefaultValue(DrupalDateTime::createFromTimestamp(time()));

How are datetime fields supposed to get a default value?
If you look at the error, the value it tries to save is '2018-01-21 04:07:06 Europe/Brussels'.

As the BaseFieldDefenitions are cached, this won't work I believe.

I think you would be better off by using SetDefaultValueCallback:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21BaseFieldDefinition.php/function/BaseFieldDefinition%3A%3AsetDefaultValueCallback/8.2.x


How to show single pop-up for whole guest session In my site I want to place a javascript ad code( from Zedo) which is popping up one window for each page visit by the user which is quite nagging.

Ideally what I want is to pop up the ad after user leaves the site or closes the window.

At least I want is to show single pop up in the whole guest session.

I place the ad code before </body> in page.tpl.php but it gets executed for every page.

I'm thinking to make it better by using this logic:

if(time() % 3 == 0)
{
//javascript ad code here
}

At least this will reduce pop up by 3 times.

Are there any better ideas?

You can use one cookie, if is the first time to the user enter into your page then create a cookie, when the user change of page you will check if the cookie exists and if exists don't show up the ad.


What exactly is "Overridden", "Needs review" & "Revert component" in Features? I can see Overridden, Needs review & Revert component in Features.

If I want to get latest updated features always, what I will do?

What drush fr, drush fu will do internally?

What I understood is, overridden is the state where our current config/settings changed with new features. If we do revert component, all the new changes will be reflected. So here what is the drush command shall I use?.

Anyone can explain all these three?

Both needs review and overridden statuses mean that the feature in the database does not match the feature in code. Running "drush fr" (feature revert) will replace the feature in the database with the feature in code.

Now lets see "Revert" vs "Update"

Revert:(drush fr)

This operation changes your site configuration (living in the database) to match up with the definitions in the feature module code.

Update / Recreate:(drush fu)

The update operation will produce a modified version of your feature module, which matches up with the configuration found in the database.

  Remember, revert for Drupal features means copy configuration from
  code into the database.

If you want to go in detail with simple explanation, then please follow below links

Modifying, updating and reverting Features
Revert and update a Drupal feature module


display 2 tables with checkboxes by ajax button I am altering a form and placing a new 'button' . On the press of the button, using the #ajax property , I want to display 2 separate tables with checkboxes for each row. Each table has separate data.

The 2 tables should be initially hidden and should become visible on button press. How should I proceed with this ??

The table data is fetched from database and some operations are performed on it.. so where should I put this code ? In the callback function ?

Update- I tried to implement this by using tableselect, but the checked boxes aren't returning the values in the $form_state['values']. You can check out the code here
 or suggest me a simpler interface to implement.

You should not put the table-building code in the ajax callback. Put the code to build the tables into the hook_form_alter() implementation that you are using to add the button. You can use $form_state['triggering_element'] to tell if the button has been pressed, and only execute the query and build the tables if you need to.


Drupal 8: Pdf (print) search results (search_api) I am using the Entity PDF plugin in Drupal 8, that does a good job in exporting to PDF nodes, but seems to exclude other scenarios such as Search Result list.

Anyone can provide some hints how would a PDF export be implemented for  search results?

You can use hook_entity_view_alter() to hidden PDF export link. Sample

<?php

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

function examples_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity->getType();
  $mode = $display->getMode();
  //Replace node type with text **page**
  if ($type == 'page' && $mode == 'search_result') {
    unset($build['entity_print_view']);
  }
}


How do I create a collaborative webform using Webforms? How can I create a webform that allows users to collaboratively fill out a webform built using the Webform module in Drupal 7?

The users are building their own webforms, which works great to populate text and content. Some forms should allow several users to collaborate on filling them out. Basically, they will be to-do checklists where each user will mark tasks complete. This is a single submission edited by multiple users.

I could write these checklist type forms using the Forms API, allowing the users to maintain the forms themselves has proven much more efficient for getting forms published.

I am open to modules that extend Webforms or even other modules that fit the requirements better. However, I would like to stay with Webforms because my users are already comfortable with it.

I have been able to share a single submission with a role.

First, enable the 'save draft' option in webform Advanced Settings The 'Save Draft' option is here: webform/configure -> Advanced Settings -> Show "Save draft" button

Then, create a role with

'Access all webform results'
'Edit all webform submissions'

permissions. Any user assigned to this role can edit a submission started by another user.

The edit submission link (node/%/submission/%/edit) will be shared with the appropriate team members.


Recreating vocabulary and term pages by using views Let's say I have a vocabulary named "Gallery" and terms inside of it: "One", "Two" and "Three".

Every term have a image field.

What I would like to accomplish:

After going to mysite.com/gallery I would like to have a custom view with grid of images of all terms from specific vocabulary. After clicking an image I would like to be redirected to mysite.com/gallery/[term-name] where I would have another view that would show a grid of specific fields from nodes related to this term.

I think it has something to do with contextual filters? But I'm not sure if it is possible to relate two views that way (so one would have path "/gallery" and other "/gallery/%" and one would dynamically create paths for the other), is it? :/

How would you approach a problem? Even if views wouldn't be valid solution.

PS. The main problem I'm struggling with now is to create a links in one view (/gallery) to other view (/gallery/%) :/ .

Regards!

try to create a views Taxonomy terms, add fields in this order: Taxonomy term: Term ID (Term ID) (enable Exclude from display, Thousands marker None), Taxonomy term: Name (uncheck "Link this field to its taxonomy term page" option, open "SHOW REWRITE RESULTS" fieldset, enable Output this field as a link, in Link path enter gallery/[tid]), this is solution for your PS.


Hide other user comments, but not to admins I have created a node, anyone can able to comment on the node. Now, what I want is:

For Authenticated users, show their own comment only (not other user's comments)
For Administrators, show all comments. (I want them to see all comments)

For this functionality, is there any contrib drupal module available? or else show me a way to do in custom module.

Hidden comment

  Optional field to let users know the reason why a comment is hidden.
  Disallow edit/reply/delete on hidden comments
  Optional permission to allow user to hide personal comments (comments on their own nodes). This permission can not unhidden
  comment.

if you want to do custom edit your node.tpl file add following code:

    global $user
    login_uid = //get user id of commnet
    if ($user->uid == login_uid){
      print render($content['comments']['comment_form']);
     }


hook_user_login not working After user enter email and password. hook_user_login gets triggered and excute below code. I am placing code in "bootstap_business.theme" file like this

function hook_user_login($account) {

$email = $account->geteMail();

echo "Email: $email";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://example.com/users" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "$email" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain','Authorization: ff23fdcffdgh5dsdsds'));

$result=curl_exec ($ch);

}

But i am not getting whether this function is excuted or not. How can i debug/solve this problem.
If i do echo also its not printing anything.

Only alter hooks and some specific theme-related hooks can be implemented in a theme.

hook_user_login isn't one of them, you need to implement it in a module.

To create a custom module see the official Creating custom modules docs. You essentially need a .info.yml file and a single .module file containing this:

function MYMODULE_user_login($account) {
  // Your code here
}


Drush error during adding an install profile as platform In Aegir, I add a platform with a buildfile:

core = 7.x
api = 2
projects[] = drupal
projects[profiler_drupal_base][type] = "profile"
projects[profiler_drupal_base][download][type] = "git"
projects[profiler_drupal_base][download][url] = "git@bitbucket.org:joachimroeleveld/profiler_drupal_base.git"
projects[profiler_drupal_base][download][branch] = "master"

I made an install profile which I pushed to the my public repository containing a .info, .make and .profile file (and the .build file so Aegir can read it).

After a bunch of tasks Aegir succeeded running (including downloading Drupal; the first step of the build file), I get this erors:

Unable to clone profiler_drupal_base from git@bitbucket.org:joachimroeleveld/profiler_drupal_base.git.
Could not download platform using drush make. No platform present

Is something wrong with the structure of my repo?

The solution for me was to use the HTTPS-link instead of the SSL-link.

projects[drupal_development_base][type] = "profile"
projects[drupal_development_base][download][type] = "git"
projects[drupal_development_base][download][url] = "https://joachimroeleveld@bitbucket.org/joachimroeleveld/drupal_development_base.git"
projects[drupal_development_base][download][branch] = "master"


Two Blocks for sort filter Views -- Drupal 7 I have a view in Drupal 7 with results including a field of date and another with price, I need to sort the results by means of these two fields when I click on the appropriate link (not button or dropbox radio), but the trick is I need add the different sort filter into two separate blocks, because each block will have a different per user context.

Besides the filters should be links. Any idea how to work this?

I dun really get what you mean. I presume you are trying let admin or user to able to do sorting.

I have two ideas

Under format change from unformatted list to table. At this case you are able to do sorting by click table header.

Another one is under sort criteria, add any content you want to sort and select expose.

If I wrong, can show me any example??


How to use hook_theme and hook_block_view correctly The following code works - the block_view calls the theme function and the correct variables get passed.

Is this the right way to use these functions when you have a block and you want it themed with variables and using a specific template?

Thanks,

function youtube_pull_block_view($delta = '') {

    switch($delta){

      case 'youtube_pull':
      $block['content'] = theme('popular_analytics', array('videos' => get_most_popular()));
      break;
    }

return $block;
}

function youtube_pull_theme() {

return array('youtube_pull_listing' => array(
             'variables' => array('videos' => NULL),
             'template' => 'youtube-pull-listing',));
}

That code would be perfectly fine, if you define a theme function and use that theme function. In your case, the code is defining the youtube_pull_listing theme function, but using the popular_analytics theme function.

As for an example of hook_block_view() implementation that uses a theme function, see user_block_view(), which contains the following code.

  if (user_access('access content')) {
    // Retrieve a list of new users who have subsequently accessed the site successfully.
    $items = db_query_range('SELECT uid, name FROM {users} WHERE status <> 0 AND access <> 0 ORDER BY created DESC', 0, variable_get('user_block_whois_new_count', 5))->fetchAll();
    $output = theme('user_list', array('users' => $items));

    $block['subject'] = t('Who\'s new');
    $block['content'] = $output;
  }
  return $block;

The fact the theme function is using a template file doesn't make any difference for how the function is called. The only difference is that the variables declared in hook_theme() are the variables the template file will be able to access.

Keep in mind that, in Drupal 7, it is now preferable to return an array in $block['content'], in the same way blog_block_view() does.

  if (user_access('access content')) {
    $result = db_select('node', 'n')
      ->fields('n', array('nid', 'title', 'created'))
      ->condition('type', 'blog')
      ->condition('status', 1)
      ->orderBy('created', 'DESC')
      ->range(0, variable_get('blog_block_count', 10))
      ->addTag('node_access')
      ->execute();

    if ($node_title_list = node_title_list($result)) {
      $block['subject'] = t('Recent blog posts');
      $block['content']['blog_list'] = $node_title_list;
      $block['content']['blog_more'] = array(
        '#theme' => 'more_link',
        '#url' => 'blog',
        '#title' => t('Read the latest blog entries.'),
      );

      return $block;
    }
  }

The reasons why using theme() is bad are given in theme() renamed to _theme() and should not be called directly, even if that change record refers to Drupal 8.

It circumvents caching
It circumvents defaults of types defined in hook_element_info(), including attached assets
It circumvents the pre_render and post_render stages
It circumvents JavaScript states information


How to change image size and position when uploading to article in tb_rave_starter I want to change image size and position
How could this be done, please help me.

To edit the size of the image:

Go to /admin/structure/types/manage/YOUR_CONTENT_TYPE/display and click the edit image style button shown in the image below.

This will open a drop down and then you can choose the image size you want:

To change the location of the image you have several options...

You can edit your themes CSS file, however this will require understanding the underlying HTML and CSS.

An alternative is to use a module like Panels that allows you to create custom layout and apply them without actually doing any coding. I've not actually used it before myself but have heard good things about it and there are lots of tutorials online - just Google it.


How to link (a menu item) to the RSS feed? In our Drupal installation there is a menu item for the RSS feed, pointing to path de/rss for the German feed.

This path appears unchanged in the frontend and is invalid, hence results in a 404.

The correct URL is /de/rss.xml or just /rss.xml.

Weird thing is, that Drupal accepts the non-working path, while it rejects the correct ones:

  The path 'de/rss.xml' is either invalid or you do not have access to it.

What's going on?

Note: I'm using the i18n module. And when I call /de/rss.xml it gets redirected to /rss.xml.

If you're using i18n module, and after you have installed module Variable, you should enable the i18n_variable module (one of the i18n submodules that requires the Variable module, among others).

Then navigate to /admin/config/regional/i18n/variable (= the Variables tab within '
Multilingual settings'). There you'll be able to specify all sorts of variables for which you want multi language support enabled also, using an appropriate sub-tab there, such as for "Site information", "Menu settings", etc.). Within sub-tab other, there is also "RSS feed for front page" (=The RSS feed for the front page, default is rss.xml). That "other" sub-tab should be between "Menu Settings" (1st sub-tab) and "Site Information" (3rd sub-tab).

I'd be curious to hear if your issue is resolved after you enable that option (by checking the checkbox).


geofield types failed to add with commerce services I have added field of type Geofield  that failed to save through services despite working well with node and user modules

It returns that error 400 : Invalid field_geoloc value given I am using the same field structure for node and user.

I did some debugging and found that the error comes from file commerce_services.module line 1406
that piece of code

if (count(array_diff_key($value, $field_info['columns'])) > 0) { return services_error(t('Invalid @field value given', array('@field' => $field_name)), 400);
    }
here is the field structure

"field_geoloc": {
    "und": [
        {
            "geom": {
                "lat": "22",
                "lon": "22"
            }
        }
    ]
}

Please help me fix it or guide to fix it.
Thanks in advance

The answer is to send computed values via the geofield module api itself by Implementing the hook_request_parsed_alter like:

function my_module_request_parsed_alter(&$data, $controller) {
switch ($controller['callback']) {
case 'commerce_services_product_create':
case 'commerce_services_product_update':

  if (isset($data['field_geoloc'])) {
    $data["field_geoloc"] = geofield_compute_values($data['field_geoloc']['und'][0]['geom']);
  }
}

But I still wonder why not working by default as node create request


How to correctly start a website using Git/Drush/Composer workflow? I am trying to follow this article to start a D8 site:
https://www.drupal.org/node/803746

The article is for D7 but I think there are no much differences.

These are the steps I followed so far:

Cloned Drupal 8.2.x repository to my dev environment
Branched to 'my-project'
Created a remote repo, replaced it as my 'origin' and renamed Drupal.org to 'drupal'.
copied the example .gitignore as is, it by default ignores settings.php and vendor folder.
Ran composer install at root
Installed Drupal to local MySQL instance (after settings up Apache)
Committed and pushed files of the entire site to repository
Created staging environment and cloned from repository
Copied settings.php, dumped dev database and re-imported it to staging, and re-ran composer install at staging environment
I ran drush rebuild to refresh cache.

I expected this to be all and now the staging environment should be up and running, but it is running with now style, apparently the themes are not correctly copied.

So my first question is what did I miss, do I have to use composer to install core themes?

My second question is, do I have to re-install any additional theme or modules using composer on all sites? Or in other words, why is it a good practice to git-ignore vendor folder rather than install once on dev env and pull dependencies from repository?

Below is a screenshot for how staging main page looks like:

[EDIT]
Checking the /admin/reports/dblog page, these was the warning that appeared a lot:

warning: file_put_contents(temporary://filexmZMo3): failed to open stream: "Drupal\Core\StreamWrapper\TemporaryStream::stream_open" call failed in file_unmanaged_save_data()

Because my dev environment was Windows and the staging environment was Linux, the temporary folder differs.

I had to fix it using the admin pages of the file system.

Later I found that I will need to do this every time I use drush config-import so I decided to overwrite the value in settings.php as following:

$conf['file_temporary_path'] = '/tmp';


path issue with translated (entity_translation) nodes I use Drupal 7, entity_translation and pathauto with 2 languages: EN, FR.

I create a new content (of a content type with "entity translation") and I title it "test". Since Generate automatic URL alias is enabled, the URL /test displays the content.

I then translate this to French and submit.

On the sidebar I have a language selector which for FR links to /fr/node/1.

How is it possible to automatically make it link to /fr/test? The only way to solve this is by manually typing test in the alias of the French translated content. Why isn't pathauto working in the translations of the node?

Entity Translation 7.x-1.x-dev solves this.

Hint provided in the Packt Drupal-7-Multilingual-Sites book:

  Pathauto works fine for nodes using the node translation model as each
  language  has a separate node. At the time of writing, for feld
  translation, the Pathauto and  Entity Translation module maintainers
  have been ironing out some issues. To get   the automatic URL aliases
  to work in Drupal 7 for feld-translated nodes, you must  use at least
  Entity Translation version 7.x-1.0-alpha2, if available, or the most
  recent  dev version.


How can i display child terms under parent terms and assigned articles using entity field query? Hi i have one content type with  two vocabulary term references one is called category and terms is A,B,C like the 2nd one resources it contains parent with child terms like below hierarchy

Resource 1

    Subsection 1
    Subsection 2
    Subsection 3
    Subsection 4

Resource 2
Resource 3
Resource 4

so i want to display articles based on first taxonomy  category then 2nd taxonomy resources related items using entity field query below hierarchy

Resource 1

    Subsection 1

        Article 1
        Article 2

    Subsection 2
    Subsection 3
    Subsection 4

Resource 2
Resource 3
Resource 4

below is my code for display only 1st taxonomy based articles fetching but i need to display both cases please help.

        <?php
        $vocab = taxonomy_vocabulary_machine_name_load('resource_category');
        $trees = taxonomy_get_tree($vocab->vid);
        $array_tree = array();
        $array_tree1 = array();
        foreach($trees as $tree)
        {
            if($tree->depth == 0)
            array_push($array_tree,$tree->tid);
        }
        $i = 0;

        foreach($trees as $tree)
        {
            foreach($tree->parents as $parent)
            {
                if($parent != 0)
                {
                    $array_tree1[$parent][$i]=$tree->tid;
                    $i++;

                }
                //~ if(array_search($tree->tid,$array_tree))
                //~ array_push($array_tree1,$tree->tid);
            }

        }
?>

<?php
foreach($trees as $tree)
{
    if($tree->depth == 0) {
    echo '
'.$tree->name;
    if(count($array_tree1[$tree->tid]))
    echo '
';
            foreach($array_tree1[$tree->tid] as $sub)
            {
                echo '
'.$sub.'
';
                $query_resources = new EntityFieldQuery();
                $query_resources->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'resouces')
                        ->propertyCondition('status', NODE_PUBLISHED)
                        ->fieldCondition('field_resource_category', 'tid', '21')
                        ->fieldCondition('field_resources_subcategory');
                $result_resources = $query_resources->execute();
                if (isset($result_resources['node'])) {
                    $news_items_resources = array_keys($result_resources['node']);
                    $news_items_res = entity_load('node', $news_items_resources);
                        //echo '
';print_r($news_items_res); echo '
';
                } else {
                    echo '
No Resources
';
                }
                    }
            echo '
';
            echo '
';
        }
}

?>

Term relationships aren't kept in a table that the entity API knows about, so you can't use an EFQ to query them.

taxonomy_get_tree() exists for exactly this purpose:

  Create a hierarchical representation of a vocabulary.

e.g.

$vocab = taxonomy_vocabulary_machine_name_load('foo_vocab');
$tree = taxonomy_get_tree($vocab->vid);

You can optionally provide a $parent_id as a 2nd argument, to force the root of the tree to a specific term.


User picture and name in user menu I would like to achieve what Acquia did on https://dev.twitter.com/. When you sign in, you can see the user picture and the user name in the right end of the menu bar and that is what I need.

I made just some basic attempts yet:

First I tried to use the Menu Token module. Tried to put user picture and user name tokens into the title. Then I realized, that you can't put html in the menu item title as it goes through check_plain() (and it is good that way). Other problem with this was, that the menu item was shown for Anonymous users as well, and the user name was "Anonymous".

I'm using the Omega theme.

The twist on the whole problem is, that I would like to use the Superfish module as well (drop-down as on the Twitter site), and it has its own theme function for building/rendering the menu items.

I can think of a possible solution, that would be a custom theme function and a menu link alter, so that I add an image besides the title. But the Superfish module won't handle the image added to the "raw" link. Correct me if I am wrong...

One method of doing this is to override theme_menu_link() in your template.php file. Specifically, we will be looking for the "My account" link and changing that the text to the username and adding the image.

Add the following to your template.php in your Omega subtheme:

function OMEGASUBTHEME_menu_link(array $variables) {
  global $user;
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $title = '';
  // Check if the user is logged in, that you are in the correct menu,
  // and that you have the right menu item
  if ($user->uid != 0 && $element['#theme'] == 'menu_link__user_menu' && $element['#title'] == t('My account')) {
    $element['#title'] = $user->name;
    // Add 'html' = TRUE to the link options
    $element['#localized_options']['html'] = TRUE;
    // Load the user picture file information; Unnecessary if you use theme_user_picture()
    $fid = $user->picture;
    $file = file_load($fid);
    // I found it necessary to use theme_image_style() instead of theme_user_picture()
    // because I didn't want any extra html, just the image.
    $title = theme('image_style', array('style_name' => 'thumbnail', 'path' => $file->uri, 'alt' => $element['#title'], 'title' => $element['#title'])) . $element['#title'];
  } else {
    $title = $element['#title'];
  }
  $output = l($title, $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

This produces the following html for the menu item in question (my thumbnail image style is set to scale and crop 28 x 28):

username

The rest is just css and possibly javascript.


How to make #states work when dependant element is modified with JS .click() We have custom JS that changes the value of some radio buttons using .click() and we have #states defined in other form elements that react to changes in those radio buttons.

The #states work fine when the radios are manually clicked but don't work when they are clicked through our custom JS .click() (the radio button values change, but the #states are not fired).

This is how the #states is defined:

'#states' => array(
  'invisible' => array(
    ':input[name="field_measure_system[und]"]' => array('value' => 'METRIC'),
   ),
),

and this is how the JS modifies the radio button:

$('a.tab-metric').click(function() {
$('#edit-field-measure-system-und-metric').click();

Thanks!

Drupal states are bound to the change event, therefore you need to trigger that one too. The following snipped should do what you want:

$('#id-of-radio-button').trigger('click').trigger('change');


How do you know if user_login_submit was successful in Drupal 7? Based on the answer from this question How do I programmatically log in a user?

I know how to login in a user, but is there a way to test if user_login_submit was successful or not? It does not have a return value.

You can check if user is logged in or not by using global $user variable, if user is not logged in then $user->uid will be 0 for anonymous users.


Combining 2 exposed filters Using Drupal 6. Views 2.

After googling a bit I found this module which does exactly what I need http://drupal.org/project/views_or, combine 2 exposed filters into 1 single "search box". However, it doesn't work for Views 2.

Anyone know of any alternatives? I want to allow the user to search for terms, both in the title of the node and the taxonomy tags.

Thanks

If I understand you correctly, then I believe the solution I used for a similar task is this - http://drupal.org/node/578620#comment-2750454.

Hope it helps,
Shushu


List all users who voted on a node with their ratings I am using fivestar module for voting on nodes. For each node I would like to create a list of users who have voted on this node and the rating they have given. I am trying to do this using Views 3 but I don't see any relationship which can give me this.

I tried doing this using both the node base table and user base table in Views.

Any ideas how I can go about this?

If you use node as your base table, you can add the relation Content: Votes. This will expose all Votes on that node. From there you can add the fields Votes: User and Votes: Value that can be displayed in a table or something.


Custom module template not detected The page--404 suggestion is visible in the twig debug comments:

function amu_http_status_code_display_theme_suggestions_page(array $variables)
{
  $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  $suggestions = theme_get_suggestions($path_args, 'page');
  $http_error_suggestions = [
    'system.401' => 'page__401',
    'system.403' => 'page__403',
    'system.404' => 'page__404',
  ];
  $route_name = \Drupal::routeMatch()->getRouteName();
  if (isset($http_error_suggestions[$route_name])) {

    $suggestions[] = $http_error_suggestions[$route_name];
  }

  return $suggestions;
}

But it fails to consider the

  templates/page--404.html.twig

from my module.

I have tried this

function amu_http_status_code_display_theme($existing, $type, $theme, $path) {

  $arguments= array(
      'template' => 'page--404',
      'base hook' => 'node',
  );

  // this is the name of the templates
  return array(
    'page--404' =>  $arguments,
  );
}

thanks to 4k4 comment, i have made it working

/**
 * Setting 40x template suggestions
 */
function amu_http_status_code_display_theme_suggestions_page(array $variables)
{
  $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  $suggestions = theme_get_suggestions($path_args, 'page');
  //mapping the route with its suggestion hook
  $http_error_suggestions = [
    'system.403' => 'page__403',
    'system.404' => 'page__404',
  ];
  $route_name = \Drupal::routeMatch()->getRouteName();
  if (isset($http_error_suggestions[$route_name])) {

    $suggestions[] = $http_error_suggestions[$route_name];
  }

  return $suggestions;
}

/*
 *
 * make drupal knows the templates are located in the module
 *
 * */
function amu_http_status_code_display_theme($existing, $type, $theme, $path) {

  $arguments403= array(
    'template' => 'page--403',
    'base hook' => 'page',
  );

  $arguments404= array(
    'template' => 'page--404',
    'base hook' => 'page',
  );

  //mapping the hook with its template
  return array(
    'page__403' =>  $arguments403,
    'page__404' =>  $arguments404,

  );
}


How to Get Views field template to be used in replacement patterns? I'm using a template file like (views-view-field.tpl.php) to modify the output of a specific Drupal 7 Views Field.

I'm trying to modify the field and then use it back in the Views visual editor as a replacement pattern. The problem is it uses the original $output when it is used as a replacement pattern in the other fields' rewritten output (instead of using what I modified in the themed template file).

Is there anyway to do this? I'm trying to avoid going in and theming the other fields just to use the modified first one.

If you make this field the displayed field it will take the theme adjustments. Do your rewrite and replacement patters on this field, put it at the end of the field list and exclude the others.  If this field is used as a replacement pattern the theme will not be applied.


How can I create comment on node insert? I try to create comment on node insert using insert() hook but it collides with INSERT INTO {comment_entity_statistics} sql.

Integrity constraint violation: 1062 Duplicate entry '53-node-field_support' for key 'PRIMARY': INSERT INTO {comment_entity_statistics}

The code:

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function notifications_node_insert(Drupal\Core\Entity\EntityInterface $entity)
{
    $timestamp = mt_rand($entity->getCreatedTime(), REQUEST_TIME);
    $stub = array(
        'entity_type' => $entity->getEntityTypeId(),
        'entity_id' => $entity->id(),
        'field_name' => 'field_support',
        'name' => 'devel generate',
        'mail' => 'devel_generate@example.com',
        'timestamp' => $timestamp,
        'subject' => $_POST['field_support_message'],
        'uid' => \Drupal::currentUser()->id(),
        'langcode' => $entity->language()->getId(),
    );
    $comment = \Drupal\comment\Entity\Comment::create($stub);
    $comment->save();
}

I guess you're hitting some edge case in \Drupal\comment\CommentStatistics::create(), which is called in comment_entity_insert(). The code assumes that there is no comment yet when that is called. Which is an assumption that you are breaking, probably because your module gets called first.

That's arguably a core bug, you could open a bug report and try to fix it there to do a merge query. That said, as a workaround, make sure that your hook is called later than comment. You will have to implement hook_entity_insert() instead of node as that is apparently called later (by default, hooks are stored by modules by weight, name, so C should be before N).

PS: You should enable verbose error logging and check the full backtrace of that error. That can often help with understanding what's going on.


Drupal 7.27: 408 Request time out in Chrome browser We are getting 408 request time out errors in Chrome browser only since the beginning of May. We have not been able to replicate the problem with any other browser. With one website we had a SSL protocol and the error only occured in Chrom on http://
After implmenting a redirect from http:// to https:// via .htaccess the error seemed to have gone.
On a second site there is no SSL certificate and the error only occurs occasionally but it does. We have set the request_time_out to 10080 in the php.ini to no avail. Another thing we tried: We redirected that site to be accessed only with "www".

Has anyone experienced something similiar? Any suggestions would be very welcome.

This is a Chrome bug.

https://meta.stackexchange.com/questions/208790/408-request-time-outs-still-continues/232275#232275

One solution: http://blog.haproxy.com/2014/05/26/haproxy-and-http-errors-408-in-chrome/

Seems to be limited to Chrome, page requests through http:// and servers running HAProxy.


How to redirect the user using hook_init? If the user requests www.mysite.com/user/login he should be redirected to www.mysite.com/mylogin. I know this is possible with hook_init or hook_boot, can some one explain how this can be achieved.

Thanks

/**
 * Implements hook_init().
 */
function mymodule_init() {
  global $base_url;
  if (user_is_anonymous() && arg(0) == 'user') {
    drupal_goto($base_url . 'mylogin');
  }
}


How to use "db_query" instead of "db_select"? I am using "db_select" in a computed field to get an array of values from database (trough an entity reference field - multi value):

$wrapper = entity_metadata_wrapper($entity_type, $entity);
$current_nid = $wrapper->nid->value();
$values_y = array();
/* First I get an array of referenced nodes IDs that are neccesary in second query*/
$child = db_select('field_data_field_plan_tpl_select_trainings', 'f')
  ->fields('f', array('field_plan_tpl_select_trainings_target_id'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'skills_plan_tpl')
  ->condition('entity_id', $current_nid)
  ->execute();
$child_nid = array();
foreach ($child as $item_child){
   $child_nid[] = $item_child->field_plan_tpl_select_trainings_target_id;
}
/* Here I get an array of values from referenced nodes */
$week_no = db_select('field_data_field_skill_week_no_planned', 'f')
  ->fields('f', array('field_skill_week_no_planned_value'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'skill')
  ->condition('entity_id', array($child_nid))
  ->execute();
$week_value = array();
foreach ($week_no as $item_week){
   $week_value[] = $item_week->field_skill_week_no_planned_value;
}

$values_y = array_filter($week_value);

I understand that "db_query" is faster than "db_select"; is it true and can it have a positive impact in my situation? How can this be translated into "db_query"?

db_query can be used with an actual MySQL query - you just insert the MySQL query as you would in, say, PHPMyAdmin or some other UI for MySQL (or command line).

You can also substitute arguments into the query based on the second argument passed to the function, as such (found on Drupal.org as an example):

$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));

Here the $uid variable is being passed as an argument to the query. Theoretically you could also write this as such:

$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n WHERE n.uid = ' . $uid);

As Clive mentions in the comments though, this is just for illustrative purposes, as it does open you up to potential attack.


webform validation integer value I tried webform validation, I can validate textfield component for numeric value.
However, I cannot find how to set it as integer value only.
How can I validate numeric (integer) value.

Webform Validation's numeric validator relies on PHP's is_numeric. Thus, any numeric expression (e.g. 1.5) is going to be validated there. In order to validate integers only, you'll need to use Regex validation where only integers character can be valid (e.g. "^([0-9]+)$").


Paragraphs Collection (Behavior plugins) vs. Field Group I'm trying to build a site (or define site a building configuration), which allows editors to create their own layouts using the Paragraphs  module. Powerful options for editors, reuseability across different projects and full control over the generated HTML are important.

There will be grid paragraphs to create the layout/structure containing content paragraphs for image, text, sliders, videos, accordions, etc. Most paragraphs will have "non-content" data like column width, background color, slider autoplay on/off, etc. So far I've found two ways the to handle the non-content part, but I'm unsure which is the better way to do it:

A) Use normal fields for non-content settings and Field Group to create finetune the editor interface. Use template preprocessing and/or Twig logic to create the desired frontend output. (Do frontend coding in a base theme to allow reuseability across different projects.)

B) Use the Plugin-system from Paragraphs Collection to create "behavior" plugins (code and YAML configuration) for non-content settings. Get the frontend stuff done with preprocessing in the module's code.

The collection plugin was created by the maintainers of the paragraphs plugin themselves, so B) is obviously the way it should be done. It also more clearly separates content from design/other stuff. However, I'm usually doing frontend coding, and while I'm used to PHP, I'm fairly new to Drupal, so A) would be the path I'm used to. Also the paragraphs behavior plugin is explicitly labelled as experimental and not ready for production use.

I'm looking for some hints from experienced Drupalers on which route to take, also concerning long term maintenance for many small sites (at least 4-5 years) and reuseability across different client projects.

As you stated, the Paragraphs Collection module should be considered Experimental, and not used in Production environments:

  THIS PROJECT IS EXPERIMENTAL. DO NOT USE IT IN PRODUCTION PROJECTS. THERE IS NO UPGRADE PATH UNTIL A BETA RELEASE.

This is especially true if your plan is to use this on multiple sites, with the life expectancy of 5 years.

The common method in Drupal 7, and currently in Drupal 8 is your first point, to use fields for settings and use preprocesses and/or twig templates to turn those fields into classes/markup you want.

For re-usability, you will either want to use the Features module and a base theme, or create your own module that will handle the config, templates and styling.  I took that route with the Bootstrap Paragraphs module.


Calendar Module Styling of upcoming events I'm trying to remove the left margin/padding on the event items that show in Upcoming Events when you use the Calendar module(see attached pic). Could anyone advise what element it is that I need to change the CSS on, to remove the left margin or padding? I want the items under the heading to appear flush (left aligning) with the heading. I am also using Omega 3 so I'm not sure if thats relevant.

In the View of the Upcoming Events, i changed the view option from HTML List to Unformatted List and the problem went away. See attached pic.


How to get the media that owns a file? I have a file and I know there is a media that references it. How can I get this media?

In the opposite direction, knowing the media id, I can get the file:

$media = Media::load($mid);
$fid = $media->field_media_image->target_id;
$file = File::load($fid);

But now I know the file id and I want the media. How can I get it?

You can use entityQuery:

$fid = 13141;
$usedIn = \Drupal::entityQuery('media')
  ->condition('field_media_image.target_id', $fid)
  ->execute();

Example response:

Array
(
    [15105] => 13109
)


How to make fields required for one type of user but not others? (registration and profile forms) I would like to know what is the best way to handle this scenario using Drupal 7.

The issue I am facing is that the Join (registration) forms, and Profile forms are different for all 4 types of users I am working with. The registration and profile forms are all connected to one master profile form. This means that if a field is required for one, it will be for all of users, how can I avoid this? What is the best way to go about it?

Thanks!

Required By role

  Field required by role is a module that improves core "required"
  functionality.

  Similar to CCK Required by role brings extra features such as:

  Ready for all entities, including custom entities. Doesn´t need extra
  configuration, just install. Respects previous configuration.
  Configuration per field instance.


tinymce and colorbox and inline images I have a blog, I am developing and using the following plugins, but I am not committed to them and will change to get the behavior I want.

TinyMCE
Wysiwyg
Colorbox
Media

In many blogs I see inline images that are small and when they clicked on then expanded in a colorbox.

I am curious how to achieve this using drupal 7 and uploading images using the media module?

There are two approaches I know to make inline images in WYSIWYG editors open in Colorbox. The one which I used in my last project was inserting images with Insert module. Which requires you to add an image field to your content type and upload your images to that field and than insert them with any image settings (instead of uploading them via the Media button on the editor).

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

This approach allows you also to get the images with Views etc, since they are actually stand-alone fields.

The second approach is adding a CSS class to the inline image uploaded via the media button. I'm not quite sure about how and which class but I did use this approach a few years ago and back then the mentioned modules had their 7.x-1.x versions, still. I was looking for the current state of using this approach but didn't find anything new. I'll experiment it a bit and write here.

Edit: After investigating about an hour, couldn't find any better way than the approach with the Insert module. It's the best user experience among all other approaches, if not still perfect.


drupal_get_form of custom content types I am wracking my brain to try to figure out how to retrieve a custom content type's edit form programatically.

For example, I created a content type called "address", and have this:

$form = drupal_get_form("address_node_form");

But it does not work. I get back this warning:

  Warning: call_user_func_array() [function.call-user-func-array]: First
  argument is expected to be a valid callback, 'node_form' was given in
  drupal_retrieve_form() (line 771 of
  /home/richardp/public_html/drupal7/d7/includes/form.inc).

I know that in D6 you also had to include an object where you specify the type, but I have tried this and it still doesn't work.

When I try simply $x = node_add("page"); I get a white screen of death, presumably because I ran into a PHP error.

Am I supposed to be including a file first or something like that?

Here is the code to display the Edit Form in Node View page:

<?php
// modules/custom/custom.module

function custom_preprocess_node(&$vars) {
    module_load_include('inc', 'node', 'node.pages');
    $node = $vars['node'];
    $form = drupal_get_form('mytype_node_form', $node);
    $vars['content']['edit_form'] = $form;
}
?>

Notes:

You need to replace custom with your module's name and mytype with
the machine-readable name of your content-type.
I just used a clone of $vars['node'] to prevent probable problems
caused by the fact that $vars is passed by reference; though it
might not be necessary.


Using a custom view for a taxonomy term page Using Drupal 7 and Views 7.x-3.0-beta3, what is the best way to have a taxonomy page use a custom view?

For example, in Path Auto I have a rule that points the URL alias countries/england towards taxonomy/term/44.

When a user visits countries/england I want to display a page created with Views, not the default taxonomy page.

I am populating the menu using Taxonomy Menu which doesn't yet support custom paths in Drupal 7.

Maybe I am misunderstanding what you are saying, but Views comes with a view for taxonomy/term/%tid. Once enabled, when you visit http://example.com/taxonomy/term/44, Views will show its own page, and not the default page output from Drupal.


Filter by taxonomy in Views table I have a vocabulary Area for classifying maths problems, with two parent terms (Pure and Applied) and appropriate child terms (Geometry, etc.) under each. Problems (a content type) are tagged with the appropriate areas of mathematics that they cover.

I also have a table page defined in Views with filter criteria Type (= Problem) and Area (exposed), for listing all the problems.

The problem I have is as follows: If someone selects `Applied Mathematics', nothing appears, because Problems are only tagged with the child terms.

How can I get all the Problems to show up?

In Drupal 7 I should add!

If you look at the default Taxonomy Term view provided with views, you'll see that it has a contextual filters Content: Has taxonomy term ID (with depth) and Content: Has taxonomy term ID depth modifier. Both are needed. If you look at the description for the Depth field for the first filter you'll see the following:

  The depth will match nodes tagged with terms in the hierarchy. For example, if you have the term "fruit" and a child term "apple", with a depth of 1 (or higher) then filtering for the term "fruit" will get nodes that are tagged with "apple" as well as "fruit". If negative, the reverse is true; searching for "apple" will also pick up nodes tagged with "fruit" if depth is -1 (or lower).

In your case fruit is applied and apple is, for example, Geometry. So if you specify a depth of 1 or higher you should get the behaviour you want.


Add custom HTML to custom field In a module, I have defined a custom field. Using hook_field_formatter_info() and hook_field_formatter_view(), I can manage the display of every item (value) within that field. I want to allow the use of multiple values of this field.

How can I add extra HTML to this 'collection'? Programmatically, from within my module.

For example, let's say my module adds a 'fruit' field, that allows me to enter its name and its color. Now, I'd like to display this as such:

Name: Strawberry. Color: Red
Name: Orange. Color: Orange
Name: Lime. Color: Green
<some>Extra Html</some>

How to add that extra last line?

I can find references to hooks that should do it, but I simply don't understand how to tie all these pieces of information together.  I suspect I have to work with:

hook_field_prepare_view https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook_field_prepare_view/7

I also found this resource suggesting these hooks: http://www.failover.co/blog/drupal-7-custom-field-formatter-hooks-overview

and that I should manipulate the render array.

And I tried just adding an extra element to the array, an extra delta:

$element[] = array(
    '#type' => 'markup',
    '#markup' => "Test HTML"
);

But is seems to get ignored by Drupal

It turns out all I needed to do was to use hook_field_prepare_view() to add an extra, empty elements to the $items array

/**
 * Implements hook_field_prepare_view().
 */
function threejs_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items)
{
    $items[1]['footer'] = array( );
}


What qualifies as "active development" on drupal.org? The D7 JW Player module claims to be "Actively maintained" and "Under active development", and yet hasn't had a commit in 30 weeks.

The page for "Actively maintained" implies that the only required qualification for that status is that bug reports are "looked at".  That seems pretty minimal to me.  What about the requirements for being considered "under active development"?  Is there really any requirement or can any module be listed as such if its maintainers say it is?

If you have edit permissions on a project, you see that it is a vocabulary:

The link is to Maintenance of your project.  In other words, it is essentially an honor system that the project creator sets.  Unfortunately, developer loses interest in a project they also tend to lose interest in maintaining the webpages and documentation.

Clive has summarized the rest.


pm-update fails "sh: --backend=2: command not found" The pm-download command is working so I can update modules individually, but I can't do it in bulk. Both drush 6.2.0 and 6.1.0 give an error.

The output of drush up --debug is the following.

  Bootstrap to phase 0. [0.01 sec, 2.24 MB]
  [bootstrap] Drush bootstrap phase : _drush_bootstrap_drush() [0.01
  sec, 2.37 MB] [bootstrap] Cache HIT cid:
  6.2.0-commandfiles-0-da12a99782b48770f5d9ad8965ca5448 [0.02 sec, 2.39 MB]           [debug] Bootstrap to phase 0. [0.09 sec, 6.4 MB]
  [bootstrap] Bootstrap to phase 6. [0.14 sec, 6.4 MB]
  [bootstrap] Drush bootstrap phase : _drush_bootstrap_drupal_root()
  [0.14 sec, 6.41 MB]                     [bootstrap] Initialized Drupal
  7.24 root directory at /path/to/site [0.16 sec, 7.43 MB]    [notice] Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.16 sec, 7.44
  MB]                     [bootstrap] Initialized Drupal site default at
  sites/default [0.16 sec, 7.44 MB]
  [notice] Cache HIT cid:
  6.2.0-install_profile-66ecfeb9791a023150773849f1550c5d [0.16 sec, 7.45 MB]          [debug] Cache HIT cid:
  6.2.0-commandfiles-2-699657487b88e8b0c2ede2984aa12913 [0.16 sec, 7.45 MB]           [debug] Drush bootstrap phase :
  _drush_bootstrap_drupal_configuration() [0.17 sec, 7.47 MB]            [bootstrap] Drush bootstrap phase : _drush_bootstrap_drupal_database()
  [0.17 sec, 7.51 MB]                 [bootstrap] Successfully connected
  to the Drupal database. [0.17 sec, 7.51 MB]
  [bootstrap] Drush bootstrap phase : _drush_bootstrap_drupal_full()
  [0.18 sec, 8.14 MB]                     [bootstrap] Cache HIT cid:
  6.2.0-install_profile-66ecfeb9791a023150773849f1550c5d [0.37 sec, 26.15 MB]         [debug] Cache HIT cid: 6.2.0-commandfiles-5-8aee30ce3a469e89d0725cfb79ceb51b [0.37 sec, 26.16 MB]          [debug] Drush bootstrap phase :
  _drush_bootstrap_drupal_login() [0.38 sec, 26.62 MB]                   [bootstrap] Successfully logged into Drupal as Guest (uid=0) [0.38
  sec, 26.63 MB]                          [bootstrap] Found command:
  pm-update (commandfile=pm) [0.38 sec, 26.63 MB]
  [bootstrap] Calling hook drush_pm_update [0.71 sec, 26.97 MB]
  [debug] Loading release_info engine. [0.9 sec, 29.07 MB]
  [notice] Loading version_control engine. [0.9 sec, 29.17 MB]
  [notice] Loading package_handler engine. [0.91 sec, 29.19 MB]
  [notice] Executing: wget --version Including
  /usr/local/Cellar/drush/6.2.0/libexec/commands/pm/updatecode.pm.inc
  [0.93 sec, 29.21 [bootstrap] MB] Calling hook
  drush_pm_updatecode_validate [0.94 sec, 29.31 MB]
  [debug] Returned from hook drush_pm_updatecode_validate [0.94 sec,
  29.31 MB]                               [debug] Calling hook drush_pm_updatecode [0.94 sec, 29.32 MB]
  [debug] Cache HIT cid:
  6.2.0-alias-path--2c8463220c4fed24dfb54242bc0f682e [0.94 sec, 29.36 MB]             [debug] Backend invoke:   --backend=2 --verbose
  --debug --root=/path/to/site          [command]
  --uri=site.local  pm-updatestatus 2>&1 [1.26 sec, 29.37 MB]   --backend=2 --verbose --debug --root=/path/to/site --uri=site.local            [notice] pm-updatestatus 2>&1 [1.26 sec, 29.38 MB] Illegal string
  offset 'site' backend.inc:1013 [1.27 sec, 29.38 MB]
  [warning] The command could not be executed successfully (returned:
  sh: --backend=2: command not found   [error] , code: 127) [1.27 sec,
  29.38 MB] Returned from hook drush_pm_updatecode [1.27 sec, 29.36 MB]                                        [debug] Changes made in drush_pm_updatecode have been rolled back.
  [1.27 sec, 29.37 MB]                 [rollback] Command dispatch
  complete [1.27 sec, 29.34 MB]
  [notice] Returned from hook drush_pm_update [1.28 sec, 27.27 MB]
  [debug] Command dispatch complete [1.28 sec, 27.24 MB]
  [notice]  Timer  Cum (sec)  Count  Avg (msec)   page   1.113      1
  1113.33 Peak memory usage was 31.64 MB [1.28 sec, 27.24 MB]                                               [memory]

The issue happens under OS X Mountain Lion and PHP 5.4.20, and continued after upgrading to Mavericks.

This is happening because Drush is trying to find the local Drush executable via $drush = realpath($_SERVER['argv']['0']);.  In this context, realpath is returning FALSE, because $_SERVER['argv']['0'] does not exist.

As a workaround for this particular problem (which is that pm-update cannot call updatedb), you could run drush pm-updatecode followed by drush updatedb.

Note

If you work around the problem instead of solving it, you will also run into this same issue with other commands, such as sql-sync.


How to include an external PHP script? I have PHP file and I need to include that PHP file in static page. Where is best place to store that PHP file so I can include it in a static page.

If that's your code, transform it into Drupal custom module. If you want use PHP API delivered by external service - transform it into library (move code into  sites/all/libraries/yourLibrary) and write custom module which loads files on demand (with Libraries API).


Can't modify Content Access in Media Gallery Module I've got the Media Gallery module installed and want to control the access to it using the Content Access module but can't find how to do that. I get an "Access Control" button on all my other regular pages but don't on the Media Gallery pages.

It sounded like there was an issue with permissions with Drupal 7.2 http://drupal.org/node/1147906 but it was fixed in 7.3. I'm running 7.8 right now. Thanks.

Check the admin/structure/types/manage/media_gallery/access settings page on your site and ensure that the Enable per content node access control settings checkbox is checked and then save.


Can't uninstall "Translation Language capabilities (tmgmt_language_combination)" dissabled ALL translation modules that might be dependant I've tried drush, I disabled i18, ALL fields, multilingual, entity translation, l10n, everything about translation is disabled.

How can I completely get rid of this module, it's caused nothing but griefwith patches and bugs...

Had to go into Phpmyadmin browse system>> search tmgmt_language_combination

Click on edit and set status to 0

Then I had to manually delete the modules, refresh, repaste the modules, then refresh, and finally it showed up as red.


User approval needed to reference (entity reference) their profile (profile2) Here is the use case:

User registers, and creates "Employee Profile" (using profile2)
Admin user creates node of type Location
Location node references (using entity reference) user's "Employee Profile," and then displays all the employees at a location (using the Views module, and EVA)

It is all complete, but users whose profile is being referenced needs to give permission before their profile is displayed in the Location node.

In order to achieve this, at a large scale, is to create a field on the user profile (example "Allow your profile to be displayed on Locations?" Yes or No).

Using views, filter profiles by field with value equal to yes.


Show menu tab on certain content type I have created a menu tab with views and I want to show that tab only on a certain content type. How can I do this?

Have you tried this resource? http://drupal.org/node/354423 , if not, could be useful, is about a menu tab to show only with certain content type.


webform: additional options for components Im trying to add additional options for webform component but I seem to be unable to read the data out. I successfully managed to save the data into "extra" inside the db. But I'm unable to read it out again.

what I basically did is this:

function webform_maxlenght_form_webform_component_edit_form_alter(&$form, &$form_state, $form_id) {
$form['extra']['message'] = array(
  '#type' => 'textarea',
      '#title' => 'Message',
      '#default_value' => isset($form['extra']['message']) ? $form['extra']['message'] : NULL,
  );
}

It saves it perfectly fine into the database under the field "extra" like I wanted but I'm lost as to how to use it later.

Any help is greatly appreciated, if I'm going into a completely wrong direction please say so

Please have a look to the new hook implemented in web form: hook_webform_select_options_info().

function mymodule_webform_select_options_info() {
  $items = array();

  $items['days'] = array(
    'title' => t('Days of the week'),
    'options callback' => 'webform_options_days',
    'file' => 'includes/webform.options.inc',
  );

  return $items;
}

The documentation for that hook describes it as follow:

  Define callbacks that can be used as select list options.

  Return value

  An array of callbacks that can be used for select list options. This array should be keyed by the "name" of the pre-defined list. The values should be an array with the following additional keys:

  title: The translated title for this list.
  options callback: The name of the function that will return the list.
  options arguments: Any additional arguments to send to the callback.
  file: Optional. The file containing the options callback, relative to the module root.


Are there any embedded video/media field modules which integrate with Rules? I'm trying to set up some Rules conditions which deal with whether or not a user has added a YouTube URL into a media field for a node. The idea is to use a Media type module to embed the YouTube video into the forum post. But I want a specific Rule to fire if the user saves their forum post without adding a YouTube video URL to that custom field.

However, I can't seem to find a module like Media or Video Embed Field, or Embedded Media field which expose that field entity to Rules.

You could use a hook_form_alter() to check if a youtube video has been added. Then run rules_invoke_event() to trigger the rule.

Btw, I personally like the Video Embed Field module.


My Ajax call for my submit button does not work? I am building a form with the form builder but I can't even get my button to use its ajax function to callback. Instead of doing a normal ajax call on the page, it reloads the entire page.

What am I doing wrong here? The DPM function doesn't even run, so i'm assuming i'm not even triggering the ajax call, but I have copy pasted the function name into the callback, so i'm not sure why its not triggering on submit?

  $form['suggested_actions']['list']['mentorship'] = array('#type' => 'container');
  $form['suggested_actions']['list']['mentorship']['text'] = array('#type' => 'markup', '#markup' => '');
  $form['suggested_actions']['list']['mentorship']['text']['#markup'] .= 'Mentorships - Unconfirmed';
  $form['suggested_actions']['list']['mentorship']['button'] = array('#type' => 'button', '#button_type' => 'submit');
  $form['suggested_actions']['list']['mentorship']['button']['#name'] = 'Mentorships';
  $form['suggested_actions']['list']['mentorship']['button']['#attributes'] = array('data-title' => array('Mentorships'), 'class' => array('SA_Button'));
  $form['suggested_actions']['list']['mentorship']['button']['#value'] = 'Confirm Mentorships';
  $form['suggested_actions']['list']['mentorship']['button']['#ajax'] = array(
      'callback' => 'erc360_completeness_report_suggested_actions_mentorship_ajax',
      'wrapper' => 'mentorshipunconfirmed',
      'method' => 'replace',
      'effect' => 'none',
  );

  function erc360_completeness_report_suggested_actions_mentorship_ajax($form, $form_state){
      dpm("The AJAX FUNCTION has ran...");
      return $form['suggested_actions']['list']['mentorship']['text']['#markup'] = 'confirm';
  }

Try following code.

$form['suggested_actions']['list']['mentorship']['button']['#ajax'] = array(
  'callback' => 'erc360_completeness_report_suggested_actions_mentorship_ajax',
  'wrapper' => 'mentorshipunconfirmed',
  '#callback' => 'ajax_test',
  '#wrapper' => 'wrapper',
  'method' => 'replace',
  'effect' => 'fade',
);

function erc360_completeness_report_suggested_actions_mentorship_ajax($form, $form_state){
  dpm("The AJAX FUNCTION has ran...");
  $form['suggested_actions']['list']['mentorship']['text']['#markup'] = 'confirm';
  return $form['suggested_actions']['list']['mentorship']['text'];
}


Entity Browser in Forms API I'm having trouble getting the entity browser widget to work correctly in a custom form. Just wondering if anyone has had any success in getting it working. I've got to the point the button is rendering, you can use the browser, select the media. The the media id is also attached to the hidden field the widget generates.

...from my digging around it looks like it never creates the right markup in the "current" div that get sent back from the ajax request that triggers on "process"

Code below...

      $form['entity_browser_wrapper'] = [
      '#type' => 'container',
      'widget' => [
          '#title' => t('Entity Browser'),
          '#field_name' => 'entity_browser_wrapper',
          '#field_parents' => [],
          '#required' => false,
          '#parents' => ['entity_browser_wrapper'],
          '#tree' => true,
          '#id' => 'edit-entity-browser-wrapper',
          '#type' => 'details',
          '#open' => true,
          'entity_browser' => [
              '#type' => 'entity_browser',
              '#entity_browser' => 'document_browser',
              '#cardinality' => 1,
              '#entity_browser_validators' => ['entity_type' => ['type' => 'media']],
              '#process' => [
                  ['\Drupal\entity_browser\Element\EntityBrowserElement', 'processEntityBrowser'],
                  ['\Drupal\entity_browser\Plugin\Field\FieldWidget\EntityReferenceBrowserWidget', 'processEntityBrowser'],
              ]
          ],
          'current' => [
              '#theme_wrappers' => ['container'],
              '#attributes' => [
                  'class' => 'entities-list',
              ],
              'items' => [],
          ],
      ],
  ];

This is based off a question I found in the entity browser issues https://www.drupal.org/node/2816881. I've looked into the suggestions that were posted and have come up blank.

Thanks

I got a possibly easier solution. you need to have entity_browser and entity_browser_block required as dependencies and installed in your module. Then in your BlockBase buildForm or LayoutDefault buildConfigurationForm you can do something like what they do in the entity_browser_block module in the EntityBrowserBlock.php
// make sure you have this at the top of your file
use Drupal\entity_browser_block\Plugin\Block\EntityBrowserBlock;

// blockForm or buildConfigurationForm
$test = EntityBrowserBlock::loadEntitiesByIDs(explode(' ',$configuration['selection']['entity_browser']['entity_ids']));
$form['selection'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'entity-browser-block-form'],
];
$form['selection']['entity_browser'] = [
  '#type' => 'entity_browser',
  '#entity_browser' => 'classes',
  '#process' => [
    [
      '\Drupal\entity_browser\Element\EntityBrowserElement',
      'processEntityBrowser',
    ],
    ['\Drupal\entity_browser_block\Plugin\Block\EntityBrowserBlock', 'processEntityBrowser'],
  ],
  '#default_value' => $test,
];

$order_class = 'entity-browser-block-delta-order';

$form['selection']['table'] = [
  '#type' => 'table',
  '#header' => [
    $this->t('Title'),
    $this->t('Operations'),
  ],
  '#empty' => $this->t('No entities yet'),
  '#tabledrag' => [
    [
      'action' => 'order',
      'relationship' => 'sibling',
      'group' => $order_class,
    ],
  ],
  '#process' => [
    ['\Drupal\entity_browser_block\Plugin\Block\EntityBrowserBlock', 'processTable'],
  ],
  '#default_view_modes' => 'default',
];


How can I style the WYSIWYG content? Let's say I'm currently editing a page and there is a WYSIWYG editor in the backend to edit a specific part.

Now I add a table via the WYSIWYG. How can I apply CSS styles on that table WITHOUT altering the CKEditor plugin settings (I don't want to provide classes in the "Styles" dropdown)?

You can either implement hook_ckeditor_css_alter or you can add ckeditor_stylesheets to your themes info.yml file.

See: hook_ckeditor_css_alter for more.

Example:

function mymodule_ckeditor_css_alter(array &$css, Editor $editor) {
  $css[] = drupal_get_path('theme', 'mytheme') . '/css/mymodule-ckeditor.css';
}

Or in mytheme.info.yml:

ckeditor_stylesheets:
  - css/styles.css


Homepage has redirect loop One of my sites has started to have a redirect loop that just happens on the homepage. Not the secondary pages though. (Drupal 7 - Commerce Kickstart)

Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.

Some days it does this, some days it doesn't. I feel like it magically fixes itself during the week and on the weekend it breaks. Is there any way to can find out where it is trying to redirect itself to and remedy it? Would the redirect location/error be logged somewhere I could check?

Found follow errors in php logs:

PHP Warning:  Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini

PHP Fatal error: Unsupported operand types in public_html/dev/profiles/commerce_kickstart/modules/contrib/search_api_db/service.inc on line 970

Got the redirect loop to stop after increasing the max_input_vars to 9000. I feel it's more of a bandaid fix though. So I'm taking this further into the Commerice Kickstart community.


How to calculate the sum for each option of all webform results in a Drupal webform grid? I created a webform in drupal, and added a grid component in it. The grid has 13 questions and 3 options (good, bad, terrible). It's like a poll and people come and answer the questions.

In results, I already have the sum for each option in each question. What I also need is the sum for each option for all questions togehter. For example I need a sum row in grid footer!

I tried webform submissions in views, but it does not give me the data stored in grid.

Be aware that I'm noob in PHP and I don't know how to make TPL files.

image in this link says it all:

thanks

Create a 'webform submission' view. By using the Views Calc module you can display the sum of each field at bottom of the table/grid.

This module adds simple calculations to a views table. Requires the Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

Image from module page


How to set the correct RSS row plugin? I need to add an image to the RSS feed. So I create a new row plugin for the RSS and it extends RssFields row plugin.

/**
 * Renders an RSS item based on fields.
 *
 * @ViewsRow(
 *   id = "image_field_rss_fields",
 *   title = @Translation("Fields with image field"),
 *   help = @Translation("Display fields as RSS items with an image item."),
 *   theme = "views_view_row_rss",
 *   display_types = {"feed"}
 * )
 */
class ImageFieldForRssFields extends RssFields {

I can select it in the format settings.

And it seems that works perfectly when I update the preview, I can see a new field image on every item of the RSS. But when the RSS feed is rendered, it uses the RssFields plugin instead of the ImageFieldForRssFields plugin that is setted.

I debugged it and it seems that always renders the RssFields plugin even if I delete the RssFields plugin, the view tries to locate it.

Am I missing something? How do I have to do to render the correct plugin?

There is a patch to add an image as an enclosure field to core here:
https://www.drupal.org/project/drupal/issues/2511878


Revision history summary I am looking for a solution to show a summary of revision history for all nodes in one place. The out of the box solution is to show a revision history for each node apart. I want to be able to track my content admins' changes in one place (I couldn't find a module that does what I want)
Thanks!

If you don't mind to use Views module, you can configure any list of revisions. You also can add filter/sort logic, pager, configure access and much more useful things.

You always can export your solution with Views export or with Features module and reuse it on other Drupal sites.

More information about Views: http://nodeone.se/en/node/20


Using a newer JQuery version The Drupal 6 version of jQuery is too old (1.26). Could I delete, and replace it with a newer version?

No, that would not be advisable; instead, use the jQuery Update module.


How to implement a Rules Condition like [account:last-login] = never? Here is my contextual explanation:

I would like to redirect on a special page for first time after login. But registering system is using an email validation, so the path to the first login is "user/reset/uid/*", which brings the user to its profile page to save a password when the user clicks the one-time login button. This is fine and using a redirect after register of any kind is overriding it, which I don't want to. So I'm looking for a data comparison with the Rules module.

My question: How can I compare as a condition with rules [account:last-access] or [account:last-login] with something that would say never?

The rule would be this:

Rules Event : After updating account (because of the one-time login password change)
Rules Condition : [account:last-login] = never
Rules Action : redirect toward my special welcome page

These are the modules used:

rules
reference with user reference sub-module
ajax register (which usefully rewrite login to home)

It looks that what you're trying to do implement (= do a data comparison with "never") is not an obvious thing to do. Therefor, you may want to go for a plan-b that, for sure, will implement what you're trying to achieve, i.e. "... redirect on a special page for first time after login ..." (as in your question). Read on for more details.

Create a custom rule that looks like so (in Rules export format, use the Rules UI to import it in your own site):

{ "rules_redirect_new_users_to_special_page" : {
    "LABEL" : "Redirect new users to special page",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } },
      { "redirect" : { "url" : "welcome\/newuser" } }
    ]
  }
}

Some details about this rule:

Rules Event: User has logged in.
Rules Condition: User does NOT (!!!) have a role with role id = "4".
Rules Action:

Grant User the role with role id = "4".
Perform a page redirect to relative path welcome/newuser.

So this rule checks if a user does not yet have some (designated) role with role id = "4" (adapt to whatever role id that fits your case, and make sure this role is NOT yet granted when activating a new user id). If that's the case then the user is granted that role, followed by a page redirect to relative path welcome/newuser (adapt to whatever path that fits your case). Obviously, next time a user performs a login again, the Rules Condition will no longer be TRUE, and no more redirect will be performed.

Pretty similar to "... redirect on a special page for first time after login ..." (as in your question), no?

Variation

What is explained before in this answer, does require some extra (dedicate) role. If you rather want to keep the number of roles in your site to a minimum, you could also use the Flag module (as an alternative for such extra role). Some more details about this variation:

Define a "global" flag to flag users
Replace the Rules Condition (to check for the dedicated role), by another one like "Check if the user is NOT flagged" (by the global flag).
Replace the Rules Action (to grant the dedicated role), by another one like "Flag this user flagged" (by the global flag).

Voilà ... use the solution you prefer, either one will do ...


Default Event calendar view is missing I have installed event calendar module and using Zen sub-theme.As event calendar module gives its own content type and view.I can see the content type however I am not able to find the default view Event Calendar in view list.Anybody know the reason please revert.

It is made available as a view template.

Goto admin/structure/views/add-template and create a new calendar view based on the Date Field that you want to use.


How to customize order confirmation e-mail I am experimenting with Commerce 2 and it is amazing, however one thing that I am unable to resolve customizing store e-mails? The default confirmation is not adequate and should be easy to customize using tokens or whatever like drupal core email messages. Can anybody provide a high level overview how to customize the order summary e-mail? Any tips will be greatly appreciated not only by myself, but certainly many other site builders who are stumped over this.

Order receipt emails are powered by Twig templates, just like regular pages. This helps us avoid the inflexibility of tokens and their lack of conditional support ("Only show the Shipping information heading if the token has data"), which were big problems for D7 sites.

You can override the commerce-order-receipt.twig.html template in your theme to customize it.

See https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/order/templates/commerce-order-receipt.html.twig


Display a view with exposed form programmatically I show a view in my own module, like this: $viewFromDrupal = views_embed_view('storage', 'block');. The view is showing up, but the exposed filter is not working when I place the included view directly after an other view.

When the view $viewFromDrupal is showing at the top of the page the exposed filter works correctly.

Does someone have some experience with this?

Should I include some extra files or something?

So better to say in your question more details of how it doesn't work, but I'll take a guess...

Try

$view = views_get_view('storage');
  $view->set_display('block');
$view_markup = $view->preview('block');

I've done this before to render the View, that will give you some markup...

Then I've noticed that the "action" of the form could be incorrect, so you have to do a hook_form_alter implementation and set the #action to the current page path...I'm guessing what the value of $form['#id'] will be, you will need to verify that ...

    function yourmodule_form_alter(&$form, &$form_state) {
    if($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-storage-block') {
        $path = current_path();
        $form['#action'] = '/' . $path;
    }

  }


Show certain elements based on URL query string I am very new to drupal and also very willing to learn.
I am trying to migrate old code from another tool to drupal 8.
I am working on a form, using the webform module.
Can I possibly show certain webform elements based on specific URL query strings?
Example:
test.com?user=employee, then show TextField = employee ID
test.com?user=customer, then show Textfield = Company name.

Any help would be greatly appreciated.

You can create a hidden element called 'user' which can be prepopulated via the URL, then this hidden element can be used to conditionally hide/show other elements and even the submit button.

Below is the YAML source for a proof-of-concept.

user:
  '#type': hidden
  '#title': user
  '#prepopulate': true
customer_name:
  '#type': textfield
  '#title': 'Customer name'
  '#states':
    visible:
      ':input[name="user"]':
        value: customer
    required:
      ':input[name="user"]':
        value: customer
employee_name:
  '#type': textfield
  '#title': 'Employee name'
  '#states':
    visible:
      ':input[name="user"]':
        value: employee
    required:
      ':input[name="user"]':
        value: employee
actions:
  '#type': webform_actions
  '#title': 'Submit button(s)'
  '#states':
    visible:
      - ':input[name="user"]':
          value: customer
      - or
      - ':input[name="user"]':
          value: employee

Personally, I would change the 'user' from a hidden element to a select menu, just-in-case someone navigates to the form without any query string parameters, they would still be able to select the 'type of user'.


How form layout of user login page can be changed Drupal 7 without altering its tpl file ? I want to change the layout of user login form in Drupal 7. I don't want to change or create its tpl file for that purpose. Is there any module which will works for me ?

Have a look at hook_form_alter. You have to change the #weight property of the form elements.

If you don't know what I'm talking about have a look at the FAPI reference and quick start guide.