Ongoing email alerts for content "assigned" to users via Entity Reference I have put together a work tracking/scheduling system for the company I work for - it's built on Drupal 7 and basically enables clients, projects and tasks to be added and assigned to eachother (i.e. tasks added to projects, projects added to clients) via Entity Reference fields.

These three items are set up as Content Types, and both projects and tasks have statuses (active, ongoing, complete, etc) served by Taxonomy vocabularies. I'm also using Entity Reference to enable tasks to be "assigned" to users.

What I want to do next is set up two email alerts:

An email alert to the user when a new task assigned to him/her has been added
Ongoing email alerts summarising all outstanding (i.e. status not set to "complete") tasks (this would be daily, bi-daily or weekly)

I think the first is best catered for using Rules, but I'm not sure how to tackle the second. I know it depends on filtering by status and the reference field as well as being sent out at predetermined intervals, so I know it would probably involve Rules and Cron, but I don't know where to go from there.

http://nodeone.se/en/learn-the-rules-framework
Check out episodes 2 and 3 in particular. Then watch the rest of the series. Then watch all the other series. Then rejoice that Johan Falk is so freakin' awesome.


hook_form_alter or overriding the routing and UserLoginForm class I am trying to add another mechanism for login into Drupal (adding an SSO function which would validate based on some criteria that a third party system will provide to Drupal).

I am trying to decide whether using hook_form_alter() (like I would in Drupal 7) is the more "Drupal 8" way or if altering the routing (shown below) so that it goes towards my custom login class that extends UserLoginForm would be a better option. I am guessing that the second approach is considered the "proper" way to do things.

Routing:

user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

Class I would be extending in my own custom class:

class UserLoginForm extends FormBase {

}

So my real question is this - if I need to override the login mechanism (including both the SSO functionality as well as standard Drupal authentication if the SSO login fails), what is the "proper" method to do this?

I would definitely go for the second option. In my opinion the form_alter hooks are reserved for 'minor' changes to a form. I always use custom forms as much as possible (extending the original form).


How to change the title of a modal window? I have a link that displays a modal window.

The link redirects to a page view.

When I click on it, it is marked in the title of the modal window Array.

How to customize the title ?

<?php

namespace Drupal\commerce_agree_cgv\Plugin\Commerce\CheckoutPane;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the completion message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "agree_cgv",
 *   label = @Translation("Agree CGV"),
 *   default_step = "review",
 * )
 */
class AgreeCGV extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $store_name = $this->order->getStore()->getName();
    $store_id = $this->order->getStoreId();
    $pane_form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $attributes = [
      'attributes' => [
        'class' => 'use-ajax',
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => auto,
        ]),
      ],
    ];
    $link = Link::fromTextAndUrl(
      $this->t('the general terms and conditions of the store "@store_name"', ['@store_name' => $store_name]),
      Url::fromUri("internal:/store/$store_id/cgv", $attributes)
    )->toString();
    $pane_form['cgv'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept @cgv.', ['@cgv' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

}


Compine the author id's of two nodes in views and display block if equal I know the title is really bad and not descriptive at all, but here is the case :

On a Drupal 7 site, each user has a "profile" page, which is a node of a certain content type, created upon registration (Content Type A).
So far , so good. I want to let each user create nodes of a Content Type B, and display their preview on their "profile" page.

For Example, let's say each user is a musician and each user has a profile page presenting themselves with several blocks and views. The purpose is to let them create content concerning their gigs, and display the resulting block with the list of the upcoming gigs.

The problem is, that trying to create a view achieving it, i cannot use as a filter the ideal, which would be something in the form [Content_Type_A][nid][authorid] = [Content_Type_B][nid][authorid], so as to display the nodes of content type B that are created only by the same author.. I tried with contextual filters (author id), but this refers only to the node that is displayed in the view (in this case Content_Type_B), so, it has no result.
Maybe it is something really really simple, but i'm stuck, since i have to declare the two types of nodes in the view in order to compare their author's ids.

Any help would be very useful.

I can't comment, so I'll answer instead.
If I read your question correctly, you want to show multiple specific views on a specific content type which you have associated as a profile page.

You could do the following in each view:

Create a relationship to the Author
create each view as a block, using a contextual filter

(author) User:Name
When filter value not available: provide default, Raw value from URL, Path component 2
path users/%/view-name

add it as a block in an appropriate place for your theme, and restrict it to show only on   users/*   pages

I have done this to show recent blog entries in a profile page.


Is there a way to hide images from the media library? I'm using the media module, and I'd like to hide some images (in a certain subdirectory) from the files overview in the admin area.

Is this possible?

Thx in advance!

Yes, in version 2.x of the media module the media browser is implemented as a view. This is the key to doing any sort of customisation to the browser. You should be able to see it in admin/structure/views and override it as you would with any other view.

The media browser view uses files as it's base type. It has some existing filters for filename, type etc. You can add another one that filters by path. If you use the starts with operator and value public://foo/. That will end up doing a SQL LIKE query on the uri column of the file_managed table, which should give you what you want.

It's worth noting that you can customise the media browser only for certain file fields. To do that, clone the view instead of overriding it, thereby giving you two media browsers. Then for each field that uses a media widget, you need to choose which browser(s) you want.


Flag content once seen in a slideshow Is there a way with either flags or rules or another module to make content being displayed in a slideshow flagged/marked as "viewed"? Then on refresh that content wouldn't display again to that user. Functionality of swiping for the mobile experience is key here. Think of it as a simplified tinder functionality.

I think No Sssweat comment is right in that this requires custom code.. And you should include some extra details regarding Pierre's questions.

Assuming that you want it like Tinder, I think triggering a hidden flag on each node for each swipe event could be the easiest option. Then on refresh, a views filter would hide flagged content by that user.

This answer describes a method for doing similar. I haven't tested it myself yet but it's an accepted answer and quite recent so it should still work.

It's hard to give a more thorough answer for this without knowing more about the slideshow. And my jQuery is rudimentary at best. If this is a viable approach, post some more details and hopefully myself or another user can help with getting the event. If not, I'll remove this.


Service to browse all contrib modules on drupal.org http://simplytest.me/ allows you to search all existing modules. I'm trying to implement a widget with the same functionality, but I'm stuck on how to browse all the projects on drupal.org... Can someone point me in the right direction? I found the module "project_browser", but can't seem to figure out how they accomplish it...

This excellent script written by rocketeerbkw will create a text file containing the name of every d.o contrib module, giving you everything you need to get started:

/**
 * Download a full list of all modules on drupal.org by using the API. More info
 * at https://www.drupal.org/about-drupalorg/api.
 */
$url = 'https://www.drupal.org/api-d7/node.json?type=project_module';
$modules = array();
do {
  print $url . PHP_EOL;
  $options = array(
    'http' => array(
      'user_agent' => 'get_list_of_modules.php from https://github.com/rocketeerbkw/drupal_function_stats',
      'header' => 'Accept: application/json',
    ),
  );
  $context = stream_context_create($options);
  $response = file_get_contents($url, false, $context);
  $data = json_decode($response);
  foreach ($data->list as $module) {
    $modules[] = $module->field_project_machine_name;
  }
  $url = isset($data->next) ? $data->next : FALSE;
  // The next links are always provided without a format [#2253947].
  // Formatless URLs are 301 redirected to format URLs but strip all query
  // query parameters [#2364755].
  $url = str_replace('node?', 'node.json?', $url);
} while ($url);
$file = fopen('project_usage.txt', 'w');
fwrite($file, implode("\n", $modules));
fclose($file);

An example output is here:

https://raw.githubusercontent.com/rocketeerbkw/drupal_function_stats/master/project_usage.txt

Once you've got that data the only tasks are deciding where/how to store it, and creating the UI to manage it.


Preview template for node with custom template? I have a custom content type, 'Article with Header' for which I have a custom twig template, 'page--article-with-header.html.twig', which manages the layout for this content type. When I preview the node before publishing, the template used is page.html.twig. I would like to have the same layout for previewing as for when the node is published, but I don't see any options for doing this. The template suggestions that come up in preview mode (page--node--preview.html, for example) would affect every content type.

Is there a naming convention for preview mode twig templates for custom content types that I'm missing? Is there a preprocessing function I can implement that will force the preview mode for this content type to use the correct template?

The naming convention is
node--[type]--[viewmode].html.twig

So in your case it would be

node--article-with-header--preview.html.twig

See https://www.drupal.org/docs/8/theming/twig/twig-template-naming-conventions
for more info.


Can I check a user is logged in using Services I need to be able to integrate an external PHP script with Drupal 7. However because the script also connects to a MySQL database errors are produced when I include the bootstrap.inc, so I'm looking at using the Services module. Will this allow me to determine if the user is logged  in to Drupal, and if so get details about the user? If so, could you please show me how this could be done.

Also, is it possible to secure the server/service so that it can only be accessed by scripts on the same host?

Services module works with the entity system so you should be able to pull some user data out of the box like email, username etc. I'm not exactly sure if Services modules send you any clue about user data that you can use to determine if the user is online or not but you can add a small custom code that alter the read functionality of the Services for User entity to query and return the current session. See code sample below.

Couple of function you might need in the process is:

// you can alter the resources object and use your own
hook_services_resources_alter()

// implement it as below in your custom module
function YOURMODULE_services_resources_alter(){
  $resources['user']['retrieve']['callback'] = '_YOURMODULE_api_user_resource_retrieve';
}

// then implement the retrive
function _YOURMODULE_api_user_resource_retrieve($uid){
    $account = user_load($uid);
  if (empty($account)) {
    return services_error(t('There is no user with ID @uid.', array('@uid' => $uid)), 404);
  }

  services_remove_user_data($account);
  // DO YOUR SQL TO CHECK IF USER IS ONLINE
  // _check_this_user_online($uid);

  // Everything went right.

  return $account;
}


Field Collection fields not displaying I have been running into some trouble with displaying Field Collections. I have a content type (products) that has a field collection called packages. Randomly I would notice that sometimes the field collection fields wouldn't display. Today they have stopped displaying and aren't coming back.

I can't seem to figure out what the issue is. All the fields are set to display in the field collection display settings. Even when I just look at the node view page they aren't displayed there.

I was curious if anyone can help with this issue?

EDIT: It appears that enabling and disabling modules (doesn't matter which one) fixes this and the fields display. Not sure what triggers it to break again though.

You can at least start debugging the issue using the devel module: it can tell you if the field collection entity is loaded (so, a render problem) or not.
Also it can gives you the id of the entity for further debugging.


How can I prevent an organic group administrator from accessing edit page of a group? I want them to be able to post content only, not edit the group itself.  I'm using og_read_only so they can only post content to their own group as well.  This module has a problem though, you have to select which content types are read only each time you create a group, and if you add content types, you have to edit all of your groups again and check off the new content type as read only.

Is there a module that can prevent the group admin from accessing the group edit page?  Would that module also be able to prevent the admin from posting to a group that they are not a member of?

I will accept an answer if it only covers preventing the group admin from accessing the edit page.  I was just hoping the other issue might be covered by the same module since they both seem related to access control.

My suggestion would be to use rules to redirect users that aren't admins to another page, or use hook_menu_alter() to alter the access permissions to the page. Alternatively, you can use hook_page_alter() to check the active user's roles and redirect them if they aren't in the admin group.


Blogging platform using Drupal 7 I am planning to make blogging platform using Drupal 7. In which I am going to allow user to create his own site using my subdomain. Is this possible with Drupal 7?

Which modules I am going to need?

If I understand correctly, you're looking at either the core blog module (which isn't that great), or a combination of content types and Views.

Start here for blog building information!

With regards to the second part, are you looking to have the user create a site, and then start blogging on it?  Wordpress.org style?  For that you'll firstly need to get a solid theme in place, as well as a working blog.  Secondly, look into Aegir which is a REALLY solid, powerful tool for creating Drupal sites off the back of another site (using a site as an installation profile almost...but not quite).

There are a couple of installation/demonstration videos here and here.


How to display "About the author" tab in article display page? I want to basically override the normal display of article, to include two tabs in that. One tab will be "Read Article", which when clicks loads the article page. Others tab will be "About the Author", which when clicks loads the author page.

So ultimately when I go to any article page, there will be two tabs, "Read Aricle" (selected by default), and "About the author".

Please suggest how can I achieve this. I have tried overriding node display by using Panels, but I am not able to add links or display author information in another tab.

-- Thanks for your time.

There is Author Pane

  Author Pane is a block of information about a given user, like those
  typically found on a forum post, but can be used in other places as
  well. From core, it collects the user picture, name, join date, online
  status, contact link, and profile information. In addition, any module
  or theme can feed it more information via the preprocess system. All
  of this information is then gathered and displayed using a template
  file.

For the tabbed view you cold try Quick Tabs

  The Quick Tabs module allows you to create blocks of tabbed content,
  specifically views, blocks, nodes* and other quicktabs*.


Set fields in uc_addresses checkout pane to disabled I want to disable the billing address fields in uc_addresses so they cannot be altered by the user while they're checking out.  However, I cannot find a form to use hook_form_alter on.  It seems those fields are living inside a pane, but I don't know how to isolate and edit that.

I suppose this is one of those times they told me about where all I want to do is hack the other modules.

edit1:
If you're interested here's the function that controls the panes and calls up the form.  I don't really understand how it works.

It must be a form and You can alter via hook_form_alter.
But in function you should must check the form_id and after that print_r or dpr or dsm (whatever you like ) the $form. And search for the address field and unset it.


Reviewing and displaying node reviews in Drupal 7 I have to create a Movie content type that's going to be submitted by the Admin, but where anonymous users will have the possibility of adding a review.

As I'm using D7 (making NodeReview not an option), I was thinking of using the Vote API and fivestar.

My actual question is (and please excuse my n00bness): can I somehow embedded a "Review" content type (that's going to have fivestar, author name and a short text) in the Movie nodes and expose that to anonymous users?

Could someone point me what the Drupal way would be in this case?

If you wanted to do this very simply, you could just add a fivestar field to Drupal's built-in comments.  Comments already provides the author name and a description field (the comment), and enabling comments on nodes is easy (you can do it from structure/content types).


just want to change checkbox value while submit I am using drupal 7:

$form['title']['#tree'] = TRUE;
$form['title']['node_first'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
        'value' => $value->title,
    ),
);
$form['title']['node_second'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
        'value' => $value2->title,
    ),
);

i am getting this output after submitting (when first checkbox has been checked) :

    Array
(
    [title] => Array
        (
            [node_first] => Array
                (
                    [value] => value
                )

            [node_second] => Array
                (
                    [value] => 0
                )

        )
)

desired output:

Array
(
    [title] => Array
        (
            [node_first] => Array
                (
                    [value] => True
                )

            [node_second] => Array
                (
                    [value] => False
                )

        )
)

It should be possible to manipulate the values as desired in a custom validate function. In your form code, add something like this:

$form['#validate'][] = 'mymodule_custom_validate';

The mymodule_custom_validate is a function you could define as such to change the values to booleans, or anything else you need:

function mymodule_custom_validate(&$form, &$form_state) {
  if ($form_state['values']['title']['node_first']['value'] === 'value') {
    $form_state['values']['title']['node_first']['value'] = True;
  }
  else {
    $form_state['values']['title']['node_first']['value'] = False;
  }
  if ($form_state['values']['title']['node_second']['value'] === 'value') {
    $form_state['values']['title']['node_second']['value'] = True;
  }
  else {
    $form_state['values']['title']['node_second']['value'] = False;
  }
}

This is a fairly rudimentary implementation, but hopefully this will lead you in the right direction. You can see in this example how the values can be manipulated before they reach the submit handler.


Remove "No front page content has been created yet" How can I remove default system message like "No front page content has been created yet" in Drupal 8?

I've tried below method but is doesn't work.

function MYTHEME_preprocess_page(&$vars) {

  // Remove the "No front page content has been created yet.".
  if (isset($vars['page']['content']['system_main']['default_message'])) {

    unset($vars['page']['content']['system_main']['default_message']);
  }
}

There are many possible solutions for this problem, but here are a few of the more straightforward ones:

Edit the Frontpage view at /admin/structure/views/view/frontpage as follows:

This View form allows you to adjust the out-of-the-box front page. In the NO RESULTS BEHAVIOR section, click on the Global: Unfiltered text item. This will open a dialog box to edit that setting. From here you can see that this is where the undesirable message is coming from. Click on the Remove link beside the bottom buttons to remove that message. Depending on the desired front page behavior, you may also want to remove one or both of the other items listed under NO RESULTS BEHAVIOR.

Once you've removed the unwanted items, be sure to click the Save button on the View form to make those changes permanent. You can then browse to the front page and see the results. (You might need to Clear all caches at /admin/config/development/performance to see the change)

Or, create a custom front page:

Create new content of type Basic Page. Give it the title you want your front page to have. For the body, you can leave it blank, or put whatever static content you want to always appear on the front page. After saving and publishing this new content, write down the "/node/some-number" part of the URL.

You can now set this new node as the front page at /admin/config/system/site-information by changing the Default front page setting to the /node/some-number you wrote down earlier. Save the settings and things should be all set.

To do it programmatically, you might add this code to your custom theme or module

use Drupal\Views\ViewExecutable;

// Implements hook_views_pre_render().
function MY_THEME_OR_MODULE_NAME_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'frontpage' && $view->current_display == 'page_1') {
    // Use some or all of the following 3 lines to remove specific
    // 'no results' behaviors
    unset($view->empty['area_text_custom']);
    unset($view->empty['node_listing_empty']);
    unset($view->empty['title']);
  }
}

or you could use $view->empty = []; instead of the 3 separate unset()'s to remove all "no results" behaviors from the frontpage view. Note that this code assumes you haven't changed the view's name or display name from the defaults. If this is not so, the if() statement will require some tweaking.


Give a role permission to add and edit their terms in a taxonomy In Drupal 7 I am trying to give users the ability to add terms to a taxonomy and then edit only the terms they have created.

I'm using the Taxonomy access fix module to give users permission to add terms in specific taxonomies. However, Drupal does not provide an "edit own terms" permission like it does for nodes. Users can either edit all terms in the taxonomy, or not have editing permission.

Is there any solution for this?

If drupal doesn't provide any "edit own terms" permission, then better do it programatically if you wish.

While accessing term page, load/check for the owner of term and allow them to access edit page.


How to pass theme variables in #theme in a form element? I need to pass product variable defined in hook_theme() and invoked in #theme
but not sure how to pass product variables in #theme
Please suggest.

    function storeinv_theme() {
      return array(
        'storeinv_pickup' => array(
          'variables' => array('product' => NULL),
        ),
      );
    }

    function storeinv_uc_product_description($product)      {
      $description = array(
        'pickup' => array(
          '#product' => array(
             '#type' => 'value',
             '#value' => $product,
           ),
           '#theme'  =>'storeinv_pickup',
           '#weight' => 1,
         ),
      );

       return $description;
}

    function theme_storeinv_pickup($product){

            $data = $product['#value']->data;

            if (isset($data['pickup']['store_id']))
            {
                    $store_id = $data['pickup']['store_id'];
                    $day = $data['pickup']['day'];
                    $date = date( 'l m/d/Y g:ia', strtotime( $day ) );
                    $result = views_get_view_result('field_altstoreid_value','default');
                    foreach($result as $k => $v){
                      if ($store_id == $v->field_altstoreid){
                            $name = $v->title;
                            return "<p>Pickup " .$date."at " . $name." </p>";
                      }
                    }
            }
            else {
                    return '';
            }
    }

Minor syntax change required...

function storeinv_uc_product_description($product)      {
  $description = array(
    'pickup' => array(
      'product' => array('#type' => 'value', '#value' => $product),
      '#theme'  =>'storeinv_pickup',
      '#weight' => 1,
    ),
  );
  return $description;
}

Your product variable doesn't need to be prefixed with a hash character. Thats used for specific keys/properties of the render array.


How to get node id from URL? I want to pass a URL to a function. This function should get the node ID from the URL.

How to do this?

You can try the following code (please note that about-us is merely an example page - you can put whichever page you want here):

$url = 'about-us';
$path = drupal_lookup_path('source', $url);

if ($path) {
  $node = menu_get_object('node', 1, $path);
  return $node->nid;
}
else {
  //Error handling in case path provided does not exist
}

The code above returns a whole node object though, which might be expensive depending on how often you run it - another option would be to run explode() on the output of drupal_lookup_path() and just take the NID that way.

References:

drupal_lookup_path();

menu_get_object();


How to remove JS from a page during preprocess D7 I'm trying to remove few JS files from one page, which will be called in an Iframe (so no TEMPLATE_js_alter possible because of the if condition).

This code below unset the JS but they are still loaded on the page. It's like I can't save the new list of JS.

Any ideas ?

 function theme_preprocess_page(&$variables) {
        $scripts = drupal_add_js();
        dsm($scripts);

        if(arg(0) == "account" && arg(1) == "reset"){
            foreach ($scripts as $key => $value) {
                $uri = strrpos($key, 'sites/all');
                if($uri !== FALSE){
                    unset($scripts[$key]);
                }
            }
            $variables['scripts'] = $scripts;
        }
    }

You can try hook_js_alter and remove it from there:

module_hook_js_alter(&$data) {
  dpm($data);
  unset($data['script']);
  dpm($data);
}


Display subscribe to group on access denied page I am using Drupal 7.25 (I need to update to 7.26) and organic groups 7.x-2.4.  I currently have public and private groups working.  I have two users (admin and a normal user).  I have a menu tab that opens the og list (/og-list) view which lists all groups (public and private).

When logged in as a normal user if I click on a public group it shows a subscribe to group link.  That's great.  However, if I click on a private group it gives me the Access denied page without a subscribe link.

I would like to have any normal user be able to click a private group and have it display a link to subscribe.  Any help would be greatly appreciated!

You have a couple of options.

Not sure how you have your group node page setup but what I have done is use a node view panel.  In that panel I added the Field: Group (group_group) in a region then set the formatter to "OG subscribe link".  That will display the "Subscribe to group" link when a user clicks on the group they are not a member of.  Since you are getting access denied I'm guessing your group node page is not setup that way.

Another option is to modify the og-list view and add the field "Content: Group".  Then change its Formatter to "OG subscribe link".  That will create a new column in the view that will display a link called "Subscribe to group" for groups you are not a member of and "Unsubscribe to group" for groups you are a member of.


How to batch upload images and generate multiple images I am planning my new website with Drupal 7. The site will have two core features: blog and photos. Blog is no problem and for photos I know how to implement most of my requirements. Except one ;-)

I plan to add a content-type "Photos" (or "Media"). Each photo will be stored in its content. These contents are categorized using a taxonomy so each photo can be in multiple terms (aka albums). For example a whale can be in "Underwater", "Big-fish" and "Salt water". Views with contextual filters will render the "album"-views etc. So far no problem.

What we don't know how to do yet is bulk-upload of images. Any idea would be great. If there is a gallery module or profile that handles that taxonomy thing / dynamic albums it would be an option to.

Idea: Maybe I can define a "Bulk-Upload" content type which is for uploads only. This conent-type has an "image" field set to "unlimited". When creating such a content a Rule will be triggered which creates multiple "Images" contents for it and deletes the "Bulk-Upload" content afterwards. ...sounds possible but a little tricky.

Any ideas?

Thanks and cheers,
Marc

To upload more than one image to a field you can change the number of values the field will accept:

To get a photo album configuration you could also look at the node_gallery module, or roll your own arrangement.

The plupload module will allow you to select multiple images to be uploaded into a single field through one upload process.


How do i show a not-equals operator for rules while setting up commerce shipping conditions? I am setting up my commerce shipping conditions and i need a NOT Equal operator so i can target all international countries. how can this be done?

Choose "=", then at the bottom of your condition, enable "negate".  It's just below where your screenshot is cut-off.


How to show only oldest and newest node in Drupal views? I want to create a view that only shows the oldest and newest node of a certain content type what is the easiest way to do this?

Thanks

How about creating a contextual filter in view, and take a look at the below image to select any of these creation dates?

Afterwards, filter your content type as in the following image:


Webform field default value + Profile field value I have a simple Webform (https://www.drupal.org/project/webform):

Single field called "name".

I also have a Profile (https://www.drupal.org/project/profile):

Profile is called "basic_profile".
Profile contains 2 fields: "field_name" and "field_department".

I want the default value of my Webform field "name" to be the content of the user's Basic Profile value for "field_name", but I cannot save the form because "Default value is using the following invalid tokens".

I have also tried using "[webform-authenticated-user:display-name]" which does not work.

I have tried using "[current-user:display-name]" which works but does not give me the info I want.

So how can I get the user's profile values to be used as default values for form fields? Thanks!

P.S.: The reason for this is that we are authenticating via Active Directory, and Drupal will be loading a user's profile from AD upon login. Therefore we want to leverage all data that exists in AD.

composer.json:

{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6",
        "drupal-composer/drupal-scaffold": "^2.2",
        "drupal/adminimal_admin_toolbar": "^1.5",
        "drupal/adminimal_theme": "^1.3",
        "drupal/business": "^1.7",
        "drupal/business_responsive_theme": "^1.1",
        "drupal/console": "^1.0.2",
        "drupal/core": "~8.5",
        "drupal/devel": "^1.2",
        "drupal/domain": "^1.0@alpha",
        "drupal/domain_theme_switch": "^1.3",
        "drupal/eform": "1.x-dev",
        "drupal/honeypot": "^1.27",
        "drupal/insert": "^1.0",
        "drupal/maestro": "^2.1@RC",
        "drupal/mailsystem": "^4.1",
        "drupal/metatag": "^1.4",
        "drupal/module_filter": "^3.1",
        "drupal/paragraphs": "^1.2",
        "drupal/pathauto": "^1.1",
        "drupal/profile": "^1.0@RC",
        "drupal/token": "^1.3",
        "drupal/webform": "^5.0@RC",
        "drupal/workflow": "^1.0",
        "drush/drush": "^9.0.0",
        "kint-php/kint": "^2.2",
        "webflo/drupal-finder": "^1.0.0",
        "webmozart/path-util": "^2.3"
    },
    "require-dev": {
        "webflo/drupal-core-require-dev": "~8.5"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ]
    },
    "scripts": {
        "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold",
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"]
        },
        "patches": {
            "drupal/domain": {
                "Drupal Domain New Content Type Domain Fields": "https://www.drupal.org/files/issues/2018-03-15/2953168-da-form-display-13.patch"
            }
        }
    }
}

According to Make profile fields avalaible as tokens, tokens for Profile fields was added, but it was added to dev 4 months ago. Since the 8.x-1.0-rc1 version was released 9 months ago, it does not have tokens.

So either switch to dev version until they release it or apply the patch provided on #22 to 8.x-1.0-rc1.


Default user relationships with the site admin I am using the User Relationships module for my Drupal7 site. I have created a one way relationship with reciprocal by the name "Follower". So if User A can be followed by User B. Also, User A can follow User B. Now i set out in the process of creating a default relationship. I did that but it works only one way. I want that by default all user follow and are followed by the ADMIN. the default relationship that i created through the CMS works fine but it works only one way. I see that Admin is following the users but not vice-versa. Also, this happens only for new users of the site. I do not see old users having that default relationships. How can i achieve that? Any suggestions.

I was able to achieve this with rules + user relationship rules modules.

Export:

{ "rules_follow" : {
    "LABEL" : "follow",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "user_relationships_rules", "rules" ],
    "ON" : [ "user_insert" ],
    "DO" : [
      { "user_relationships_rules_action_create_relationship" : {
          "relationship_type" : "1",
          "requester" : [ "account" ],
          "requestee" : "1",
          "approve" : 1
        }
      }
    ]
  }
}

Rule Details:
Event: After saving a new user account

Conditions: None

Action: Request, create or approve relationships between users

Rule Settings:
Relationship Type: [your defined relationship] (follower)

Requestor: (Data Selection Method) Data selector "account"

Requestee: (Direct input mode) "1" (or the user ID of your admin account)

Approve Relationship: TRUE


views_query_alter change to operator OR for contextual filters and normal filters My question is rather simple and I have searched quite a bit for the answer with no result.
My view produces below SQL (simplified):

SELECT stuff
FROM
tableA
LEFT JOIN tableB
LEFT JOIN tableC ON stuff
WHERE (( (MY_CONTEXTUAL_FILTER = '5' ) )AND(( (MY_NORMAL_FILTER IS NULL ) )))

All I want to do is to change that AND between the contextual filter and normal filter. I have tried to change all ANDs (including set_group_operator()) to OR and it does not change my AND.

Also need to mention it is an 'Entity Reference' display which I am trying to achieve the above on. Views version 7.x-3.7.

UPDATE

In order to achieve the above, I also tried hook_views_pre_execute() as below:

 $old_query = (string)$view->query->query();
 $new_query = str_replace('AND', 'OR', $old_query);
 $view->build_info['query']=$new_query;

But that doesn't work and throws and error. I know they are different approaches with different issues but both are trying to solve one problem.

As a simple try to help, did you implement hook_views_query_alter(&$view, &$query) as following ?

First, call Views API in YOUR_MODULE.module :

/**
 * Implementation of hook_views_api().
 */
function YOUR_MODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'YOUR_MODULE_NAME'),
  );
}

Create a file YOUR_MODULE.views.inc. It seems that with Views, you don't need to put files[] = YOUR_MODULE.views.inc in your module's .info file, as you usually would.

Then implement hook_views_query_alter() in views.inc.

function YOUR_MODULE_views_query_alter(&$view, &$query) {

  if($view->name == 'VIEW_NAME') {

    dpm($query);
    //at this point find the right part to alter and adapt following line
    $query->where[0]['type'] = 'OR';

  }
}

EDIT: If for any reason, you can't override the View with hook_views_query_alter(), Views Filter Harmonizer might fit your need.

  Views Filter Harmonizer solves an operational foible with the Views
  module regarding filtering. This small module allows you to have a contextual filter argument apply only when there is no corresponding regular (exposed) filter value present.

Last, check also Views arguments in filters sandbox, or test this patch. Both rely on the same logic, setting a "Global: Null" contextual filters and using it in regular filters. Many people report using it to solve the same And/Or contextual filters issue. Good luck !


Custom status message on a Views page I have different urls :

domain.com/blog : a list of articles made with Views module
domain.com/blog/article-title : article alias
domain.com/newsletter/confirm/add/xyz/ok : confirmation link sent to new subscribers by email by Simplenews module
domain.com/blog/ok : page to which subscribers are redirected after they click the confirmation link (simplenews passes the last arg to the redirect page)

For now, domain.com/blog/ok returns the same as /blog or a 404 (if I set the Global:null contextual filter in Views). I'd like new subscribers to be redirected to the blog page with a custom status message (for instance "You're now subscribed").

I guess it's something with hook_menu ? or MYTHEME_preprocess_page ?

In case someone's interested, I finally got it fixed implementing a simplenews hook :

function MY_MODULE_simplenews_subscribe_user() {
  drupal_get_messages('status'); // Flush default simplenews status message
  drupal_set_message(t('My custom message'), 'status'); // Set my own message
}


WSOD "The provided host name is not valid for this server" My Drupal 8 site only works with www. but without it I'm getting a WSOD with the "The provided host name is not valid for this server" error.

I've tried to implement the suggestions from this thread:
What does "The provided host name is not valid for this server" mean?

Specifically I tried:

$settings['trusted_host_patterns'] = array(
  '^www\.example\.com$',
  '^example\.com$'
);

$settings['trusted_host_patterns'] = [];

$settings['trusted_host_patterns'] = [ '.*' ];

Still, site will only work with www

You need to add your domains into the array as per your first example. I.e.

    $settings['trusted_host_patterns'] = array(
  '^www\.yourdomain\.co\.uk$',
  '^yourdomain\.co\.uk$',
);

Then clear the caches and the message should go away. It may be that you're missing the comma after your second entry.


24 hour notation for Time Field I'm using Time Field to make a field in my event content type for the begin and endtime in of the event.
I know that when you outpout the time field via views, you can output it as 24h notation, which works fine. But I want to output the time using php in a tpl file
using the row object.
So I have php code in my views tpl file that says:

    <?php $uur  = $row->field_field_evenement_uur[0]['rendered']['#time']['value_formatted'];
          $uur .= ' - ';
          $uur .= $row->field_field_evenement_uur[0]['rendered']['#time']['value2_formatted'];
?>

First thing that came to mind of course was go to admin/structure/types/manage/my_content_type/fields/my_time_field and set the field formatting to 24h notation. It simply looks though like it's not part of the configuration.

Then I debugged my $row output in my view to discover this other way to get a rawer sort of value for the time. This way I would write code like:

$row->field_field_evenement_uur[0]['raw']['value'];

So that would output the time value like 51600. I've been looking for some formatter functions that I could wrap around this value and get me a 24hour notation, even from php.net but it's all seeming like it has to do with the date(); function.

I totally looked past the display fields part of the field configuration of fields ui. That's exactly where you can set it to output 24hr notation.


How to render a template in Drupal 8 I am trying to render a template in Drupal 8. In Drupal 7, I would create a theme with hook_theme, make a templates directory in my module, drop the template file in and I could display it with theme(). How do I do the eqivilent with Drupal 8? I tried the following, but it errors out:

In twitter_pull.module

/**
 *  Implements hook_theme().
 */
function twitter_pull_theme($existing, $type, $theme, $path) {
  return array(
    'twitter_pull_tweet_listing' => array(
      'variables' => array(
        'description' => array(),
      ),
      'template' => 'templates/twitter_pull_tweet_listing',
    ),
  );
}

Inside twitter_pull/templates: the twitter_pull_tweet_listing.html.twig

Inside my block:

$tweet_template = array('#theme' => 'twitter_pull_tweet_listing', '#attributes' => array('params' => $params));
$output = drupal_render($tweet_template, array('params' => $params));
print $output;

I get the following error in my logs:

User error: "content" is an invalid render array key in Drupal\Core\Render\Element::children() (line 89 of C:\xampp\htdocs\drupal\core\lib\Drupal\Core\Render\Element.php).

EDIT:
Another error:

Twig_Error_Loader: Unable to find template "modules/custom/twitter_pull/templates/templates/twitter_pull_tweet_listing.html.twig" (looked into: C:\xampp\htdocs\drupal). in Twig_Loader_Filesystem->findTemplate() (line 202 of C:\xampp\htdocs\drupal\core\vendor\twig\twig\lib\Twig\Loader\Filesystem.php).

I imagine this error is happening because I'm not using namespaces and autoloading correctly. Where do I put my template file? Based on the error message, I even tried to put it at C:\xampp\htdocs\drupal\templates\ but it still did not work.

In general in Drupal 8 you should leave out the template line and name the template the same as your hook, converting the underscores to dashes. This was changed because templates are the default output format for themeable output in D8. So in your case this hook_theme():

/**
 *  Implements hook_theme().
 */
function twitter_pull_theme($existing, $type, $theme, $path) {
  return [
    'twitter_pull_tweet_listing' => [
      'variables' => [
        'description' => [],
      ],
    ],
  ];
}

…would point to a template at templates/twitter-pull-tweet-listing.html.twig. (That's using short array syntax.)

Relevant change record: https://www.drupal.org/node/2231673

And also, from a block or controller, please return a render array instead of a string. That way the results can be manipulated afterwards and the raw data is still accessible down the line. In other words, avoid calling drupal_render() from your code whenever possible. This applies to Drupal 7 as well: https://www.drupal.org/node/930760#creating

So from your block:

return [
  '#theme' => 'twitter_pull_tweet_listing',
  '#description' => 'foo',
  '#attributes' => [],
];


How to create a URL to an unmanaged public file in Drupal 8 I'm running into a problem creating a URL to an unmanaged file in the "public" file directory (this is for the file_example for Drupal 8).

The following code will throw an exception:

use Drupal\Core\Url;

$stuff = "content for an unmanaged file\n";
$dest = file_unmanaged_save_data($data, "public://unmanaged-mahem.txt");

print "URI: $dest\n";
$url = Url::fromUri($dest);
$our_uri = $url->getUri();
print "Our URL was created, and thinks it corresponds to the URI $our_uri\n";

//but this throws:
$external_link = \Drupal::l(t('External link'), $url);
print "External Link: $external_link\n";

When run, here's what you see (the stack trace is removed):

$ drush @d8 scr unmanaged-mahem.php
URI: public://unmanaged-mahem_1.txt
Our URL was created, and thinks it corresponds to the URI public://unmanaged-mahem.txt
exception 'InvalidArgumentException' with message 'The URI 'public://unmanaged-mahem_1.txt' is invalid. You must use a valid URI scheme. Use base: for a path, e.g., to a Drupal file that needs the base path. Do not use this for internal
paths controlled by Drupal.' in /var/www/drupal/core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php:69

I'm not sure if this is a bug or if this is by design, since in general, you'd want to use a managed file for anything in the public files directory that was for public consumption.  But the change record doesn't say anything about this.

Is there a valid way to create a link to an unmanaged file in Drupal 8?

You need to run the file path through file_create_url() and then use it together with base:

Url::fromUri(file_create_url($dest));

(file_create_url() should return absolute URL's, so you don't need base)

There's an issue to simplify that: https://www.drupal.org/node/2539622


Does Drupal have a collaborative editing module? What I would like to offer my users is the ability to propose a writing project to a group of people (users and non users) and the people who want to join the writing project are able to edit the same node together in separate locations.

The answer from knowledges33ker is a good start.

However the workbench module - https://drupal.org/project/workbench
 - might also help with this and add further functionality.

Particularly in that it offers good tracking of edits that have been made to content and you can revert content to previous revisions etc.

With the user reference field set up, you could also, if you wanted, use the Rules module - https://drupal.org/project/rules - to fire emails or notifications to users when the content is edited/updated.


managed_file upload clearing $form_state I am having an annoying problem whereby $form_state['values']['region'] and $form_state['values']['country'] are being cleared when I upload an image via the managed_file field. This is causing a "...tid cannot be null" error upon DB insertion (of course because the values are now null after managed_file upload). If I disable the managed_file field everything works as it should but of course I need the upload!

I am relatively new to Drupal and thus not quite understanding why this is acting like it is. Can anyone help me out as this is driving me nuts!

My form

function myforms_company_add_form($form, &$form_state, $node) {

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  if(!isset($form_state['values']['region']) && !isset($form_state['values']['country'])) {
      $selectedRegion = array_shift(taxonomy_get_parents($node->field_company_region['und'][0]['tid']))->tid;
      $selectedCountry = $node->field_company_region['und'][0]['tid'];
    }
    else {
        $selectedRegion = $form_state['values']['region'];
        $selectedCountry = $form_state['values']['country'];
    }

$form['region'] = array(
    '#title' => t('Region'),
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => _get_region_list('region'),
    '#prefix' => '

',
    '#suffix' => '
',
    '#default_value' => $selectedRegion,
    '#ajax' => array(
      'callback' => 'region_ajax_callback',
      'wrapper' => 'wrapper',
     ),
  );

  $form['country']['wrapper'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '

',
  );

  if (isset($selectedRegion)) {
    $form['country'] = array(
        '#title' => t('Country'),
        '#type' => 'select',
        '#required' => TRUE,
        '#options' => _get_country_list($selectedRegion),
        '#default_value' => $selectedCountry,
        '#ajax' => array(
            'callback' => 'region_ajax_callback',
            'wrapper' => 'wrapper',
        ),
      );
   }

  $form['company_logo'] = array(
    '#title' => t('Logo'),
    '#type' => 'managed_file',
    '#upload_location' => 'public://my-files/',
    '#required' => FALSE,
    '#default_value' => $node->field_company_logo['und'][0]['fid'],
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#prefix' => '
',
  );

  return $form;

}

Then my callback

function region_ajax_callback($form, &$form_state) {
  return $form;
}

I recently encountered the same problem. I found that data is erased in function - drupal_validate_form(). I have not fully understood why this is happening, therefore, just went bypassed the problem. I have rewritten my code so that the code section that erased the data in drupal_validate_form() is not executed.

My code:

  $managed_file_processing_fn = array_merge(
    element_info_property('managed_file', '#process', array()),
    array('ccw_managed_file_process')
  );

  $form['customization']['main']['request_design']['upload_design'] = array(
    '#type' => 'managed_file',
    '#progress_indicator' => 'bar',
    '#upload_location' => 'public://',
    '#upload_validators' => array(
      'file_validate_extensions' => array('jpg jpeg gif png zip rar tar'),
    ),
    '#states' => array(
      'visible' => array(
        ':input[name="type_of_upload"]' => array(
          array('value' => strval(CCW_GET_HELP)),
        ),
      ),
    ),
    '#process' => $managed_file_processing_fn,
    '#default_value' => $upload_design,
  );

/**
 * Process managed_file.
 */
function ccw_managed_file_process($element, &$form_state, $form) {
  // When AJAX is execute we ignore form validation.
  $element['upload_button']['#limit_validation_errors'] = FALSE;
  $element['remove_button']['#limit_validation_errors'] = FALSE;

  return $element;
}

Topic with the same problem on drupal.org:
https://www.drupal.org/node/2311199

Also, I noticed that in Drupal 8 the behavior is the same.


How do I create scrolling views? I want to scroll my views, but I don't find a module that allows this.

Is there a module for scrolling views? How can I scroll views, if there isn't a module with that purpose?

If you're looking for scrolling similar to Twitter, try the Views Infinite Scroll module.

If you're looking for something more like this site, try the Geared Scrolling module (DISCLAIMER: which I maintain).


I cannot add a new CSS class to the classes_array array I'm using Drupal 7, and a Bootstrap sub-theme. I am using the following code to add a new CSS class (taxonomy-[vocabulary-name]) to the classes_array array.

template.php

function bootstrap_gstt_preprocess_html(&$variables) {
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $results = _bootstrap_gstt_taxonomy_node_get_terms($node);
    $taxonomy_vocab = $results->name;
    if (is_array($results)) {
      foreach ($results as $item) {
        $taxonomy_vocab = "taxonomy-".strtolower(drupal_clean_css_identifier($item->name));
        $variables['classes_array'][] = $taxonomy_vocab;

        $variables['classes'] = implode(' ', $variables['classes_array']);
        dpm($variables['classes_array']);
      }
    }
  }
}

function _bootstrap_gstt_taxonomy_node_get_terms($node, $key = 'tid') {
  static $terms;
  if (!isset($terms[$node->vid][$key])) {
    $query = db_select('taxonomy_index', 'r');
    $t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
    $v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
    $query->fields( $t_alias );
    $query->condition("r.nid", $node->nid);
    $result = $query->execute();
    $terms[$node->vid][$key] = array();
    foreach ($result as $term) {
      $terms[$node->vid][$key][$term->$key] = $term;
    }
  }
  return $terms[$node->vid][$key];
}

html.tpl.php

<!DOCTYPE html>
<html<?php print $html_attributes;?><?php print $rdf_namespaces;?>>

  <link rel="profile" href="<?php print $grddl_profile; ?>" />
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>

  <?php print $scripts; ?>

<body<?php print $body_attributes; ?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

With dpm($variables['classes_array']);, the new CSS classes I added appear in the array, but they aren't output as body CSS classes.

Is there anything I need to change in my code?

You simply do as Drupal does in its html.tpl.php file. Instead of using <body<?php print $body_attributes; ?>>, you use the following code.

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

$attributes is set from template_preprocess() with the following code.

  // Flatten out attributes, title_attributes, and content_attributes.
  // Because this function can be called very often, and often with empty
  // attributes, optimize performance by only calling drupal_attributes() if
  // necessary.
  $variables['attributes'] = $variables['attributes_array'] ? drupal_attributes($variables['attributes_array']) : '';
  $variables['title_attributes'] = $variables['title_attributes_array'] ? drupal_attributes($variables['title_attributes_array']) : '';
  $variables['content_attributes'] = $variables['content_attributes_array'] ? drupal_attributes($variables['content_attributes_array']) : '';

Also, you don't need the following line in bootstrap_gstt_preprocess_html().

$variables['classes'] = implode(' ', $variables['classes_array']);

template_process(), which is executed after bootstrap_gstt_preprocess_html(), contains the following code.

  // Flatten out classes.
  $variables['classes'] = implode(' ', $variables['classes_array']);

So, what your code is doing is already done from Drupal.

As side note, this what I would change in the code you shown.

$results = _bootstrap_gstt_taxonomy_node_get_terms($node);
$taxonomy_vocab = $results->name;
if (is_array($results)) {
  // Omissis.
}

Since _bootstrap_gstt_taxonomy_node_get_terms() is surely returning an array, you cannot access an object property as you do with $results->name.

$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
$v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');

If you are going to use the value returned from $query->join(), then you should use the following code.

$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = %alias.tid');
$query->join('taxonomy_vocabulary', 'v', "$t_alias.vid = %alias.vid");

Also, since you are using $key (whose default value is 'tid') in the rest of the code, you should probably use the following code.

$t_alias = $query->join('taxonomy_term_data', 't', "r.$key = %alias.$key");
$query->join('taxonomy_vocabulary', 'v', "$t_alias.vid = %alias.vid");

To understand what %alias means, see SelectQuery::join().

  $condition: The condition on which to join this table. If the join requires values, this clause should use a named placeholder and the value or values to insert should be passed in the 4th parameter. For the first table joined on a query, this value is ignored as the first table is taken as the base table. The token %alias can be used in this string to be replaced with the actual alias. This is useful when $alias is modified by the database system, for example, when joining the same table more than once.

If you are sure the same table is not joined more than once, you can simply ignore the value returned from $query->join() and use the following code.

$query->join('taxonomy_term_data', 't', "r.$key = t.$key");
$query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');


How to change "Secure Login Module - Secure base url" without login? I have installed Secure Login with Secure base URL setting on a live site, and clone that into a different domain for testing. The "/user" page has no login form because the Secure base URL should be different. How can I change this URL without login? Where is this data in phpMyadmin?

It's in the variables table. Variable name is securelogin_base_ssl, value like s:4:"theurl";


Fill a form on one website and second website automatically grabs it I have two websites, which have exactly same forms and fields. When the user fills the form on first website, the content gets published on first website. I manually do it on another website. Is there any simpler way of doing this? Is it possible that it automatically grabs the data from 1st website as user fills the form?

You can do this with a bit of JQuery. Assuming your form action is action1.php which is on site 1 and you have another handler action2.php on site 2:

$('#form_id').submit(function(event){
    event.preventDefault();  // Stop default handling
    var $form = $(this);
    $.ajax({
        type: 'post',
        url: 'action2.php',  // Submit to the second site
        data: $th.serialize(),
        success: function(){
            $th.submit();    // Submit to the first site
        }
    });
});

And now the form will be submitted to both sites and they will both handle it


How do I overwrite node title for specific content type? I'm trying to add a chapter tag (§) in front of a title for content type 'ABC' in a Drupal 7 site.

I tried the following:

function mytheme_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $variables['classes_array'][] = 'node-full';
  }
  //watchdog("mytheme_preprocess_node", 'items %items', array('%items' => print_r($variables['node'], true)));
  $node = $variables['node'];
  if ($node->type=='abc') {
    $node->title = 'this is a test' . $node->title;
    $variables['node'] = $node;
    watchdog("mytheme", 'items %items', array('%items' => print_r($variables['node'], true)));
  }
}

I did see the message output in the log, however updated title is not showing up on the site.

Every implementation of hook_preprocess_node() made from a module (or a theme) is executed after template_preprocess_node(), which contains the following code:

  $variables['node_url']  = url($uri['path'], $uri['options']);
  $variables['title']     = check_plain($node->title);
  $variables['page']      = $variables['view_mode'] == 'full' && node_is_page($node);

template_preprocess_node() is the preprocess function executed from the Node module, which is the module that defines theme_node().

The template file is then using $title for the page title.

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

If you want to change the value for title, you should change the value of $title, in your preprocess function.

The execution order of preprocess functions is explained in the documentation for theme(). In that documentation "HOOK" is a placeholder for the type of the preprocess function, e.g. "node," "html," and "page."
Between the rendering engine used for the theme, a module, and the currently set theme, the preprocess function implemented from the theme is the last one to be called. This helps if there is another module that alters the title, and you want to use the one set from the theme.

What I reported is also valid for Drupal 6.


Does using modules Metatags and Metatags Quick together cause SEO problems? I am checking the SEO of my Drupal 7 site, where I installed the Metatag and the Metatag Quick modules.

Does using both the modules together on a site cause SEO problems?

You have to be careful so that the output of each module won't overlap. For instance, the same meta should not be present twice and even worse with even slightly different values. I am not aware of the exact SEO penalty depending on the engine, but it is common sense.

You can examine the output of the modules for the <head> tag with the browser's inspector, or Firebug.


How do I add an image to a block in Drupal 7? I want to add an image to a block located in the First Sidebar in Drupal 7. Does anyone know how to do this? Thank you.

This answer may seem needlessly complex to answer such a simple question, but that is because I have no interest in giving fishes away, I want to teach fishing.

Other answers suggest you embed the image directly in the block with an <img> tag. Personally I oppose that solution because it's "one-off" and prevents the rest of your site's functionality from interacting with the image, such as automatic rescaling of the image.

Two suggestions:

Upload the image to a node, create a View that lists your image, and expose it as a block
Use Panels to control the rendering of your page, and add the image, also from a node

While I strongly recommend using Panels, it's usually quite complicated to setup and understand for Drupal beginners so you may want to skip that.


Grant permission to post a new node of content-type 2 if previous node of his content-type 1 has a state of approved I'm using Workflow module for an Article Submission Contest website.

I have two main Role defined in system:

Referee
Participant

The whole workflow goes like this:

Participant user logs in, submit his summary article (content-type).
System sends an e-mail to participant regarding receiving the
article.
Referee user logs in, checks the submission then Approve/Deny the
submission (Workflow module).
System sends another e-mail letting the participant know the results.
If Approved, Participant may send his Full Article.
Referee Checks new submission, Approve/Deny and Publish to the
website.
System sends a congratulations e-mail letting the Participant know!

Everything is setup already and working just fine, the part that got me hooked in Rules module is:

  When the Referee Approves the Summary Article (Content-type 1) via workflow module, then it
  gives the access to Participant to Create new node on Full Article (Content-type
  2)

I'd really appreciate any hints, comments, answers, beers and coffee's you may provide to solve my issue! thank you.

You can create two Roles.

Role 1 -> has permission to create summary (content type 1)
Role 2 -> has permission to create full article (content type 2)

you can assign Role 1 to users by default.

Next you create a rule like

  Event : Summary gets approved
  Action : Add user role

The way you create the rule depends on whether you are using Workflow Node or Workflow field

If you are using Workflow Node then the rule  will be

  Event : Workflow state has changed
  Condition : Check the state

If you are using Workflow Field then the rule will be

  Event : After updating existing node
  Condition : Do a data comparison for the workflow field with the state ID.

Action will be Add user role, that is Role 2


How to reduce the speed of rotation in view ticker module I created a view with views ticker for the newsfeed items. The newsfeed items are configured to vertical scroll with speed: very slow. But the rotation speed of the items are a bit fast and I'm inclined to reduce the speed of the rotation.
So, I looked into module files and tried to change the vTicker_speed values in the views_ticker_style_plugin.inc file located in the ../sites/all/modules/views_ticker/includes/

I changed the values in the line 142. Previously, it was 1000 - one second to 40000 - forty seconds. But I couldn't get it reflected in the site. It scrolls with same speed as it was before.
Can any one suggest me how to reduce the speed. Or is there any other module to work with vertical scroll??

If you are using FADE effect, look in the folder xxxx of the module the views.ticker.fade.js file, and rise the value of the:

b = b || 4000;

to something like 10000 or 12000.

Good luck.


Get all the text fields type and alter value after save I'm trying to alter the value of entity text fields upon node save, even the custom-made fields

so far I've managed to do that with the title and default body field but not with a custom field, I'm trying to target any field that might be a text field, here's my code:

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $replacement_pattern = array("/a/", "/b/");
  $replacement = array("c", "d");

  /* Check whether it's a node */
  if ($entity instanceof \Drupal\node\NodeInterface) {
    // Node title
    $nodeTitle = $entity->getTitle();
    $entity->setTitle(preg_replace($replacement_pattern, $replacement , $nodeTitle));

    // Body main
    if(!empty($entity->body->value)) {
      $entity->body->value = preg_replace($replacement_pattern, $replacement , $entity->body->value);
    }

    // Body Summary
    if(!empty($entity->body->summary)) {
      $entity->body->summary = preg_replace($replacement_pattern, $replacement , $entity->body->summary);
    }
  }
}

Another approach by checking field name. I think this will get you the "custom" field part, but not the "all" fields part:

MYMODULE.module:

use Drupal\Core\Entity\EntityInterface;

function MYMODULE_node_presave(EntityInterface $entity) {
  if ($entity->hasField('field_name')) {
    $entity->get('field_name')->value = preg_replace(
      $toReplace,
      $newText,
      $entity->get('field_name')->value
    );
  }
}

But this only checks for fields of that name. I am also looking for a way to alter the value of a ckeditor/text field by testing field type instead of field name.

I would have hoped setting the field name value to something like text_long would have worked. This is a base field hook suggestion, but I am not having any luck at this time.

To add to the use case, it would be nice to alter ckeditor/text fields whether attached directly to the node, or via a Paragraph type.

The answer in the comment link above is helpful, but I have not succeeded in implementation.


Does Apache Solr assign a weight to HTML tags? Would Solr consider HTML tags when it creates its indexes? Would <h1>, for example, be more important than <h2>, <p>?

If you are using the Apachesolr module, then yes. The module has some sensible weighting defaults for the tags, but they can be further customized at admin/settings/apachesolr/query-fields.


How do I create sub-pages for a custom content type? In Drupal 8, I'd like to create a set of page that relate to a parent content type as so:

Movie (site.com/movie-name)

Reviews (site.com/movie-name/reviews)
Actors (site.com/movie-name/actors)
...

I'd like each child to be it's own page, but retain some information from the parent (e.g. Movie Title, Movie Image, etc.).  Also, I'd like to display a menu navigation that is smart enough to adapt to each parent (perhaps a simple menu with relative paths would suffice?).

I imagine that I'll want to use views to accomplish this.  Any pointers?

Take a look at pathauto and Entity Reference field


Batch Deleting Entity Types On one of my sites, I have over 600 Profile 2 profile types (most of them have between 20-30 field instances, some have additional fields just used in that one type). I've tested a few different methods for bulk deletion, but can't find a way using the Entity/Profile APIs to get the deletion to occur without basically wiping out the site for a few hours.

It seems that, when a content type, profile type, etc. is deleted, a ton of caches are cleared and rebuilt for each deletion, meaning the process goes something like:

Delete the entity type. (I do this part.)
All the attached field instances are deleted.
All the attached fields that have no other instances are deleted.
All the field info and entity caches are cleared.
All the caches are rebuilt (due to other visitors on the site trying to load pages which need those caches).
Ready to delete another entity type.

Is there any quicker way of mass-deleting entity types (I've already removed all the entities themselves—they're quite simple and fast to remove)? I'd like to cut out steps 4 and 5, which take about 90 seconds.

(I changed to a different system for storing profiles, because the cache rebuild and memory requirements were getting out of hand with over 500 profile types (in addition to 20 other content types), and over 10,000 field instances!)

I decided to bite the bullet and run everything with Batch API. This meant the site was painfully slow for probably 2-3 hours, then slow for another hour or so. The profile type deletions became faster as there were fewer left to delete (since cache rebuilds were less intense the fewer field instances that were required).

I set up the batch using something like the following:

// You can remove the limit if you want, but this is a very long operation,
// so it's nice to do it in smaller chunks during traffic lulls.
$types = db_query("SELECT type FROM {profile_type} LIMIT 100")->fetchCol();
$batch = array(
  'operations' => array(
    array('mymodule_bulk_delete_profile_types', array($types))
  ),
  'finished' => 'mymodule_bulk_delete_profile_types_finished',
  'title' => t('Removing Profile Types'),
  'init_message' => t('Beginning profile type deletion...'),
  'progress_message' => t('Deleting profile types...'),
  'file' => drupal_get_path('module', 'fn_profile') . '/includes/fn_profile.utility.inc',
);
batch_set($batch);
batch_process();

Then, I had two batch callbacks (the processing function and the finished function), like so:

function mymodule_bulk_delete_profile_types($types, &$context) {
  $context['finished'] = 0;

  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($types);
    $context['results']['count'] = 1;
  }

  if (!isset($context['sandbox']['types'])) {
    $context['sandbox']['types'] = $types;
  }

  $key = $context['results']['count'] - 1;
  $type_to_delete = $context['sandbox']['types'][$key];
  $profile_type = profile2_get_types($type_to_delete);
  profile2_type_delete($profile_type);

  $context['results']['count']++; // Increment the counter.
  $context['finished'] = $context['results']['count'] / $context['sandbox']['max'];

  // Show message updating user on how many profile types have been deleted.
  $context['message'] = t('Deleted @count of @total profile types.', array(
    '@count' => $context['results']['count'],
    '@total' => $context['sandbox']['max'],
  ));
}

function mymodule_bulk_delete_profile_types_finished($success, $results, $operations) {
  // Display any warnings.
  if (!empty($results['warnings'])) {
    foreach ($results['warnings'] as $warning) {
      if ($warning) {
        drupal_set_message($warning, 'warning');
      }
    }
  }
  // Set operation successful message.
  if ($success) {
    if ($results['count'] == 0) {
      $message = t("No profile types were deleted.");
    } else {
      $message = t("@count profile types deleted successfully.", array('@count' => $results['count']));
    }
  } else {
    $message = t("There were problems deleting profile types.");
  }
  drupal_set_message($message, 'status');
}

At the beginning, it was taking between 50 seconds and 80 seconds to delete a profile type. Towards the end of the batch, it was only taking about 20-30 seconds. The site now only uses about 30-40 MB (according to devel.module) when clearing all caches; it was using about 190 MB before, and taking over 2 minutes to rebuild the caches!


how to filter by YEAR of a date (not the published date) in a view I can add a contextual filter for the YEAR of the published or created date, but not for another date .  How can I create an exposed filter by this other date?

If I am not mistaken this has to do with the granularity setting of the filter. At the moment you add the filter in Views you can set the granularity (if it already exists you can change it by clicking the filter or clicking the settings link behind it).

Contextual

Make sure to select Date: Date (node) as the contextual filter type. Also make sure this is set to year to make the filter work per year only and select the field you want to filter on.

this allowed me to use /2015 in my url to filter nodes with a date field with a 2015 value.

Exposed

If the problem is with exposed filters, just select the date field, and set the granularity to year:


Good Drupal distribution to start with Workflow? Is there a  better Drupal 7 distribution that I can start with, for an enterprise website which require to have workflow support?

Note: I don't know what you mean by "better", and also I don't know what you are comparing to.

NodeStream is my employers distribution. We base nearly all of project off it, and we try to keep much of our work in the open, to ensure that everyone can use it. We have support for the Workbench module and its workflow.

There was a presentation about how we work with NodeStream and built on top of it during the Barcelona devdays 2012, but as far as I can tell, no videos have been posted from there yet, so I can't link to it.


How do you make an existing variable (from a module) available for use in my__node.tpl.php? D7 The contrib module i'm using (media gallery) outputs a block with a single thumbnail used to trigger a lightbox gallery.

The module has a tpl file used to render the thumbnail.

I want to isolate the single block thumbnail image ($media_gallery_item used in media_gallery_media_item_thumbnail.tpl.php) and insert it directly into a new node template (node--media-gallery.tpl.php)so that I can float the image in the body field (and preserve the lightbox trigger).

This is my first attempt at using a preprocessor.
Incidentally, I posted in the modules issue queue two weeks ago. I'm posting here as well to hopefully get a quicker response.

The only variables different template files have in common are the ones returned from template_preprocess(), or hook_preprocess(). See also _template_preprocess_default_variables(), which defines the default values for some of those variables.


How to show attribute dropdown in add to cart form in Commerce 2.x The attribute dropdown list doesn't show, instead I get an autocomplete field labelled "Product Variation" and it contains the full title of the variation. When I enter text, a list of variations appear but when selecting a different variation the product doesn't refresh.

I would like it to show the label of the attribute with a dropdown list of the values. I'd like it to say "colour : "Value"". I have two attributes one showing a weight capacity the other a colour. They are both appended to the variation title but I need to select combinations of the two. I've trawled the internet and it seams the dropdown list should work out of the box.

I have a matching Product type and variation type. On the manage display of the product type the variation field format is "Add to Cart". On the variation type the attribute field is enabled but it doesn't show up.

Where am I going wrong please?

You have somehow disabled the proper widget. Go to the "Order item types" page and click "Manage form display" for your order item type, the widget for the "Purchased entity" field should be "Product variation attributes".

I would love to find out how your system ended up in this state. Was this a fresh install? Did you create a custom order item type? Let us know in the Commerce issue queue.


How do I get Search API to index rendered content including referenced nodes? We are building av website in Drupal 8 where the content is divided into 3 content types;

Basic Page, the scaffold for all visual pages like "About, Features
etc."
Content Block 1, for a layout with one text field and one image
Content Block 2, for a layout with one text filed and two images

Nodes on Content Block 1 and 2 are referenced in on Basic Page nodes to enable different designs for each Page. This is done using a view block on Basic Pages.

Now, to the question:

Is there a way to set Search API to index only nodes on Basic Page, rendered with the content of referenced Content Block nodes?

I also need to exclude Content Block nodes from being indexed and showing up as nodes in the results, but that I have a grip on.

I hope my question is clear enough. Please comment otherwise and I will be happy to elaborate.

Thanks!

You should be able to traverse through the reference fields on the Search API Add Fields page. Then you want to add all the referenced text fields, so they become part of the main node. However, it is possible that Search API currently has some limitations there, it didn't show configurable fields for me when I tried something similar a few days ago. I'm sure that will eventually be fixed, though. There might be issues already.

PS: You might want to check out Paragraphs. It's a similar concept, with a much better editing experience, you can have different types of embedded content elements and edit it all in the same form. We're working on Search API integration right now and will also look into the problem mentioned above.


Unpublish node instead of deleting it In my web application, I would like to prevent accidental or unauthorized deletions or modifications (e.g. a student steals teacher's credentials and deletes or changes bad marks). But, at the same time, I'm trying to keep the interface as easy and straightforward as possible.

I've already enabled node revisions, so if a mark is changed we can restore the previous state, but I also hid the revision message, because it confuses non-techie teachers.

The next step would be transparently prevent mark deletion. The user should see and use the "Delete" button and the deletion confirmation page, but when confirming, Drupal should not delete the node and just unpublish it. Is this possible to do?

(I would then create a view to see/administer the revised/unpublished nodes, to check unauthorized modifications)

Use hook_node_delete . This hook is being invoked right before node deletion.

function YOURMODULE_node_delete($node) {
  if ($node->type == 'NODETYPE') {
    $node->status = 0;
    node_save($node);
    unset($node);
  }
}


How to hide My results tab for the User using Quiz module in Drupal 7 It looks so silly to ask these questions but I'm beginner in drupal. I need a help on implementing the modules. I'm trying to build a portal using Quiz Module wherein I need to hide a tab for the user but should be visible to administrator.

Is it possible to hide the My results tab in drupal 7? If so how?

You can use Tab Tamer module.
Project page says:

Tab Tamer is an administration utility that provides easy re-ordering,
hiding, and deactivation of tabs and subtabs.

For more information go through the module documentation.


Hitting the back button after a batch process cause a nasty error I have a batch process (using batch API) that runs when a user on my site tries to launch a non signed Java applet. The batch process does all the needed codesigning and other things and then redirects the user to the applet when it is finished. This all works well but if the user hits back from the applet page they get this nasty error with the text from my batch_error function.

It seems that this occurs because when you hit back you end up trying to run a batch process that no longer exists. Is there anyway to avoid this?

EDIT:

Here is my function that sets up the batch process:

function batch_codesign($node) {
$batch = array(
   'operations' => array(
        array('batch_codesign_process', array("create_jar_files", $node)),
        array('batch_codesign_process', array("output_new_agentsheets_applet_html", $node)),
    ),
    'finished' => 'batch_codesign_finished',
    'title' => t('Codesigning'),
    'init_message' => t('Codesigning ' . $node->title .'.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error has occured while condesigning the project, please try again.'),
    );
batch_set($batch);
$nid = $node->nid;
batch_process("path/to/endpoint");
}

Here's a possible solution, however you'll need to alter the menu callback for patch and wrap the default page callback.

Create your hook_menu_alter() and change batch to be your own page callback function, and update the file attribute (unset if in your .module)

  // Default page for batch operations.
    $items['batch'] = array(
      'page callback' => 'system_batch_page',
      'file' => 'system.admin.inc',
    );

Basically your callback can mimic around the default system_batch_page() page callback. From there you can adjust what happens when someone hits an inactive or stale batch.


how remove required field from billing information into checkout I need to add a checkbox to make billing information same as shipping information in drupal 8.
So i want remove required fields into billing address and set this information programmatically after submit the form.

But is very hard to remove required fields from billing information into checkout panes.
I also hack the Drupal\address\Element\Address.php at line 202 to set the #required attribute to FALSE but when i submit the form, i have always the message "... field is required."

Why the attribute #required => FALSE doesn't work? Why is so hard to modify this field? Why is not there a template for this field?

thanks

You have to use hook_form_alter to changing form elements options. This field is required because very often payments modules need this data to prepare correct post variables.


What all is required to completely uninstall Webform? After disabling and uninstalling Webform, I noticed that it appears to still be active. Existing Webform content are all still there and accessible. Apparently this is intended behavior.

I can delete the content and content type, but I'm worried there might be other items or residue that is not as apparent. What all do I need to do in order to completely remove all Webform stuff from the site?

Like I said you need to uninstall it from /modules UI and then delete its folder from /site/all/modules.

If you take a look at webform module source code, in webform.install under function webform_uninstall() you will find this code:

foreach (node_type_get_names() as $type => $name) {
    variable_del('webform_node_' . $type);
}

as you can see it deletes every node which has webform type. for more details of what is going to be deleted after uninstalling the module, check the  function webform_install() and function webform_uninstall() functions in the mentioned file.


How do I get the views pager to display (after adding an view header)? I'm using the standard views implementation of taxonomy term pages, ok I've added a view header display, but beyond that, it's a stock Views 3 view.

It apparently has a pager set, but it's not showing up. Once upon a time it was there, now it's not. It was my client that noticed *blush*. Yes there are enough results in the query. Have tried Mini and Full versions, but nothing seems to create any HTML that resembles a pager.

It seemed to happen after adding another simple view in the header.

To save you wading through the comments which led to this answer, here it is in summary:

The problem was that the 2nd view included in the Header of the main view also had a pager on it.

Two solutions:

Views can cope with having more than one pager, with a bit extra config: you have to set the Pager Id field on one of the Views Displays to an integer not in use by other views/displays on that page (e.g. 1 instead of 0).
In my case I realised that the attached header view did not actually need a pager (it was only ever going to display one result - the description for the taxonomy term), and I should have selected "show fixed number of results" instead of a pager option. Changing this fixed the problem.

Hope this answer is useful for someone else getting stuck!


Sometimes CCK custom fields get lost although they appear normally in the database I have pressflow 6.22.

When the editors try to create new node, they lose what they have inserted in CCK custom fields. I have checked node_load and the result is missing those values as well.

I checked the tables and the result is as below:

mysql> select * from content_field_headline_image where nid=380320\G
*************************** 1. row ***************************
                                  vid: 380322
                                  nid: 380320
  field_headline_image_imceimage_path: http://mywebsite.com/sites/default/files/im/Maven.jpg
 field_headline_image_imceimage_width: 0
field_headline_image_imceimage_height: 0
   field_headline_image_imceimage_alt: Maven
                                delta: 0

but this image doesn't appear in node_load result as well as in the preview of the node itself.
##EDIT##

I fixed it when I flush_all for memcache !!

Any idea of how to disable memcache for logged-in users only??

note:cache mode is disabled (cache mode in admin>>performance)

Thanks for your help

Even though some fields appear correct in the DB, they don't always load up into the edit view, I've noticed similar oddness long ago when trying to replace some image assist tags in the database directly with a php script.

In our case, the edit view (node/edit) begun showing correct data after we purged all caches.

To solve your problem, read and understand how Memcached works from http://en.wikipedia.org/wiki/Memcached -- When making manual DB edits, you must let Memcached know that you've made modifications to tables, this functionality is built into Drupal database handling, hence you'll never notice it when working directly from Drupal, but if you are making custom update queries into the tables, you must let Memcached know there was a change. Was a bit of a surprise to me since I thought it just automaticly works in the background. :)

See the example code part from the wikipedia page how to do it.

..and if you don't use custom update queries to modify those CCK fields, I suspect there must be some sort of a bug in Pressflow itself. Do the changes propagate into the edit view after few hours? Apart from this, there's not really enough info to dig in deeper :/


How to group and merge results together in Views? I have Views setup to list only nodes of a certain type and group them by a field. It looks somewhat like this:

Group 1:
Title A
Title B

Group 2:
Title C

Now I want to merge the Titles togehter so it looks like this:

Group 1:
Title A & Title B

Group 2:
Title C

How can I do this?

You can achieve this in following ways,

1) Choose your views format as table under Format 'Format: Table', Then click settings. You can find a table listing your selected fields. near to each field there is an option to choose column. There choose your  Title B s column to Title A and in the separator provide '&' . Ensure Grouping field has chose. Now you will get a display in following format
Group 1:
Title A & Title B

OR

2) After grouping, Choose Exclude from display option for your Title A  field. Then for second field choose Rewrite results. There you can find Replacement patterns. Use your token in appropriate format. eg. [title] & [nid]

Hope this may helps you


How can I get the Operations Link Field back? I have a custom entity created in code which displays list in collection route. I decided to use a view to show this collection.

I created a new view of type 'Product' (Views shows my custom entity)
I added the fields I need to display
then searched for Operations Links (to add the edit, delete menu)

but it wasn't showing. I can confirm I've used this before in a view of custom entities.
Wat magic do I need to do here?

I had deleted the "list_builder" handler from my custom entity's annotations - thinking I didn't need a list builder since I was using a Views handler. Well, turns out that was the problem. The "Operations" link in views came back after I reinserted the list builder handler in my custom entity.


How can I export all users in a CSV format? A site we have over 8000+ users with Views, Ctools and VBO installed. Is it possible to export all users data into 1 CSV file? We tired Views Data Export with no luck(memory limit), even we increase the memory to 128MB. Please help.

Stick the following in a file named expusers.module

<?php
/**
 *  Implementation of hook_menu()
 */
function expusers_menu() {
  $items['expusers'] = array(
    'page callback' => '_expusers_select',
    'access arguments' => array('administer expusers'),
  );
  return $items;
}

/**
 * Callback
 */
function _expusers_select() {
  //
  $csvfile_name = 'expusers.csv'; // the file to save to
  $users = array();
  $result = db_query('SELECT * FROM {users}');
  foreach ($result as $record) {
    unset($userarray);
    foreach ($record as $key => $value) {
      $userarray[] = (empty($value)) ? '' : '"' . $value . '"';
    }
    $user = implode(',',$userarray);
    $users[] = $user . PHP_EOL; // Remove this if file_save_data don't work.
    // Use PHP statement below to append to file here if file_save_data don't work.
    // file_put_contents(..path to file.., $user, FILE_APPEND);
  }
  $file = file_save_data($users,'public://' .$csvfile_name); // Remove this if file_save_data don't work.
  return '
CSV dump of {users} table written to file "' . $file->uri . '".
';
}

Stick the following in a file named expusers.info;

name = Export users
description = "Exports the {users} table to a CSV file in the public file area."
core = 7.x

Create a directory named expusers in your in your modules directory, and place both files in it.

Enable the custom module "Export users" on the site's module page.

Navigate to the path expusers (e.g. http://example.com/expusers).

The message:

CSV dump of {users} table written to file "public://expusers.csv".

Should appear.

Go to your public file area and pick up your file.

The above tiny custom module should be far less resource hungry than Views data export, so, hopefully, you will get your CSV without hitting a memory limit .

However, it first collects all the user data into an array in memory, before dumping into the file.

If you still hit a memory limit, you can't use Drupal's very convenient file_save_data to save to a file.  Instead, you must save the data one line at a time.  There is no built-in Drupal function to do this, but you should be able to use PHPs file_put_contents instead.

I've used comment to indicate how to change the code to replace Drupal's file_save_data  with PHP's file_put_contents.


How to condition SelectQuery by field value? I have a view that receives taxonomy terms. Via pre execute hook, I want to only get terms the terms that have the current user referenced (in their field). I know it works via views itself, but there is more to it. I have to do it programmatically.

function tk_access_views_pre_execute(&$view) {
  if ('myview' == $view->name) {
    global $user;

    if (in_array('extern', $user->roles)) {
      $query = $view->build_info['query'];
      // debug($query->conditions());
      // $query->condition('field_referenced_user', $user->uid);
      $query->join(
        'field_data_field_referenced_user',
        'referenced_user'
        // 'field_data_field_referenced_user.field_referenced_user_target_id = '
      );
      $query->condition('referenced_user.field_referenced_user_target_id', $user->uid);
      $view->build_info['query'] = $query;
    }
    // debug(array_keys($view->build_info));
  }
}

But it doesnt work, unfortunately. What am I doing wrong?

Edit

If I add a contextual filter inside the view, I can debug the final sql statement:

SELECT
  taxonomy_term_data.name AS taxonomy_term_data_name,
  taxonomy_term_data.vid AS taxonomy_term_data_vid,
  taxonomy_term_data.tid AS tid,
  taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name,
  'taxonomy_term' AS field_data_field_customer_taxonomy_term_entity_type,
  'myview:entityreference_1' AS view_name

FROM
  {taxonomy_term_data} taxonomy_term_data
LEFT JOIN
  {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
INNER JOIN
  {field_data_field_projectstatus} field_data_field_projectstatus ON taxonomy_term_data.tid = field_data_field_projectstatus.entity_id
    AND (field_data_field_projectstatus.entity_type = :views_join_condition_0
    AND field_data_field_projectstatus.deleted = :views_join_condition_1)
LEFT JOIN
  {field_data_field_referenced_user} field_data_field_referenced_user ON taxonomy_term_data.tid = field_data_field_referenced_user.entity_id
  AND (field_data_field_referenced_user.entity_type = :views_join_condition_2
  AND field_data_field_referenced_user.deleted = :views_join_condition_3)

WHERE
  (((field_data_field_referenced_user.field_referenced_user_target_id = :field_data_field_referenced_user_field_referenced_user_target_id )
   )
  AND(( (taxonomy_vocabulary.machine_name IN (:db_condition_placeholder_4)) AND (field_data_field_projectstatus.field_projectstatus_value IN (:db_condition_placeholder_5, :db_condition_placeholder_6)) )))

ORDER BY taxonomy_term_data_name ASC

I still dont know how to get the additional conditions via SelectQuery object.

Yay, I dit it:

$query = $view->build_info['query'];
$query->leftJoin(
  'field_data_field_referenced_user',
  'field_referenced_user',
  'taxonomy_term_data.tid = field_referenced_user.entity_id'
);
$query->where(
  'field_referenced_user.field_referenced_user_target_id = :uid',
  array(':uid' => $user->uid)
);

$view->build_info['query'] = $query;


How can I fetch the complete main navigation menu via JSON:API? How can I fetch the complete main navigation menu via jsonapi?

I've tried:

curl --header 'Accept: application/vnd.api+json' https://cms.example.com/jsonapi/menu/menu/

and

 curl --header 'Accept: application/vnd.api+json' https://cms.example.com/jsonapi/menu/menu/232fc942-51f3-4478-8535-e5dc482a166e

where 232fc942-51f3-4478-8535-e5dc482a166e is the id of the main-navigation menu BUT only the first level nodes are returned:

{
  "data": {
    "type": "menu--menu",
    "id": "232fc942-51f3-4478-8535-e5dc482a166e",
    "attributes": {
      "label": "Main navigation"
    },
    "links": {
      "self": {
    "href": "https://cms.garanteasy.com/jsonapi/menu/menu/232fc942-51f3-4478-8535-e5dc482a166e"
      }
    }
  },
  "jsonapi": {
    "version": "1.0",
    "meta": {
      "links": {
    "self": {
      "href": "http://jsonapi.org/format/1.0/"
    }
      }
    }
  },
  "links": {
    "self": {
      "href": "https://cms.garanteasy.com/jsonapi/menu/menu/232fc942-51f3-4478-8535-e5dc482a166e"
    }
  }
}

I did not get it to run with JSON:API, there are several long-standing issues...

However you can get it to run if you additionally install the REST Menu Tree module.

Be aware that this has several direct and indirect dependencies:

It has a direct dependency on Menu Normalizer and according to this issue you need to then activate that endpoint for example with the REST UI module - which in turn will activate the core REST module.

Then in your site activate the endpoint via the Rest UI in /admin/config/services/rest.

Afterwards you might also want to allow everyone to GET this endpoint via /admin/people/permissions#module-rest

And finally you get a JSON array in /entity/menu/main/tree.
Or query a different menu via /entity/menu/{internal_menu_name}/tree.


how to remove WIDTH and HEIGHT from img-tag in Drupal 8 Does anybody know how to remove width and height?

I want that the img tag looks like this

In your theme open file THEMENAME.theme, example in my case THEMENAME is bartik and file is bartik.theme add code below:

function bartik_preprocess_image(&$variables) {
  if (isset($variables['attributes']['width']) && isset($variables['attributes']['height'])) {
    unset($variables['attributes']['width']);
    unset($variables['attributes']['height']);
  }
}

Clear all cache and see result.