Implement user editable personal pages with subpages So I would like to have this structure:

/users/jhon
# A page (default blank) which can be edited by jhon

/users/jhon/project
# A page which can be created and edited by jhon and
# should be linked to in a menu in /users/jhon

/users/jhon/project/sub-project
# The same as above and should be linked to
# in a menu in /users/jhon/project

So I was starting to work on the profiles, but it don't feels like the right way..

You might not be aware of it, but this is a rather broad question.

Drupal is quite different to other CMS's. You don't create pages according to a certain URL structure. In a way, it's the opposite.

Your users just create content with relations/references to other content. How and where that is shown is up to you, not them.

One way to do this is to have two node types, "Project" and "Sub project" for example. Users create projects and they can create sub projects and select the parent project using an entity reference field.

Then, all you need is to set up alias patterns using custom code or the pathauto module (An inofficial D8 port can be found here, use on your own risk) so that it results in those URL's.

You can add plenty of things on top of it with views, custom code and so on: links to create sub-projects from a project, listing projects and subprojects but defining the content structure (and only after that the URL structure) is where you have to start.


How to display number of pageviews on articles and pages I am looking to display the number of pageviews for articles and pages next to where it has tags for example.

Are there any modules that do this?

Have you tried with Node view count module ?

  Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.


add region with module installation I am developing a module, that when installed, should place an HTML element in a drupal block.
That block, will be inside a region. I would like the region to be added to the theme on module installation. Any workarounds?

you cant create custom region in a theme using custom module in a drupal way . however you can fetch available regions


Accessing user input My question is basically how to access values that the user entered in previous forms. For example, I am using drupal commerce and as the user sees a product, fills some text field values and clicks add to cart and then finishes the checkout. At the end of the checkout how can i access programatically  the values that he entered in the first stage of the process?

One way I think it might work, is to add a submit handler in the  original product form that "grabs" the values when he clicks add to cart and then save them to a session. Is this the correct way ?  Is there any other way like querying  the db or something?

I do not want to display to the user anything, I just want to work "behind the scenes".For  Example after the checkout is complete, I want to call the hooK_commerce_checkout_complete and by using the values that he entered in the first place modify and save a pdf (I know how to crate the pdf with  the tcpdf lib what i do not know is how to  call the values as i said earlier).

If this were Java the values would correspond to an instance variable and i would have access through the corresponding get method. Surely there must be something equivalent for this in php/drupal.

I would appreciate any advice or links to the proper documentation on how to do that.

PS I am most interested on accessing commerce  line items  and the value of their fields but i should probably start with the easy ones first!

Thanks in advance

PHP isn't Java...there's no concept of 'instance variables' in this context, and no automatic persistence of such vars across page requests.

Drupal Commerce persists information about the order, order lines, products, etc to the database during the checkout process, and then re-loads the relevant entity when it needs it (which is the standard workflow).

In hook_commerce_checkout_complete() you already have access to the $order entity, so there's no need to load it yourself. I'd advise using an entity_metadata_wrapper() to access the order; to get the order lines, for example, you'd use something like:

function MYMODULE_commerce_checkout_complete($order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
    // Do something with $line_item_wrapper.
    $field_val = $line_item_wrapper->field_something->value();
  }
}


Webform submission as new node I have a webform, that the user can fill out. After the user clicks on the "submit" button, a new node should be created with the content the user typed in (text, images, ...). The form itself should be multi-step (first page = personal data, second page = content, etc.). I'm not sure if I can use the regular node creation, because I would need to

customize the form
the form should be multi-step

Is this possible?

Alternative to Webform + Bala's answer is Multistep Nodeform. Using it you can redesign node creation into multistep form and simply allow anonymous to add noeds of given content type.

  For each step you can define which fields should be included in this step. "Fields" includes core-fields like "Title", "Body" or "Authoring information" as well as fields defined by other modules (e.g. Date).


default email for guest checkout I am using the Commerce Kickstart 2.x demo. When the guest checkout option is selected, the default guest email demo+1614916499@commercekickstart.com.
Is there a way to change what's displayed as default contact email for guest?

answering my own question.  was able to figure this one. the guest email is prepopulated in orderEventsSubscriber.php.


Article view with links to other articles So I'm trying to create a view which displays the most recent article belonging to a specific taxonomy term and pulls out just the links to other articles which have the same term.

I want to display the article content and below that 4-5 links to other articles of the same taxonomy. I want to display this view as a block.

Is this possible? How can this be done?

Add a  contextual filter: Content: Has taxonomy term ID (with depth), for displaying related articles


Modify tpl file to print the path to the image instead of the image itself? I need to change this tpl file which generate images for a image field to print  the path to image instead of the image itself.

This code print out the images. It works fine

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <span class="<?php print $delta % 2 ? 'odd' : 'even'; ?>"><?php print render($item); ?>
    <?php endforeach; ?>

I need to print just the path to the image (not the image).
I tried with this code but I get a error message related to line 58. (see the error message below)

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <?php dpm($item); // I uploaded a capture of this dpm

          echo $item['#item']->uri; // THIS IS LINE 58

     ?>
    <?php endforeach; ?>

Error:

  Notice: Trying to get property of non-object en include() (line 58 de
  /Applications/MAMP/htdocs/lembassade.com/sites/all/themes/omega_subtheme_2/templates/field--field-im-genes-del-fondo.tpl.php).

From the looks of your devel output (and the error message), each $item is an array, not an object.

You should be able to fix it by changing the line inside the loop to:

echo $item['#item']['uri'];


How can I update a user flag in rules? I am using a user flag, Visits, to track each user's visits to other user's profiles.

When a user visits another user's profile, a rule is triggered that automatically flags the visited user on behalf of the visiting user.

Flagging the user on the first visit is no problem.  But on the second visit and thereafter, I want to update the flag that was flagged on the first visit.  To do this, I made the following rule:

Event: User account page is viewed
Condition 1: NOT [account] is [site:current-user]
Condition 2: User is flagged ([account] on behalf of [site:current-user])
Actions-> How do I fetch and update the flag?

This rule is triggered correctly; however, I don't know how to get the previous flag (the flag applied when the user visited the profile for the first time) in order to update it.

My question: how can I fetch the previously applied flag in rules so that I can update the timestamp and re-save it?

What I tried

Flag provides a rules action Fetch user flagged by user, but this does not help because this returns an array of users, not the flagging, which is what I want to update.

I can add the Unflag a node action and then the Flag a node action, but this will destroy my previous flag and replace it with a new one; since I want to track referer information over time, this is not a good solution.

Since I'm using Flag 3.x in which flags are entities, I tried using the Fetch entity by property action in Rules to fetch the flagging, but in this case the only property I can choose to select is the value of the Referer field, which is not helpful.  There seems to be no way to fetch the flag by its endpoints.

Why I'm doing this

This flag has a computed field, Referer, which stores the value of $_SERVER['HTTP_REFERER'] upon flagging.

When a user visits the profile of a user for the second time, I want to update this flag by updating the timestamp of the flagging and adding the new referer information to the flag.

My question: how can I fetch the previously applied flag in rules so
  that I can update the timestamp and re-save it?

Some good news but mostly bad.

If you add an extra text field to the flag and add an extra rule to set its data value to [flagged_uid]-[flagger_uid] when a flag is created, it seems that you can then fetch the flagging using that field as the Property and [account_uid]-[current-user_uid].

I say seems because while the rule runs without errors and I know my logic is right, I can't do anything to the fetched flagging to prove I've actually fetched it. I get an error when trying to delete it because "Rules doesn't have info about deleting a flagging" and saving it doesn't change the timestamp.

It just feels like it's not fully integrated. Even if you added a date field, I'm not sure Rules could access it on user view.

I guess I would either create a custom rules action to finish the rule or go with a fully fledged Field Collections solution.


Create an article entry without image All I want is to post a video embed, but the drupal form is forcing me to use an image for each, otherwise I can't upload my post.

Is there a way to override that field in particular?

You can un-require the field. Navigate to:

  /admin/structure/types/manage/[content_type]/fields

and un-require there.


How to set the views exposed filters default value programmatically? I have a view which has a term reference exposed filter.

I want to set the default values of this exposed filter programmatically based on a certain condition.

I have tried the following code but the values are not selected in the filter.

function example_views_pre_build(&$view) {
  if ($view->name == 'events') {
    $tids = array(5, 6);
    foreach (tids as $tid) {
      $view->display[$view->current_display]->handler->handlers['filter']['field_category']->value[$tid] = $tid;
    }
  }
}

AND

function example_views_pre_view(&$view, &$display_id, &$args) {
      if ($view->name == 'events') {
        $tids = array(5, 6);
        foreach (tids as $tid) {
          $view->display[$view->current_display]->display_options['filters']['field_category']->value[$tid] = $tid;
        }
      }
    }

I also tried with form_alter, in form alter the values gets selected in the filter but then it does not display correct results after removing/applying again the filter.

function example_views_pre_build(&$view) {
    if ($view->name == 'VIEW_NAME') {
        $view->display[$view->current_display]->handler->handlers['filter']['field_country_tid']->value = array(55, 91);
    }
}

This code worked for me. Check your views module version as well. I am using Views 7.x-3.14.


Manage main menu in module I have a series of sites that use the same theme.  What I'm looking to achieve is to manage the main menu (or a standard menu) via a module instead.

Reasoning:
Most of these sites will have the menu the exact same.  If I need to change something, I would do it in the module. I could put it in the theme, but I'd rather the site admins not have control over appearance or to change the theme, have the ability to add to the menu if that have a small item that needs to be placed there, or the ability to simply not show the entire menu and manage their own.

I've tried the following, but every time the cache is cleared, a new item is added. If I change something, it just adds a new item and leaves the old one.

function something_mainmenu_menu() {

    $items['external'] = array(
        'title' => 'External Item',
        'link_path' => 'http://www.whatever.com',
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'main-menu'
    );
}

Is this possible in Drupal as a module, or should I just put it in the theme and do a case based on the URL?

You can stop roles from editing menus via the permissions page. That should lock that down.

Then to manage the menus on all your sites you could use Menu Export/Import module (https://drupal.org/project/menu_import), which plays nicely with Drush to allow you to export/import entire menus. You could maintain your "master" menu in a text file in json format and then periodically push it out to all sites at once using Drush aliases or a simple shell script. Because Drush uses uid 1 I think you should be able to do whatever you need regardless of how you set your roles' permissions via the UI.


Installation showing only SQLite as database option I using Windows 8.1, XAMPP 3.2.2 and Drupal 8.0.3.

When I install Drupal, it only gives an option for Database as SQLite and it stores the file in drupal->sites->default->files. Then inside the folder 'files' name of the SQLite DB is drupal.ht.sqlite.

I want to use MySQL as DB instead of sqlite, Please help me to get out of this problem. And I have add some content it is working fine.

You won't be able to convert an existing site as far as I know; you'll need to build a new site and migrate the content over to it. It might be easier to just start a new site from scratch and export/import the data manually, depending on how far you've got.

Before you do that, you need to enable MySQL in PHP. If you only see SQLite as a DB option, it means you haven't installed the PDO MySQL extension. Consult your web server's documentation for instructions on how to do that.

Once you have, MySQL will appear as an option for installation.


Update pathauto alias without node_load? I want to force an update of the URL alias without loading the node.

Can this be done? If not, any lighter ways to update a Pathauto alias?

Nope, not without circumventing the pathauto module logic (e.g. altering the alias directly in the DB).

The main function that gets executed in pathauto node updates/inserts, pathauto_create_alias, requires a parameter, $data, passed to it. In a node context, $data is the node object. Without this node object data, pathauto would not be able retrieve data needed for tokens pattens (e.g. [node:title]).


cron for rebuild xmlsitemap mannually without drush in cpanel I'm using this: XMLsitemap module: https://www.drupal.org/project/xmlsitemap

I have a cpanel shared hosting in hostgator and drupal 7. I can not install Drush, ssh access is not enabled. i go to tasks cron in cpanel and setup the cronjob, but in field 'COMMAND' i tried :

curl drush xmlsitemap-rebuild http://link.com.br/cron.php?cron_key=xxxxx

Nothing , because i dont have a drush installed.
So, i tried:

curl xmlsitemap-rebuild http://link.com.br/cron.php?cron_key=xxxxx

Nothing too,lastly I used:

xmlsitemap-rebuild http://link.com.br/cron.php?cron_key=xxxxx

But that is not recognized as Linux command in Terminal .... cron does not happen, what should I do?

EDIT 1:
the task only works if i press the button on image,

You can probably request the the Drupal 7 cronjob by using wget or curl. On my server I can use: /usr/bin/wget -O -q /dev/null http://www.example.com/cron.php?cron_key=XXXXX.

The cron key is different per website and can be found on your status report page.

This basically opens a webpage just as if you would be running cron manually, but you can set an interval for it. If you set xmlsitemap to generate a new sitemap during cron (I believe that is default behavior), you should be good. You can set the rebuild time on the settings tab:
.

There is no direct need for Drush (though you can do this with Drush as well), and it is not possible to run Drush with curl.

If you or someone else wants to use Drush;
After installing Drush on the system you can use it like any other program: drush xmlsitemap-rebuild or drush @site_alias xmlsitemap-rebuild if you configured a site alias.


How do I get the generated HTML ID of a form element? I have fields called

'title'
'field_article_summary'

The HTML IDs of the form elements are

edit-title
edit-field-article-summary-und-0

Is there a way to programmatically get these HTML IDs? (without writing the code myself to do it - Drupal must have something that is creating them)

I know this is two years late but for anyone looking back at this, a way to get the element IDs is to use Drupal Form API's #after_build attribute to add a callback once the form has rendered.

$form['#after_build'] = array('mymodule_afterbuild'); // The callback can be called anything.

Then your function would look something like:

function mymodule_afterbuild(&$form, $form_state) {
  // Get the element ID.
  $id = $form['title']['#id'];
  // Then do something, such as passing it into Drupal settings to access with Javascript.
  drupal_add_js(array('mymodule_js_settings' => array('title_id' => $id)), 'setting');
  return $form;
}

Edit to say that the #after_build attribute can be used on individual elements in a form like so:

$form['title']['#after_build'] = array('mymodule_afterbuild');

This actually makes it easier to get the IDs, especially if you're using fieldsets, field collections or other complex field data structures.


What do you set in the "column" field for adding a minimum words validation via the Field Validation module? I'm creating a validation rule on a text field via the Field Validation module. On the create screen it asks for "Column" and includes this description:

  A column defined in the hook_field_schema() of this field.

I do not understand what I need to enter here. Can anyone explain?

This may help you out....

Field > Appropriate column value

Normal field > "value"
Taxonomy field > "tid"
Date field > "value" and "value2"
Node reference field > "nid"
User reference field > "uid"
Link field > "url","title","attributes"


How to remove default divs on views result? I'm trying to add use bootstrap modal and bootstrap slideshow to show a view but the slideshow doesn't work the way I want it because of the default generated divs by Views module. Here is the code:

heading 1

This is the description.

heading 2

This is the description.

I want the result of the view supposedly like this:

heading 1

This is the description.

heading 2

This is the description.

Only the output of the view with no views default generated divs.

Go to the Settings of your Fields and uncheck the Option: Provide default field wrapper elements


how to name templates for same content types I have a Content Type machine name as "aktionsblock_oben" and made some content and get the Content ID as 33 for this one. Now I can use template name as page--node--33.html.twig, but what if I create new content like this where I get another ID? The page--node--33.html.twig won't fire.

My try page--node--aktionsblock_oben.html.twig or aktionsblock_oben.html.twig was a failure.

Any suggestions

By default page.html.twig won't work content type specific pages, you'll have to assign a template file name manually. Check the example below which create a new template name for content type:

function [THEME_NAME]_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Add content type suggestions.
  if ($node = \Drupal::request()->attributes->get('node')) {
    array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
  }
}

With help of above code, you can use page--node--aktionsblock_oben.html.twig template file as your content type template file.


is $node always available in page.tpl.php I'm periodically getting an error about $node being undefined in one of my template files.I have a simple if condition that checks the node type being displayed. I assumed $node is always available, or am I wrong?

$node isn't necessarily defined, from the page.tpl.php Drupal 7 API:

  $node: The node object, if there is an
  automatically-loaded node associated
  with the page, and the node ID is the
  second argument in the page's path
  (e.g. node/12345 and
  node/12345/revisions, but not
  comment/reply/12345).


Why are most of my Timefields blank when editing a node? I have a node with four timefields. When I want to edit the node, all the timefields, except the first one (that has a default value), are blank.

I found this issue still doesn't solved:
https://www.drupal.org/node/1970252

How can I solve this? I could populate the missing fields via javascript?

Altenatives of timefield module?

Some of the starting pointers I can think of.

Ensure there is no custom code altering the form field. Search for hook_form_alter/hook_form_FORM_ID_alter in your custom modules.
Check your drupal error logs, if there is any error log related to timefield.
Check your browser console, if there is a JS error.
Check the timefields module issue queue if there is already such error reported, that would be the best place to start from.
Try installing timefields module on vanilla drupal and check if the same issue persist, in that case add this in the issue queue of module.
Make sure all timefields get data when saved for first time, debug using devel module,go to 'devel/php' page and run dpm(node_load('your_node_id'));, see inside node object if those fields have value or not.
"Like s there anyway the possibility to keep the values of the fields somewhere, so I could populate the missing fields via javascript?" Yes, you can only if field values are getting saved to database, in fact simple would be to do at php level something like

function my_module_form_alter($form, &$form_state, $form_id) {
  if($form_id == 'your_form_id') {
    if(isset($form[#node]->nid)) {
      $form['yourtime_field']['#default_value'] = $form['#node']->yourtime_field['und'][0]['value'];
    }
  }
}

But this is not the solution, this will be re-attempt of what drupal already trying to do. Best would be to identify why values are not showing by default.


How to run custom sql commands to database programatically I'm using MariaDB as database backend and I would like to use built in "Sequences" to get an integer number generator. I need to dinamically create sequences and get their values. Following this documentation I know the right sql commands to do it and I have tested it on MariaDB, but I haven't found a way to run this commands from Drupal 8 database connection object. I can only do selects, updates, inserts or deletes. How could I run this custom sql? I need it because I have to create custom sequences on submit some form.

I haven't found a way to run this commands from Drupal 8 database connection object. I can only do selects, updates, inserts or deletes

That's not true, you can also run arbitrary queries, e.g.:
\Drupal::database()->query('TRUNCATE TABLE foo');


How to upgrade outdated Drupal 7 version I'm using Drupal 7.10 which is an outdated version. Is it safe to just upgrade to the latest version or should I upgrade version by version from 7.11 until the latest version 7.21?

You can upgrade directly to the new version as it contains all the previous changes as well. But don't forget to follow the backup instructions...


Can't choose checkboxes as field widget in d7 I recall in previous versions (Or maybe even this version and mine is just bugging) you could take text or int fields and supply a list of key|values and make checkboxes or a selectbox from it.

The core module "Options" seems to offer this functionality from the module description but whenever I select field type Integer, Decimal, Float, or text the only widget option I have is a standard textbox.

Term and node references do allow checkbox widgets.

Am I seeing a bug? Is there a different way of doing this in D7? I've tried adding these field types to both node types and vocabs but neither acknowledges the existence of the checkboxes widget.

Set "Type of data to store" to List (text), List (integer) or List (float) and Check boxes will be default widget. If you can't see them, make sure List module is enabled.


Webform adding custom component or modify radio buttons I need to make a webform that will display the radio buttons like this jsfiddle, where the label is above the radio button. Do I need to make a new webform component to achieve this or can I just modify the default to add the div and change orientation?

You should be able to do this with CSS alone.


How to add dynamic css for each node? I need to apply dynamic css for each node. I have stored the css into the database for each row of the page.

I have generating css like node_57002-en.css here, 57002 is a node-id with language code for each responsive layout.
For eg. If I select width for desktop layout for node-id-57002 then node_57002-en.css generated with below code.

@media only screen and (max-width:991px) {}@media only screen and (max-width:767px){}

I have to find out the better solution becouse, everytime generated  the new css for each node. Below is the code which I used,

$styles = $nodeProcessor->getStyles();
$rowCss = $styles->getDesktop() . "@media only screen and (max-width:991px) {" . $styles->getTablet() . "}" . "@media only screen and (max-width:767px) {" . $styles->getMobile() . "}";
$cssPath = $modulePath . '/resources/css/rows/node_' . $this->_nid . '-' . $this->_langCode . ".css";
$cssPath .= '?' . filemtime($cssPath);

I have some questions on this,

How to get that css from db and how to apply on front-page in
drupal manner.
How to cache the library css and how to clear the cache when css
updated?
If not then what is the alternative option.

I referred Dynamically generated CSS and JS document but it is only for dynamic js. I really appreciate if anybody helps me. Thanks in advance.

I think you're over-engineering things here.

If your CSS is per-node-specific and stored in the DB anyways, then why not just use a text field to store the CSS? You just need to create a field template to output the raw content of the field in a <style scoped> tag.


Creating a ticketing system in Drupal 8. How to change a node's field value without going to the edit page? I'm creating a simple ticketing system in Drupal 8 to log my daily tasks. The content type contains title, body, and ticket status. The status field can be new, in progress, or completed. When I create a new ticket, the status is set as new by default. I also have commenting enabled on this content type.

The issue I'm having now is the UX of this setup. I can comment on the ticket fine, but if I were to change the status of the ticket to in progress or completed, I'd have to goto the edit page of the node and make this change. How can I change the status value without going to the edit page? Is there a ajax field update feature?

I wan't to be able to make my comment and also change the status of the ticket all at once vs making a comment, then click edit to change the status.

You could build an ajax form that would update the node's "Ticket Status" field, embed that in a custom block and place that block on the page for that node or embed it in the node.  Instead of in a block, you could also create a field formatter plugin that embeds the ajax form into the display for that field.


Is hook_node_view() invoked every time? I wrote a custom module that records page views. So each time a user views a node, it creates an entry in a database table. Essentially I wanted my own custom statistics module.

The problem is, it's only called once. I would assume some kind of caching is applied to this function. I have this:

function hook_node_view( $node,  $display, $view_mode, $langcode)
{
    $nodeObject = $node['#node'];

    $insert = array(
        'created'    => REQUEST_TIME,
        'nid'        => $nodeObject->id(),
        'uid'        => \Drupal::currentUser()->id(),
        'ip'         => \Drupal::request()->getClientIp(),
        'session_id' => session_id(),
    );

    db_insert('node_view_log')
    ->fields($insert)
    ->execute();

}

But it is only called once per node, and not each time the node is viewed. Any idea as to why this is happening? Is there a way to turn of caching for this function only? Or is there perhaps a better place to log page views?

Drupal core provides the statistics module which does basically this. It just maintains a counter and not a record per visit, but that's the basic idea.

And it does that with JS that triggers a callback. The reason it does it like that is that nothing on the server side can reliably do this in many situations. You might have something like varnish in front of your site, then most requests will not even reach your webserver.


Will manually setting the expire timestamp in the boost_cache table actually expire the cache for a node? I am trying to get myself acquainted with Boost running on my Drupal 6 website. I know that boost has a boost_cache table where it stores the expires value for each node.

Now I want to know whether that if I set the value in the expire column manually to a preferred value, Boost will recognize it and expire the cached version of the node on the date in the timestamp and there is no other table related to Boost caching where I should make the changes.

You might prefer to use

boost_expire_node

which will actively flush the node from boost static html cache

It could be scheduled, if needed ( e.g a hook_cron_queue_info implementation worker callback ) or done as an immediate expiry


Build context menu for news articles (sample image included) I have a complex view that queries and presents a lot of news articles depending on year and month contextual filter arguments. Everything works fine so far. However, now I want to show kind of context menu next to the view result that looks like this (shows multiple screens with different menu content depending on current display):

What is the best/most elegant way to realize such a context menu? (no ugly hacks)

What I've already tried

I tried to accomplish that using the Views UI – no luck. Creating two different View blocks (one for a list of years and one for the months of currently selected year) didn't work, because in order to get a distinct result set I need identical fields that are used for "collapsing". The field I used was "Post date" – and this always differs.

I guess that I must write a custom module where I leverage the Views API and create that markup for the context menu. But where do I start? And how can obtain the current contextual filter arguments?

Not really an answer, but perhaps a lead.  In Drupal 6, a similar thing was accomplished with the book navigation block.  You could have the book navigation block filter to a certain number of steps up/down tree from the node page that you were currently viewing.

I am not sure how this could be accomplished with existing views configuration, as I think tree navigation is not a common thing for views.

This is more the kind of trick I would expect to find in Taxonomy, based on the vocab's hierarchy.  There, navigation can be a more certain thing, as the structure is defined in the vocab, and they are just filling the tree leaves with tagged nodes.  Again with the Drupal6 reference, but perhaps you can scavange code from http://drupal.org/project/taxonomy_treemenu

If you do code something, release it back to the community?


How to display a block on only the listed pages using wildcard and excluding subpages? I have a block I'm displaying using block setting's "Only the listed pages". I'm using a wild card asterisk to show the block on any pages following about-us/. For example: about-us/*

The problem is I ONLY want pages immediately after about-us/ to show.
For example about-us/faq would show the block but about-us/faq/content should NOT show the block.

I tried about-us/*/ but that had no effect.

Any suggestions?

Method 1. PHP filter

I think your question is partially answered here:

How to add page restrictions for blocks in drupal?

Only you might use this code:

<?php
$arg = explode('/', drupal_get_path_alias());
if ($arg[0] == 'about-us' && $arg[1] && $arg[2] == NULL) {
  return TRUE;
}
else {
  return FALSE;
}
?>

Method 2: Context module

Alternatively, you can try the Context module, which offers more robust visibility options. For instance, in addition to including paths you can prefix a path with a tilde "~" to exclude it.

I think this should do it:

about-us/*
~about-us/*/*

Edit: Added second method.

Edit: Using $_GET['q'] in method 1 instead of arg() (Thx, @leymannx!)


add first/last classes when using theme_menu_link Im building my own menu tree for various reason, but one think i miss is the first / last classes. I dont find anything about it in the API and i do have drupal_attributes($element['#localized_options']['attributes']) set.

Where and how would the first/last classes be called?

my function in template.php goes something like this (taken direct from the API)

function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

Use Menu attributes module and give special ID or classes to your menu items. The module currently allows you to set the following attributes for each menu item:

Id
Name
Target
Rel
Class
Style
Accesskey


Find user profile page link from database I know the link structure of a user page .
Like
For admin,it is example.com/users/admin
But I want to know from database how can I find the link? or which table contains the link?

The path "/users/admin" is actually an "alias" for something like "user/1", where 1 is the user id. In Drupal 7, these aliases are stored in the {url_alias} table along with the real path that they point to.

So if you want to figure out what user the alias "users/admin" points to, look in the {url_alias} table and you will see a column called "source", which should have something like "user/1". "1" in this example is the user id.


How do I programatically add address to commerce order I've a subscribe form on my website which i've got working(ish). So far i've got it asking user to input name, address, email, password and the subscription level + starter kit (from a list of promoted commerce items).

Once a user hits 'subscribe' the module creates a blocked user account (it will be activated by Paypal IPN listener if they pay), adds the commerce order (at checkout stage, thanks to Ryan for the script!) and then redirects to paypal for appropriate payment.

Up to this point i'm happy with everything except that the recorded order doesn't contain the address the user entered on the subscribe form and I can't figure out how do do this.

Has anybody managed it before,  just point me in the direction of the function and i'll go from there.

Thanks

To record the address on the order, you must create a customer profile of the relevant type (billing information or, if you have Commerce Shipping on the site, shipping information), populate its addressfield value, and reference it from the order you've created. My recommendation would be to use the entity_metadata_wrapper() from the Entity API to manipulate those field values.

The addressfield on the customer profile you need to populate is commerce_customer_address, and the reference field on the order is commerce_customer_billing (or _shipping respectively).


Plugin Derivatives For Queue and Migration Plugins I've created a custom Content Entity and a custom Content Entity Type, basically I'm mirroring the Node module but the purpose of this is to have external data to be synced with this setup(not using node and the content types because I want the content not to have any canonical pages, and at the same time, I am supposed to have content with landing pages).

Content Sync - this link provides a good example of setting up a sync process using the Migrate module. I would need a set of plugins to define the migration process for a custom entity, but since I have multiple types of my custom entity, can it be possible to use derivatives for any types of plugins(Migrate module - source, process, destination and Queue plugins like QueueWorker) to handle each type of custom entity dynamically?

This might be a huge question to dig into, but I'm more interested in a yes/no type of answer, because I can do the investigation myself afterwards, just need to know if it's worth it.

The annotation cannot be derviated, but the class itself yes.


Entity Translation and Field Collection Entity Translation exposes a checkbox on fields, entitled:

  Users may translate all occurrences of this field

When dealing with a Field Collection field, which of the following should I check the box for?

Only the field collection field
Only the child fields
Both the field collection field, and its child fields

Field Collection doesn't support Entity Translation, so my advice is to find another way to achieve your aim.

There is a patch available which has been under development for a long time, use at your own risk.

The Drupal.org issue with it's accompanying patch can be found here:
https://www.drupal.org/node/1344672


Show block if user has never completed Ubercart checkout Part of my website's signup process is the purchase of a product via Ubercart. The signup process directs the user to the checkout page with the product already in their cart. The problem I am having is when users get to the cart and then abandon their cart.

I'd like to add a block to the user profile pages that says "Your profile is not yet complete. Please click here to enter your payment info", and I only want that block to show up for users who have not completed that order process. How can I filter users in that way to make that block show up only for those select users?

I've got it figured out, at least for my own use-case:

I use a webform to collect info on the newly-signed-up user. That webform then redirects to the checkout page with the product in the cart. I used the Webform Rules module to auto-assign a "pre-customer" role to the user when they finalize the webform. Then, when they complete the cart checkout process, that user role is removed and the "customer" user role is assigned to their account.
I've got a block that is visible only to users with the role "pre-customer". That block is the one where they will be prompted to click a link to finalize their order/payment info.

Hope this can help someone else at some point! :)


Adding Pagination to to custom form block results I have created a custom block that has a form which has a list of result and I wanted to know how to add pagination to the results

Thanks for any help on this

Colin

/**
 * Implements hook_block_info().
 */
function custommodule_block_info() {
    $blocks = array();
    $blocks['latest_news'] = array(
        'info' => t('Latest News'),
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

    /**
 * Implements hook_block_view().
 */
function custommodule_block_view($delta = '') {
    $block = array();
    switch ($delta) {

        case 'latest_news':
            $block['subject'] = t('');
            $block['content'] = latest_news();
            break;
    }
    return $block;
}

/*
 * Implementation of hook_theme
 * */

function custommodule_theme() {
    return array(

        'latest_news' => array('variables' => array('data' => array()),
        'template' => 'latest_news'),

    );
}

    function latest_news() {
     $query = db_select('node', 'node');
    $query = $query->fields('node', array('nid'))
            ->condition('node.status', 1) //Published.
            ->condition('node.type', 'auction_news');
    $query = $query->extend('PagerDefault');
    $result = $query->limit(20)->orderBy('node.created', 'DESC')->execute()->fetchAll(PDO::FETCH_ASSOC);
    $paging = theme('pager');

    return theme('latest_news',array('data' => $result,'paging'=>$paging));
}

In a tpl file latest_news.tpl.php

    <?php
    foreach($data as $lat_news)
    {

       echo '
'.$lat_news->nid.'
';
    }
    ?>

<?php echo $paging;?>


View will not display taxonomy location information I have a taxonomy that contains information about event venues. I am using the location module to add locative information to these taxonomy terms.

I've created a view so that I can see all my venues and their location information, but the location information is not appearing in the view.

Here's a screenshot of the view I have built, but the location information does not appear!

Each term has its location info filled in:

It's not a great answer, but I do have an answer.

For some reason, Views isn't pulling this data. I've been unable to get a clean install of Drupal 7, views, location to pull this info when entered in the Location fieldgroup on a taxonomy term.

I HAVE been able to create a custom field for the location via 'manage fields', and THAT will appear in Views.

I hope that helps you (and anyone else looking at this!)


Translate tab missing I am working on my first multilingual Drupal 9 website, and I face a challenge. I can't seem to get my contact webform elements translated. I am using Webform Version: 6.0.2.
I have enabled translation on the content type, and I can translate the title, body, menu item fields. But I can't figure out how to translate the actual labels & placeholders of the form elements. I have watched this video (D8), but I do not have the Translate tab that he is using: https://www.videodrupal.org/video/20180321/translating-webforms
I suspect that there is some module og configuration setting that I am missing, but I can't figure out what it is, so any help would be appreciated. My available tabs are the same as the ones on the screenshot from the Webform module page: https://www.drupal.org/files/issues/2018-05-19/webfork-wizard-admin.png

The form labels are part of the webform's configuration, and their translation is therefore handled by the Configuration Translation (machine name: config_translation) module. When that module is enabled, it will add the Translate tab.


How to change path using the Content: Link to Content In Block view I want to set the link of content with the title name
How to Rewrite Results using the Content:Link to Content?
Example showing node/8 to john-bartlett(content title name)
By using this {{ view_node_1 }} i am getting the node/8 path but i want the title name john-bartlett.

Please provide any solution regarding this

Download Pathauto module. After installing go to http://YOURSITE/admin/config/search/path/patterns and click add patterns like below.

After adding pattern go to http://YOURSITE/admin/config/search/path/update_bulk and select content and check "Regenerate URL aliases for all paths" and click update. After this, ALL your node path alias should be generated with the title of that nodes.

Then in rewrite result's add this line:

{{ title }}

All your links and tags will be on your node titles.


The connection was reset when creating a new node On a localhost environment, when I try to create a new node, I get this message:

  The connection was reset.

There is some issue with css, cache and/or registry since when I disable the css aggregation it works for the next node and it stops for the next node creating. In order to work again for a new node it needs enabling the Css aggregation and so on.

Also when I clear caches I get this kind of messages:

  The following module has moved within the file system: views_test. In order to fix this, clear caches or put the module back in its original location. For more [warning] information, see the documentation page. bootstrap.inc:1128

Any suggestions?
Thanks.

There are in fact two issues in your question.

To solve The connection was reset issue, have you tried to run rebuild_registry ?

drush dl registry_rebuild-7.x
drush en registry_rebuild-7.x -y
drush cc drush
drush rr

Some people also reported that with Coder Module but not only, they had to edit httpd.conf, increasing the Apache stack size to 8MB

<IfModule mpm_winnt_module>
   ThreadStackSize 8388608
</IfModule>

For the 2nd issue The following module has moved within the file system, this appeared since Drupal 7.50 release. A straight way to correct these errors is to use Module Missing Message Fixer. You'll find alternatives and full explanations in this DO post.


Populate a drop down select list with the results from a view with entity reference relationships Ok. Perhaps this has been asked before  in this site somewhere but for the life of me I can't find an answer.

I have three content types: Client, Contact and Job ticket.

Clients are companies with whom I conduct business. Contacts are contact persons within these companies. The Contact content type has a reference field referencing their company's node. Job tickets are tickets for jobs these companies hire me to do for them. In this content type I have two reference fields: one for the Client and one for the Contact.

What I need is to have the Contact reference field (drop down select list) dynamically populated with the contacts for the client I chose in the Client reference field (another drop down select list). Because if I populate it with ALL the Contact nodes then I get a very big list and I don't know which contact belong to Which company.

I know I can do this with a entity reference view display but I don't know how to configure it.

Thanks in advance for your help.

Reference field option limit

  This module allows reference fields of several types to have their
  widgets' available options limited by the values of other fields in
  the current entity.

I think this link might already be enough.
If not, then I am happy to expand the answer with more specifics.


How do I sub-sort a view? We have a view containing two fields that we would like to sort - specifically issue # and Title. We would like to sort the view first by the Issue # field and then secondly by Title, so that nodes from the same issue are clustered and sorted again by title.

How can we sub-sort a view so that one field is the primary sort and another is the secondary sort (similar to sorting in a spreadsheet)?

Just add two entries in the "Sort criteria" section, left column, bottom. The more important sorting criteria should be on top.

Add button can be used as a drop-down, to show Rearrange button, if needed.


Using Composer in a multisite installation How do I manage modules via composer in a multisite architecture? For example, if I want one site to have version 2.3 of a module, and another to have version 2.4, how do I do this?

Do I have a composer file in each site that can inherit from the composer file in the parent Drupal application?

Short answer: you cannot do it The (new Drupal) Composer Way™ (still).
The composer is mostly project-oriented, however, based on the fact that they are projects of the projects, there is a chance that a composer.json could be made that would operate on a subsite level.
As far as we can go would be to hope that something will be done in the coming 9.2 release, somewhere south of Spring 2021. Until then, workaround and search for the best practices and other experiences (however sparsely) seems the only way
#2847218: Improve documentation around the multisite functionality
The (temporarily and incomplete) solution:
The only thing you are left with is to use the composer for the common, shared modules and to use drush or manually download modules and themes according to Drupal multisite structure:
-- sites
   -- site1
         -- modules           ----> site specific modules
            -- custom
            -- contrib
         -- themes            ----> site specific themes
            -- custom
            -- contrib
         -- files

Beside official documentation, you can read this post too: Drupal Multisite Setup: Are There (Still) any Valid Reasons to Use It? Should It Get Removed in Drupal 9.x?


Ubercart or learn a new ecommerce package? Im a big Drupal fan which is why Ubercart is the obvious choice for me when it comes to ecommerce. Ive made a couple of Ubercart sites and I havn't been massively impressed.

Ubercart doesn't seem very powerful when you need extensive business logic, can be hard to theme and has javascript reliance. Admittedly ive only played with others like magento and zencart, but Ubercart doesn't seem to lead in its field the way Drupal does in its.

Im reluctant to learn a new ecommerce package due to the time required, but the javascript reliance alone makes me wonder if I have to. Has anyone else had a Drupal background and faced a similar dilemma with ecommerce?

Thanks

Disclaimer I help develop commerce (commit patches) from time to time and maintain a few commerce modules, so I might be a bit biased in my opinions

I haven't done ecommerce outside of Drupal, but I have extensive experience with both (Ubercart) Drupal 6 and (Drupal commerce) Drupal 7.

Drupal commerce has a lot of great advanced both for developers and site builders.

Since it has heavy views and rules integration, it makes it very easy to configure the modules to do what you want to do. With Rules you can add a lot of custom logic like discounts. The tax support is also very good already and is very easy to customize for your location.

The only things that's missing with Drupal commerce right now is the host of modules for various stuff compared to ubercart Drupal 6. But this is not as bad as it might sound, and there are a lot of modules being created in the community around commerce.

For developers the experience developing with commerce is the best I've tried for a long time. I started when commerce was still in alpha and have had to deal with API's chaining etc. This has all stabilized now, and the result is very impressive. You can tell that commerce is built from the ground up by people who know how commerce should be made with Drupal. It's very flexible and there's no inconstancy and strange hacks like there is in ubercart. One area in particular where there is a big difference is the price handling system is very cleverly built. Commerce is built to handle multi currency unlike ubercart which I've found to be a major pain.

Conclusoin

All in all I find that commerce is more powerful out of the box using only the UI, and the code you write is in my experience generally more clean and easier to maintain. It doesn't have any legacy code, which is easy to see and it is built to take advantage of all the new Drupal 7 features.


Maintenance mode doesn't work on front page without www prefix I have my site in sub directory and it works both with and without www prefix but when I place it in maintenance mode I've noticed it doesn't work for the front page without www prefix until you either try log in or go to another linked page.

Is there anyway I can fix it so it works on that front page when no www prefix?

Add this to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

(Per this tutorial)


What happens if a user uploads an image but doesn't save the node? I would like to know what happens if a user uploads an image by image field but doesn't save that node?

It seems that image will be in the directory but no node refers to it. Is there anyway to remove such files?

The image files will be removed during cron runs.

This happens because the status column in file_managed for those files will still be zero, indicating that they're temporary, and can be safely removed after a period of time.

The responsible code is in system_cron(), in case you need to reproduce/analyse further.


Drush command using chef causing error "Command needs a higher bootstrap level to run" Expected process to exit with [0], but received '1'

---- Begin output of /usr/local/drush/drush -y en views ----
STDOUT:
STDERR: Command pm-enable needs a higher bootstrap level to run - you will   [error]
need invoke drush from a more functional Drupal environment to run
this command.
The drush command 'en views' could not be executed.                  [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]
Hint: This error often occurs when Drush is trying to bootstrap a
site that has not been installed or does not have a configured
database.

Please note that database and executing command lines are having full privileges.

In your drush command you may need to specify the location of your Drupal files. Use --root=<path> argument.

https://github.com/drush-ops/drush#options


Email all Organic Group members when a subgroup is created I have an Organic Groups / subgroups structure where an Organisation is a group, a Property is a child group of an Organisation, and a claim is a child group of a property. So:
Organisation > Property > Claim
Each subgroup is set to inherit its parents users

When a new Property is created, I can use rules to 'Get group members from group audience' to email all of the members of the group:

However when a new Claim is created the same rule only emails the user who created the Claim. I think that this might be because inherited users are handled differently from normal users. You can see this by going into the 'group' tab on the claim and then clicking on people:

We can see in the screenshot above that there are three inherited users, but only the user who created the node will be emailed, the other two will not.

How should I email the inherited users when subgroups like Claim are created?

-- Addition --

og_subgroups.views.inc is used to create the view shown above. The contents of this file are:

function og_subgroups_views_pre_render(&$view) {
  if ($view->name == 'og_members_admin') {
    // Add an overview of the users that are inherited from parent groups.
    $inherited_users = _og_subgroups_get_inherited_users($view->args[0], $view->args[1]);
    $header = array('Name', 'Inherited from');
    $rows = array();
    $membership_states = og_group_content_states();
    if (!empty($inherited_users)) {
      foreach ($inherited_users as $inherited_uid => $data) {
        $row = array();
        $row[] = l($data[0]['user']->name, 'user/' . $inherited_uid);
        $inherited_from = array();
        foreach ($data as $inheritance) {
          $inherited_from[] = t('!parent (@roles)', array(
            '!parent' => l(entity_label($inheritance['inherited_from']['type'], $inheritance['inherited_from']['entity']), 'group/' . $inheritance['inherited_from']['type'] . '/' . $inheritance['inherited_from']['id'] . '/admin/people'),
        '@roles' => implode(', ', $inheritance['roles']),
      ));
    }
    $row[] = implode(', ', $inherited_from);
    $rows[] = $row;
  }
}
$view->attachment_after = theme('table', array(
  'caption' => t('Inherited users'),
  'header' => $header,
  'rows' => $rows,
  'empty' => t('No inherited users.'),
));
  }
}

It would be great if someone could suggest how I might be able to use the above code in rules. It would be great if I could use'Execute custom PHP code' and use something like

$inherited_users = _og_subgroups_get_inherited_users($view->args[0], $view->args[1]);

but that doesn't work in a custom PHP block in Rules. I can see the function _og_subgroups_get_inherited_users in og_subgroups.common.inc and am not sure if I can use this code to help.

Using Organic Groups 7.x-2.7 and Organic groups subgroups 7.x-2.0-beta1

I managed to use make a custom rules file for OG Subgroups that achieves what I need it to. It adds the rule 'Get subgroup group members from group audience' to a 'Custom' rule group:

This makes the users of the subgroup available to rules. You can then loop through the users and send an email to each of them:

In order to do this I created  custom 'og_subgroups.rules.inc' file in the root of the OG subgroups module. This is the code I used inside it:

<?php

/****************
Adds the ability to get the members of the parent group from a subgroup using rules
/****************

/**
 * Implements hook_rules_action_info().
 */
function og_subgroups_rules_action_info() {
  $items = array();

  $items['og_subgroups_get_members'] = array(
    'label' => t('Get subgroup group members from group audience'),
    'group' => t('Custom'),
    'parameter' => array(
      'group_content' => array(
        'type' => 'entity',
        'label' => t('Group content'),
        'description' => t('The group content determining the group audience.'),
      ),
    ),
    'provides' => array(
      'group_members' => array('type' => 'list<user>', 'label' => t('List of subgroup members')),
    ),
    'base' => 'og_subgroups_rules_get_members',
    'access callback' => 'og_subgroups_rules_integration_access',
  );

  return $items;
}

/* NEW FUNCTION ************************************************/

// This callback creates the hashed string by using the parameters provided through rules' UI
function og_subgroups_rules_get_members($group_content) {

// get the nid from the passed value of the content being added
$nid = $group_content->nid->value();

// trying to manually call the get inherited users function from og_subgroups.common.inc
$inherited_users = _og_subgroups_get_inherited_users("node", $nid);

$members = array();

foreach ($inherited_users as $inherited_uid => $data) {
  // Get the group members the group content belongs to.

  $user=user_load($inherited_uid);

  // push the returned user to the array of members
  array_push($members, $user);

}

// return the users
  return array('group_members' => $members);

}

/**
 * OG Rules integration access callback.
 */
function og_subgroups_rules_integration_access($type, $name) {
  // Grant everyone access to conditions.
  return $type == 'condition' || user_access('administer group');
}

For those of you who prefer patches here is the patch I created: Patch on drupal.org


Deleted revisions still listed I started dev on Drupal 8.6.0 and have since updated to 8.6.3. I have also cleared caches, run updates and cron.

I have set up a content revisions view:

FIELDS
Content revision: Revision create time
Content revision: Revision ID
Content revision: ID

FILTER CRITERIA
Content revision: Published (= Yes)

SORT CRITERIA
Content revision: Revision create time (desc)

CONTEXTUAL FILTERS:
Content revision: ID

So I can get all the revisions for 'this' node. The view is a block, so when I place the block on a node, I get the revision id & date showing as expected.

BUT, there seem to be additional revisions in the view then listed in the revisions tab.

For my test node, I have deleted some of the revisions.
The node's revisions tab lists:
revision id:97 - 21 Nov 2018 [the current active revision]
revision id:96 - 16 Nov 2018
revision id:39 - 22 Oct 2018
...

But the view is listing
revision id:97 - 21 Nov 2018
revision id:96 - 16 Nov 2018
revision id:84 - 05 Nov 2018 <- not listed on the node's revisions tab

If I take a look at the DB, I have the following:

table: node
nid:1; vid: 97;
which matches the current node / vid

table: node_field_revision
nid:1; vid: 97; changed: 21 Nov 2018
nid:1; vid: 96; changed: 21 Nov 2018
nid:1; vid: 84; changed: 05 Nov 2018 <- not listed on the node's revisions tab
...

table: node_revision
nid:1; vid: 97; time 21 Nov 2018
nid:1; vid: 96; time 16 Nov 2018
nid:1; vid: 84; time 05 Nov 2018 <- not listed on the node's revisions tab
...

If I go to /node/1/revisions/84/view the revision shows.

How do I either remove these deleted revisions or filter them out of my view?

thank you for your help,

ice70

I am using the diff module, pulled that apart to find it is using:

if ($revision-&gt;hasTranslation($langcode) &amp;&amp; $revision->getTranslation($langcode)-&gt;isRevisionTranslationAffected())

modified my view to use the filter:

Content revision: Revision translation affected (= True)

The revisions pulled by the view now match the revisions shown on the node's revisions tab.


Change "Custom Text" field value In Drupal 8, I created a view containing a Custom Text field. I want to alter/change its content for each row I get after running some code. I tried implementing hook_views_pre_render() and template_preprocess_views_view_fields(), but I wasn't able to access this field.

I also would like to learn when this nothing field is added to the view output, and after which hook.

To extend and clarify Saud Alfadhli's answer for others (I'm not allowed to comment yet), hook_preprocess_views_view_field (hook_preprocess_views_view_fields with the "s" exists as well) works great for this. Both the view ID, display ID, and field ID can be easily inferred from this hook, and the field output can easily get overwritten (as both a string or render array). Here's a quick example replacing all occurrences of my second custom text field with a simple string:

/**
 * Implements hook_preprocess_views_view_field().
 */
function hook_preprocess_views_view_field(&$variables) {
  if ($variables['view']->id() === 'my_view_id' && $variables['field']->options['id'] === 'nothing_2') {
    $variables['output'] = 'Hi Mom!';
  }
}

Hope this helps!


How to add image field to main navigation menu item I am having a problem using MYTHEME.theme file to add image field in the menu item object. I need to be able to specify an image for each menu link/item!

function HOOK_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = [];

  if ($entity_type->id() == 'menu_link_content')
  {
   $fields['menu-image'] = BaseFieldDefinition::create('image')
   ->setLabel(t('Image shown next to menu name'))
   ->setComputed(TRUE);
  }
  return $fields;
}

I don't think that this code actually runs, I cannot see any effects!

Here's how I added a custom image field to my main menu link items. I added this to my custom module.

function my_custom_module_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'menu_link_content') {
    $fields['menu_link_image'] = BaseFieldDefinition::create('image')
      ->setLabel(t('Menu link image'))
      ->setDescription(t('Upload the image related to this menu item'))
      ->setDisplayOptions('form', array('type' => 'string', 'weight' => 0));

    return $fields;
  }
}

Flush the caches and the field should appear in the Menu Item form.

The only issue I had was that I was getting a MySQL error Column not found: 1054 Unknown column 'menu_link_image' when submitting the form. One solution to that was to add the column menu_link_content to the menu_link_content_data table but this is not a very good solution since you are altering a core Drupal db table.

I am still working on finding a better solution (e.g. using hook_form_alter to save that field to a different/custom db table). Any feedback/comment is appreciated.


How do I get the fields of form attached with a content type as token? I do not know is it possible or not. I have a content type for creating tickets. I have a form attached to content type which contains ticket state and ticket assignee fields as drop down. Now I want to create a Rule when state of ticket updated then send an email to ticket creater. The problem is that I could not find the state field values as token.

If I understand your question correctly you want send email after state field changes by Rule:

You should:

Create a new rule that will react to the After updating existing content event
Use the following condition:
Data comparison: node:field-your-field(maybe field-state) and node-unchanged:field-your-field
Select Negate: FALSE
Create the action
Send the email


Get taxonomy terms page based on exposed filters value I've created two taxonomy vocabs: Language and Genre. LANGUAGE consists of the following terms: English,Spanish,French,etc and GENRE consists of Rock,Pop,etc.

Am using the taxonomy term page view with exposed filters for language and genre.

When am in a page that list all songs under the term english, the filter for genre and language also appears. All good till here.

Now, If i select spanish from the filter..i want the term page to reload and show the relative results.
 How can i work this out???

It will be easier if you will use just one vocabulary. Smt like this:

English
- Rock
- Pop
- etc.
Spanish
- Pop
- Rock
- etc.

Then you can use hierarchical_select module to filter exposed lists automatically.

If you can't change vocabulary structure, you should use hook_form_alter() ...


New measures to prevent spam in comments of nodes? I have a website with a node and comments which are moderated. I have installed Cache module, Image captcha (light distorsion). There was no spam till a few months ago. I installed Honeypot module and the few messages (probably automated) stopped being entered into the moderation list.

This week the site suffered a massive amount of flood spam. This coincides with the attack which is explained in Drupal.org. Is it possible that the attackers have learned how to override Honeypot and Image Captcha countermeasures?

How can I improve the security so the spam is reduced? My client will not allow more than a very small human input to delete a few spam messages.

Maybe this module will help you: BOTCHA

There are more protection methods than just honeypot.


Using the built in summary feature when using ONLY paragraphs module for text I want to have more flexibility in creating content as usual. Therefore, I use the Paragraphs module, and I also disabled the standard body text. So now, a user can now freely decide how he wants to mix images, text and other content (like embedded videos). For example, an article could now start with a text followed by a full size image, or with 2 half size images followed by a full size video and then the text and so on.

So far so good. Now the problem is that I loose the standard summary function since the default body text is just disabled. This is especially a problem for any list of articles, i.e. the front page.

I have managed to kinda solve this problem by a custom preprocess hook:

function MY_THEME_preprocess_node(array &$variables) {

  $node  = \Drupal\node\Entity\Node::load($variables['node']->id());

  if ($node->field_paragraph && !empty($node->field_paragraph->getValue())) {

    foreach ($node->field_paragraph->getValue() as $key => $value) {
      $paragraph = FALSE;
      if (!empty($value['entity'])) {
        // Use that, we're probably previewing.
        $paragraph = $value['entity'];
      } elseif (!empty($value['target_id'])) {
        $paragraph = Paragraph::load($value['target_id']);
      }

      if (!empty($paragraph) && $paragraph instanceof Paragraph) {

        $summary = $paragraph->getSummary();

        if ($summary && $paragraph->type->getValue()[0]["target_id"] === "text") {
          $variables['summary'] = $summary;
          break;
        }
      }
    }
  }
}

What this does is to loop over all paragraph entries (if any) in a given node and stop iterating at the first occurence of a paragraph type named "text", if there is also a result for the getSummary() function, i.e. this paragraph item also contains some text. Keep in mind that I am far from being a Drupal expert, so this code might not be the optimal way?

However, I cannot seem to control the length of the summary, also any headlines defined in the same paragraph are included as well. Last but not least, the result also contains unneeded markup, so in my node--article--teaser.html.twig twig template I have to strip out those tags again:

<p>{{ summary|striptags }}</p>

The next problem arises when I want to use that summary for the description meta tags on any given article page (so in this case, NOT the pages that contain only lists of articles). Usually I would just use the Metatags module and use this for the description: [node:summary]

Of course that does not work here, and I can imagine that further down the road I will encounter more problems like this.

Therefore, it seems to me that the cleanest way would be to kinda emulate [node:summary], i.e. that this value is automatically calculated by something similar to the function I used above. So for the consumer of this value this would look identical as if the page / node had an actual "default" summary.

Now, is this possible at all, and if "yes" how can I achieve this? Any insights are greatly appreciated!

Well, looks like it is time again to answer my own question!

So, since the Metatag Module I want to also use is based on tokens anyway, I have managed to implement this using my own module which in turn just defines an additional custom token which in turn returns my desired summary. Here is what my current custom_summary_token.module code looks like right now (still work in progress):

use Drupal\Core\Render\BubbleableMetadata;
use Drupal\paragraphs\Entity\Paragraph;

function custom_summary_token_token_info(){
    $type = [
        'name' => t('Nodes'),
        'description' => t('Tokens related to individual nodes.'),
        'needs-data' => 'node'
    ];

    $node['custom_summary'] = array(
        'name' => t("Custom Summary"),
        'description' => t("Token for dynamically generating a node summary, depending on the content. Used for extracting text when not using standard body field, but only paragraphs."),
    );

    return [
        'types' => ['node' => $type],
        'tokens' => ['node' => $node],
    ];
}

function custom_summary_token_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata){

    if (!isset($data['node'])) { return; }

    $replacements = array();
    $node = $data['node'];

    if($type == 'node' && !empty($node)) {

        foreach ($tokens as $name => $original) {

            switch ($name) {

                case 'custom_summary':

                    if (!empty($node->body->value)) {

                        $text = strip_tags($node->body->value);

                    } else if ($node->field_summary && !empty($node->field_summary->getValue())) {

                        $text = $node->field_summary->getValue()[0]["value"];

                    } else if ($node->field_paragraph_test && !empty($node->field_paragraph_test->getValue())) {

                        foreach ($node->field_paragraph_test->getValue() as $key => $value) {
                            $paragraph = FALSE;
                            if (!empty($value['entity'])) {
                                $paragraph = $value['entity']; // Use that, we're probably previewing.
                            } elseif (!empty($value['target_id'])) {
                                $paragraph = Paragraph::load($value['target_id']);
                            }
                            if ($paragraph !== FALSE && $paragraph instanceof Paragraph && $paragraph->getType() === "text") {
                                $text = strip_tags($paragraph->get('field_text_body')->value);
                                break;
                            }
                        }

                    }

                    if (strlen($text) > 150) {
                        $text = substr($text, 0, 150)." ...";
                    }

                    $text = str_replace("&nbsp;", " ", $text); // filter out artefact when editing with chrome
                    $replacements[$original] = $text;
                    break;
            }
        }
    }

    return $replacements;

}

So what this does in that tokens hook is (after checking that we have the right token of course) first to look for an ordinary default body text which is not empty. Simply because then this also works for my other (in this case also simpler) content types. Then, the code looks for a custom field named field_summary. Turned out that some users actually want to create a custom summary, so yeah now they can do that as well. For those who don't (the majority ...), the code then looks for the first paragraph instance which is also a text block (and not empty). Last but not least, tags are stripped, and the whole thing is truncated to 150 chars, with some "..." appended for good measure.

Now, I can use this just like any token in my Metatag setup: [node:custom_summary], and - with a little help from the twig tweak module - also in any template:

{{ drupal_token('node:custom_summary', { node: node }) }}

Of course this implementation still might be too naive or there would be an even better way, also I am not sure how big the performance impact of such a solution is. But hey - at least this works!

What would you think?


Drupal running behind a proxy send emails with links to the wrong domain/IP So I have a public site http://www.mysite.com with the following vhost entry:

ProxyPass /press http://123.45.67.89/press
ProxyPassReverse /press http://123.45.67.89/press

And I have a Drupal site running at http://123.45.67.89/press ready to receive requests.

All works fine except emails sent from the Drupal site come through as:

http://123.45.67.89/press/user/reset/1/1384468691/3WY1S7QUJK8Wdp78U9Itu2ygw-KenVLY_9mgBZeTOy8

Which is not accessible to the general public, and instead needs to output:

http://www.mysite.com/press/user/reset/1/1384468691/3WY1S7QUJK8Wdp78U9Itu2ygw-KenVLY_9mgBZeTOy8

How can I trick Drupal to think it's being accessed on the desired domain? Thanks for any advice.

Silly me, forgot all about setting $base_url in settings.php. By default it is commented out, but I've now set it to:

$base_url = 'http://www.mysite.com/press';


Change wording of history (member since) Is there a way to change the wording of "Member since" to something else?

You could put this in your settings.php

$conf['locale_custom_strings_en'][''] = array(
   'Member since'      => 'Your new label',
);

Or you could change it in the form by preprocessing that form.  I think there are also language modules that allow you to change phrases/labels site-wide.


Change header style when users sign in I am using the default template and I want the background color of the header change when a user signs in.

I know I will need to write a simple if statement like if (user_is_logged_in()) { } somewhere, but I don't know where to place it.

Look at the body tag of your theme. Some themes add classes to it indicating whether or not you are logged in.  If yours does, then you can do this via css by:

.logged-in #header
{
   background-color: #fff;
}

.not-logged-in #header
{
   background-color: #000;
}

If you don't have a body class that indicates logged in status, then you modify your page.tpl as user4035 suggested. There is no is_user_logged_in function.  Instead, it's

<?php
global $user;

if ( $user->uid ) {
  // Logged in user
}
else {
  // Not logged in
}
?>

Code Source - https://drupal.org/node/92218#comment-167984


How to restore a site from a backup done with Backup and Migrate module using Drush Just that. I've a backup using the backup and migrate module. I've done some changes and now the site is down. I can't restore the site using the admin interface (because it's broken).

Can I use Drush to restore it?

Yes, you can restore your backup with Drush.

Here are Backup and Migrate commands for Drush explained: http://www.only10types.com/2011/03/drush-backup-and-migrate-command.html

I think drush bam-restore command is what you are looking for.

  bam-restore Restore the site's database with Backup and Migrate.

  Examples: drush bam-restore db manual
  "LCC-31.03.2011-14.01.59.mysql.gz" - restore the default database
  using the given dump file, which can be found in the destination
  called "manual"

  Arguments: source - Required. The id of the source (usually a
  database) to restore the backup to. Use 'drush bam-sources' to get a
  list of sources. Defaults to 'db' destination - Required. The id of
  destination to send the backup file to. Use 'drush bam-destinations'
  to get a list of destinations. Defaults to 'manual' backup id -
  Required. The id of a backup file restore. Use 'drush bam-backups' to
  get a list of available backup files.


Query custom field on user table How do you query custom fields on the user table? If edit a user in the Admin panel, and hit the DEVEL tab, I see the field I added, 'field_display_name'.

In a node template php file, I want to replace the 'name' field with 'field_display_name'.

When I query, either using:

$result = db_select('users', 'u')
  ->fields('u')
  ->condition('name', 'bubba', '=')
  ->execute()
  ->fetchAssoc();

or

$rst = db_query("select * from {users} where name = :name", array(':name' => 'bubba',));

neither one of these return my custom field on the user table. (DPM does not show field_display_name)

So obviously, i'm missing something fundamental in my understanding of the data structure.

How do i return this added field by querying with uid or name to return and print the 'field_display_name' ?

Entity fields are in their own separate table(s), they don't get attached to the base entity table.

You can use an EntityFieldQuery to get that data:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_display_name', 'value', 'bubba');

$results = $query->execute();
if (!empty($results['user'])) {
  $users = user_load_multiple(array_keys($results['user']));
}

See Where does Drupal 7 store custom user account fields? for a bit more info


Is there a way to tell composer about manually updated modules? I am working on a drupal 8 site and tend to update some modules:

I run the composer outdated 'drupal/*' command and it shows me the list of modules need update.
Running composer update drupal/module_name --with-dependencies end up with discard changes output.
So I choose to update the module from admin interface, after updating db changes, the status report not shows any update anymore but running outdated command in composer list the modules again.

This means I somehow need to announce to composer about this manual update (I think by changing composer.json and/or composer.lock, but I did not find the flow of it, yet.

Yes, in the sense if you want to hack composer.lock you can make Composer think it got updates it never downloaded.

That requires you to know what composer.lock properties have changed (like content-hash & packages[*]) and apply them manually to the file.

That said, doing this is breaking the entire purpose of Composer (composer.json represents a manifest of what you need & composer.lock represents a manifest of what Composer retrieved); you
 run the risk of breaking of what composer.lock should do (i.e. composer install on any machine will retrieve the exact same files as when you made your last updates); so you
 should really think about the impacts on other environments/hosts that use your composer.* files.

If you're committing to a Composer-driven process, it's better to troubleshoot why your dependencies aren't updating as other commentators have suggested (e.g. too broad versioning in composer.json, auto-dropped changes from a non-interactive run)


managed links in Wysiwyg? I am looking for a systematic way to deal with links in Drupal, like there is for images.
For images, you add image field to content type, then install "Insert" module and you can use Wysiwyg to easily insert the image anywhere inside the node content and still have it "manageable" because it is a field.

I am looking for something similar for links (external and internal), but can't think of any existing method. What I have found is to either use "Links" module and have all links displayed at the bottom of the node (via a field) or use Wysiwyg "Link" button and insert links anywhere, but they are unmanaged.

I am looking for a solution where:

All links would be more easily managed - because
they would be kept as fields (most probably "Link" field)
It would be possible to have those links displayed not as a link
list at the bottom of the node, but rather in various places inside node content (like
images with "Insert" module).

I would recommend that you base your solution on the ckeditor_link module. To use this module, you will of course need to be using ckeditor for your wysiwyg editing.  If this is not a problem, then users will be able to use a new "Internal Link" URL type when creating links.  Typing in the node title of the target will make a link to node/1234, and this link will be transformed into a link to the node's path alias at render time.  Now, your internal links will automatically change if you edit the path alias of the node; there is nothing else you need to do to manage them.

For external links, I would make a new node type for external links, and make a landing page for each one.  Use a link field on the landing page to hold the external link, and put boilderplate text in your template for that content type.  Once you've set this up, you can again use the ckeditor_link module to target your landing page.  If you don't like the idea of a landing page and you're a little handy with coding, you could make your own version of ckeditor_link for external links, and modify its input filter to render the URL of the target link instead of the URL of the landing page.


How to embed a search result on a node? I am looking for a while to include a search results on a node.

Let me explain:

Administrator side, i wish i could, when i create a node, enter search criteria (eg "home + garden"-cellar), which generates me, when viewing the node, a list of nodes matching these criteria.

It will give : The title of my node, body, and below the result of my research.

I do not know if this is clear, but how could I do that?

I'm using Search API on my site, i should programmatically execute a search in the index from keywords ... but I'm stuck on this point.

Thank you in advance!
Joel.

So, I will create my own module to do that. The module will offer a new field can be created on any type of content, and will accept search criterias, the number to display, and so a search result will appear in the node.


How to redirect toward a specific node from front-page in Drupal 7? I have a multi language site made in Drupal 7. And I want to check if I am on the front page then if true to redirect the user to a to some specific node.

I have tried different methods:

to create a page front--page.tpl.php and then to check language and then redirect
I have put this code in page.tpl.php:

 global $language;

 if ($node->nid == 1) {
     if ($language->language == "en") {
         header('Location: en/home');
     } elseif ($language->language == "fr") {
         header('Location: fr/accueil');
     }
 }

I am using i18n module for Drupal 7 so I have tried also to use $conf['i18n_variables'] in settings.php like that:

  $conf['i18n_variables'] = array(
     'site_frontpage',
     'site_name',
  );

But I have not succeed to do it. Have you any suggestions ?

page--front.tpl.php simply allows you to create a different page template than the default page.tpl.php template. When drupal loads the homepage and there is a page--front.tpl.php it will laod that template instead.

If you want to check if you are on the homepage you can use the is_front variable. It would be best to use hook_boot in a custom module.

hook_boot(&$vars) {
  if($vars['is_front']) {
    // do your redirect
  }
}

You can use drupal_goto() to handle the redirect.


How to add a colon for Webform field labels? I know you can add colon in field.tpl.php for site wide content type node fields, but looks like it's not webform field related.

And webform doesn't have any webform-field.tpl.php type of templates to edit?

By default, webform fields has no colons e.g. Full Name label needs to be Full Name:.

I know I can add that with CSS, e.g.

.form-item label:after {
  content: ":";
}

But this won't work because I need colons to be printed in subnmitted email template too.

And emails dont support ::after ::before CSS I think, or there is complication with various web email providers, etc.

I know you can add a manually : when creating the label name and like that for every field (but its tiring if multipage long forms), but that's impractical for various reasons like e.g. https://www.drupal.org/node/1922550

With D7 webforms, you should be able to access the parts of the webform (rendered within webform-form.tpl.php) within a form alter:

function mymodule_form_alter( &$form, &$form_state, $form_id ) {}

If you have the devel module enabled, you can use it to print out the variables within the $form['submitted'] array - for example, to edit the title of a form component, you would use:

$form['submitted']['my_form_component']['#title'] = 'My new title';

To add a colon to the end of each component's attribute (i.e. to add a colon at the end of the #title attribute) you could set

$form['submitted']['my_form_component']['#title'] = $form['submitted']['my_form_component']['#title'] . ":";

If you use a variable instead of the specific 'my_form_component' name, you can set the form_alter function to loop over and add the ":" to the end of all component titles.

Small example here:
https://www.drupal.org/node/1558246


How do I override the title with the username? I am creating a view that will be visible under /user/%/blog, and I am trying to override the view's title with the username (e.g. kiamlaluno's blog), but the description of the field doesn't tell me what I can use to override the title.

I only get I can use Twig syntax, but that doesn't help much.

I used Content: Authored by as contextual filter. I also added author as relationship, but I didn't see any change.

How can I override the title with the name of the user authoring the nodes being shown from the view?

Make Fields your format

Alternatively: if you are using the rendered entity row plugin check the Force using fields in the Format | Settings.
In RELATIONSHIP, Add Content author

Checkmark ☑ Require relationship

In FIELDS, add Name

Checkmark ☑ Exclude from display
Uncheck ☐ Link to the user

For TITLE put {{ name }}'s blog

OR you could put it in your CONTEXTUAL FILTER; even though {{ name }} is not listed as a replacement pattern, it works (as long as you do step 1, 2, and 3).

Result

BONUS

If you want to capitalize the first letter of the user name use {{ name|capitalize }}'s blog.

You can also add a Rendered Entity as a field.


Flags to create mutual friends? I'm running a D7 system where users follow each other by using a 'follow' flag and then on user profile I've added a view to show all the users followed by a 'logged-in-user'.

What I'm struggling with is how do I generate a list of users who are followed by the friends of 'logged-in' user.

something like facebook 'mutual friends' functionality so 'logged-in' user get a list of users followed by the users he/she following.

You can do this by using Flag Friend module

  Flag Friend aims to be a lightweight friending module utilizing the
  excellent Flag module's API.

Or

Flag Follow

  This is a simple module which allows a user to view Heartbeat
  activities of his favorites/followed users. A user can add another
  user to his favorites list by just click on a 'Follow' button. It
  requires no approval to add a user to your favorites list.

or

You can do this by using Follow module.

  Follow adds sitewide and per user links that link to various social
  networking sites. The links reside in two blocks. The Follow Site
  block lists all the links for the site itself, and by default is
  visible on all pages. The Follow User block lists all the follow links
  for the user and is visible only on user profile pages.


How to count the number of consecutive days on which verified users accessed the website? My main problem is very similar to How to grant userpoints to users who perform a login 5 days consecutively?: I would like to keep track of the number of consecutive days on which verified users accessed the website. Therefore, I added an integer user field Consecutive days and created the following Rule that hooks into "visiting the website" (see How to hook into "visiting the website"?):

{ "rules_extra_consecutive_day_online" : {
    "LABEL" : "Extra consecutive day online",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-user:field-consecutive-days" ],
              "value" : "0"
            }
          },
          { "AND" : [
              { "data_is" : {
                  "data" : [ "site:current-user:last-access" ],
                  "op" : "\u003C",
                  "value" : "today midnight -1 second"
                }
              },
              { "data_is" : {
                  "data" : [ "site:current-user:last-access" ],
                  "op" : "\u003E",
                  "value" : "yesterday midnight"
                }
              }
            ]
          }
        ]
      }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "site:current-user:field-consecutive-days" ],
            "op" : "+",
            "input_2" : "1"
          },
          "PROVIDE" : { "result" : { "new_streak" : "New streak" } }
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-consecutive-days" ],
          "value" : [ "new-streak" ]
        }
      },
      { "schedule" : {
          "component" : "rules_reset_consecutive_days",
          "date" : "+2 days midnight",
          "param_user" : [ "site:current-user" ]
        }
      },
    ]
  }
}

The scheduled Rules component at the end of the Rule resets Consecutive days to 0 if necessary:

{ "rules_reset_consecutive_days" : {
    "LABEL" : "Reset consecutive days",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
    "IF" : [
      { "data_is" : {
          "data" : [ "user:last-access" ],
          "op" : "\u003C",
          "value" : "yesterday midnight -1 second"
        }
      }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "user:field-consecutive-days" ],
          "value" : "0"
        }
      }
    ]
  }
}

This seems to work relatively well, but there is a catch: the Last access field is not updated at every page request. As a result, users can increase their Consecutive days during a few minutes right after midnight by refreshing the page again and again.

How can I fix this issue? Should I override the Last access field at every page request or is there an alternative way to correctly update Consecutive days?

Overriding the built-in Last access field is not possible with Rules, so I added a new user Date field Last day online that stores a day, month and year. Recall that I had already created another user integer field Consecutive days. Here is the magical Rule:

{ "rules_extra_consecutive_day_online" : {
    "LABEL" : "Extra consecutive day online",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1", "3" : "3" } }
        }
      },
      { "OR" : [
          { "data_is" : { "data" : [ "site:current-user:field-consecutive-days" ], "value" : "0" } },
          { "data_is" : {
              "data" : [ "site:current-user:field-last-day-online" ],
              "value" : "yesterday midnight"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "site:current-user:field-consecutive-days" ],
            "op" : "+",
            "input_2" : "1"
          },
          "PROVIDE" : { "result" : { "new_consecutive_days" : "New consecutive days" } }
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-consecutive-days" ],
          "value" : [ "new-consecutive-days" ]
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-last-day-online" ],
          "value" : "today midnight"
        }
      },
      { "schedule" : {
          "component" : "rules_reset_consecutive_days",
          "date" : "+2 days midnight",
          "param_user" : [ "site:current-user" ]
        }
      }
    ]
  }
}

This is what the Rule does in words:

First, check that the current user is verified, and make sure the user's Consecutive days field is zero or the user's Last day online is yesterday.
If the above requirements are satisfied, then increase the Consecutive days, change the Last day online to today and schedule the component Reset consecutive days.

Underneath is an export of the mentioned Rules component. It resets the Consecutive days field if the Last day online field is less than yesterday (which means that the user was not online on at least one day).

{ "rules_reset_consecutive_days" : {
    "LABEL" : "Reset consecutive days",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
    "IF" : [
      { "data_is" : {
          "data" : [ "user:field-last-day-online" ],
          "op" : "\u003C",
          "value" : "yesterday midnight"
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "user:field-consecutive-days" ], "value" : "0" } }
    ]
  }
}


Custom content type and views field rendering I have a template views-view-fields--services.tpl.php

I don't want to iterate over the array of fields as I know which each of them are in this case.

I want to simply:

  <?php echo $row->title; ?>

  <?php echo $row->image; ?>

Doesn't appear to be a higher level template which might have this context of data???

UPDATED CODE SAMPLE:

views-view--services.tpl.php:

  <?php print $rows; ?>

views-view-unformatted--services.tpl.php:

<?php foreach ($rows as $id => $row): ?>
  <alex>
    <?php print $row; ?>
  </alex>
<?php endforeach; ?>

views-view-fields--services.tpl.php:

<?php foreach ($fields as $id => $field): ?>

  <?php /*print $field->class;*/ ?>
  <?php print $field->content; ?>

<?php endforeach; ?>

Results in:

    <alex>

    Entry #1

Briefly describe which problems we can help with.

  </alex>
  <alex>

    Entry #2

Quickly describe the services we offer or how our services can help?

  </alex>

Have a look at views-view-field.tpl.php. It' not used by default views, but available as a template override.

Edit: In views-view-fields.tpl.php you can also use $fields['my_field_name']->content; to access individual fields, but this will give you the fields default markup as well. The raw values can be accessed with $fields['my_field_name']->raw but those values must be proper sanitized before printing.


Proxy problems with Drupal 7.20 I have an installation of Drupal 7.20. I've entered the proxy settings in the default.settings.php but it's still unable to check on updates. A simple test with a dummy page which executes

http://updates.drupal.org/release-history/drupal/7.x?version=7.20')); ?>

Results in the following error message

  object(stdClass)#62 (2) { ["code"]=> int(-110) ["error"]=> string(20) "Connection timed out" }

Which leads me to believe the proxy settings are not being detected

As far as I'm aware, changing default.settings.php won't do anything. This file is only there to be copied into settings.php when the site is first installed - so if you change it after settings.php has been created it will do nothing at all.

You might try this module for proxy settings (though don't believe it when it claims to have a working version for D8)


Can we move a module from the directory "/modules" to the directory "/modules/contrib" without uninstalling it? We have a Drupal 8 application which has modules directly in the directory "/modules" on the file system. I want to move a contributed module from the directory "/modules" to the directory "/modules/contrib". Do I need to uninstall the module before doing it?

Are there any steps that need to be performed before and after moving the module?

As with most things, I suggested testing it out on a development/test site before trying on the live site. It's likely that the specific set of contribs and the libraries they use will affect the success of this operation.

How did you install the modules? Do you use a composer workflow?

In general, some paths stored in different places are going to be wrong. To fix that, you will need to edit those paths or have Drupal figure out the new paths. I believe doing a cache rebuild (e.g. drush cr) will fix that problem.


How to do result biasing in Apache Solr by node rating? I have a site with Drupal 7 with Apache Solr & rate module. In this site I have a content type that can be rated but search results are not being biased towards the better rated content.

If I go here: admin/config/search/apachesolr/env-solr/bias I found 3 kinds of biasing:

result biasing
type biasing
field biasing

None of these sections/tabs give me an option to bias the search results to the content that has a better rating.

I know I can relate a View with the search and order the content by rating, but that's not biasing exactly.

Any help would be appreciated. Thanks.

I think the Apache Solr Voting API module is just what you're looking for. It seems to have grown out of this issue. In limited testing I found that enabling it does add a bias setting for vote rankings: