How to clear varnish cache using drush? I'm on acquia cloud dev account im working in an acquia cloud environment and currently im clearing the varnish cache via the web interface. is there a drush command to clear varnish cache while using an acquia environment.

With Acquia Cloud API v1 Drush commands

On Acquia Could API v1 the command is ac-domain-purge. Here is a snippet from the drush help available from the Acquia box.

$ drush help ac-domain-purge

Purge a domain from the Varnish cache.

Arguments:
 domain              Domain name.

Options:
 --username          Acquia Cloud API username
 --password          Acquia Cloud API password
 --acapi-conf-path   Acquia Cloud API config files location. If not specified config will be loaded from $HOME/.drush
 --caller            Acquia Cloud API caller name. Default is the current username.
 --endpoint          Acquia Cloud API endpoint URL.
 --cainfo            Path to a file containing the SSL certificates needed to verify the ac-api-endpoint.
 --format            Format to output the object. Use "print_r" for print_r, "export" for var_export, and "json" for JSON. If not provided, the output is printed in a human-readable format.

Additionally, if you want to do this programmatically without drush, Acquia have an API endpoint for clearing the varnish cache.

Note that the drush commands only work with Acquia Cloud API version 1, which is EOL in 2020.

With Acquia Cloud API v2 requests

Acquia Cloud API v2 is json-api based, and the following API v1 to v2 migration document explains the URL request homologue that replaces each v1 drush command.  In this case:

The V1 drush API command ac-domain-purge becomes one of either:

POST /environments/{environmentId}/domains/actions/clear-varnish

To clear the Varnish cache for all domains used in an environment (eg both the internal appname.prod.acquia-sites.com domain, as well as your site's public domain.
POST /environments/{environmentId}/domains/{domain}/actions/clear-varnish

To clear the Varnish cache for a single specific domain.

See the Acquia Cloud API v2 documentation reference for additional information.


Customize Flag Ajax Message on Rules Trigger Greetings fellow Drupalers,

We're using Rules to listen for a flag trigger. And we wanted to present a custom mesage set in rules to the user after he triggered this as well. Since we're using the AJAX toggle, no message would be presented, however since there's no page load.

What's the best course of action for the desired funcionality? Or even which direction would you follow?

Best regards.

Rules don't support siuch feature. Change "Link type" to Normal link or Confirmation form, so you will got drupal messages from Rules.


How to display a menu items for a node but not for it's parent I have a page which I don't want to appear in a menu unless the user is already on that page or a child page underneath it.

For example on a shopping site, I would like to have a 'special offers' page positioned in the menu under the 'products' page, but it would only be visible if you're on the special offers page and not from the products page.

E.g. the standard menu

Home
    Products
    Contact us

When on the special offers page:

Home
    Products
         Special offers
    Contact us

Is there a way this effect can be achieved?

you could use Menu blocks and play a bit with the "Visibility settings"


Block user upon one webform submission I'm using Drupal 8, and I'm trying to block a user after submitting a certain webform. I have the below scenario:

Only authenticated user can submit and use the webform
Webform submission is limited to once per user
Users can save drafts of the webform and continue filling it later on
Rules action or otherwise should take place when the user has logged in

I tried to use Rules with rules_webform module but to no avail. The actions in rules are all there, but I need a condition to detect if the user has submitted the webform completely, not saved it as a draft only.

Appreciate any help given

Thanks

The best way to do this is to write your own webform handler and attach it to the webform's postSave() method. You can also experiment and try another method if needed from WebformHandlerBase.

Webform handlers are not documented well, but they should be because they are quite useful.

modules/custom/mymodule/src/Plugin/WebformHandler/MyModuleWebformHandler.php

<?php

namespace Drupal\mymodule\Plugin\WebformHandler;

use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform example handler.
 *
 * @WebformHandler(
 *   id = "mymodule_webform_handler",
 *   label = @Translation("My Module Webform Handler"),
 *   category = @Translation("My Module"),
 *   description = @Translation("Block users after submission"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */

class MyModuleWebformHandler extends WebformHandlerBase
{

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webformSubmission, $update = TRUE)
  {
    if (!$webformSubmission->isDraft()) {
      $webformSubmission->getOwner()->block();
    }
  }

}

After getting that setup, enable your new module (don't forget an info.yml file) and then edit your webform settings > handlers to add this to that particular form.


How can I make my menu children display horizontally below my main menu? So the dark blue menu is the main menu, and the light blue lower menu is the children of Help. How can I set my menu up so that it functions like this mockup?

Also, I don't want this to be a dropdown menu. I want the children to stay open while you are on either the parent page or on one of the child pages.

UPDATE:
I set it up the way you suggested, but instead of displaying the children in the sub-menu, it displayed the main menu and made the Help link a dropdown. Here is a pic of what happened.

There are two ways I know of to achieve this. The first is configuring Drupal core's primary and secondary links functionality and some theming, the second is the Menu Block module.
Primary and Secondary links core functionality + theming
If your theme utilizes the primary and secondary links variables you can configure the behavior you're looking for in the Menu Settings area.
From the Primary and Secondary Links documentation page:

Drupal also provides two default system menus called "Primary links" and "Secondary links". ... A powerful feature of this primary/secondary system is when you choose the same menu as the source for both theme variables. In this case, the two menus magically couple together, and the Secondary links shows you the second level of items from the menu for the page that you are on.

Here is a free Drupalize Me Video that shows the process in Drupal 6, it's very similar in Drupal 7.
You would set up your menu with the sub-pages as children of the main page links:

Home
News
Help

Basics
Content
Digital Dialog
Exams, etc

For this example I used the Main Menu that is default in core, but you can use any menu.

On the menu settings page (Admin > Structure > Menus > Settings or http://example.com/admin/structure/menu/settings) set both the 'Source for the Main links' and 'Source for the Secondary links' to your menu.

When you visit your Help page the secondary links displayed will be the children of the Help menu link. And the child links will stay open while you are on either the parent page or on one of the child pages. In the Bartik theme the secondary links are located in the top right of the page.

To match the layout of menus in your screenshot, you would most likely need to make theming adjustments as the Primary and Secondary links are not blocks configurable on the Admin > Structure > Blocks page. At the theme layer the variables are $main_menu and $secondary_menu.
Menu Block Module
If you foresee needing deeper levels of menus or want your menus to be in configurable blocks, or would just rather use a module than adjust your theme, there is the Menu Block module. From the project page:

[P]rovides configurable blocks of menu trees starting with any level of any menu. ... if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree.


Change a long text field to text I'm trying to convert a long-text field into a text-field. The only thing I found so far is the "field_config" table in the database. But any change there is only leading to errors. Do I have to change it somewhere else?

Thanks to Geoff. As my long-text never was bigger than the textfield size (255) I could use this solution with ease. I did it the following:
Created a new field "textfield"
Did a database action:

INSERT INTO newtable (newfields)
SELECT oldfields FROM oldtable

and then deleted the old field.


How to direct a specific role to a specific page This is related to this question:

How do I redirect a user role on login (Drupal 6)?

My biggest problem is that the only rules available as far as I can see are on user login, period, nothing for a specific role. How would I go about setting the redirect ONLY for certain user roles, when using rules?

In rules you could select "when a user logs in" and then as the action, select "custom php code" and fiddle with something along the lines of:

if (in_array('ROLE_TO_CHECK', array_values($account->roles))) {
  drupal_goto('PAGE_TO_GOTO');
}

ADDITION:

D'oh!

Rules can do this....

Select 'Add a new rule'
Name it whatever and select 'User has logged in' as the event
Add a condition: User has role(s)
Select the role you want
Add an action.
Select Page Redirect
Enter the path you want ADDITION:  check both Force Redirect and Immediate Issue check boxes
Save


Moving from custom CMS to Drupal and need to keep a myriad of old mod_rewrites I am moving content from an existing custom built CMS into Drupal 7. There is a host of mod_rewrite rules in place. These rules expand path names in the URL. For example, the rule below effectively expands

RewriteRule ^abc/?(.*)$     /alpha/beta/confusion/$1 [L,R]

Ideally we'd like put these rules inside of /etc/httpd/conf.d/old_redirects.conf. However, the clean URL rules are in .htaccess and are processed first.

Can I remove dependence on .htaccess and move these rules to /etc/httpd/conf/httpd.conf thereby allowing me to import the old_redirects.conf into the httpd.conf file before the Clean URL set of rewrites executes?

(I've referenced the following question How do I use .htaccess to trigger mod_rewrites before D7's Clean URLs take over? and Drupal 7 .htaccess redirects; and while good, they don't quite cover this from the perspective the a need.)

Moving effort to this question and answer Drupal 7 rewrite not using .htaccess. THis is what I'm trying to do anyhow is eliminate the .htaccess.
However, I discovered a module called htaccess

Htaccess is a module which autogenerates a Drupal root htaccess file based on your settings.
Drupal tries to provide a one size fits all htaccess for Apache webservers, but this goal is increasingly difficult. This module allows the webmaster to set specific options.

Added benefits is that for every drupal core update (in which drupal overwrites htaccess), I just re-deploy my set of rules which this module appends to the active .htaccess file. Additionally, my customization to htaccess are in the database and safe in scheduled backups in from Backup Migrate.


How to rename the views tabs in user accounts How do i rename the "view" tab in the user accounts? I want to rename it to Profile. Am using drupal 7 and the zen sub-theme. Any suggestions are welcome.

The Tab Tamer module gives you a user interface to do that.


How can I use $_SESSION in form handler drupal 8? I create a module that has form . I want send data from other form to this form and show them . How can I save previous data in my form and show new data ?

For example I send number 1 to my form and form show 1 , then send number 2 and form show 1 and 2 , and then send number 3 and my form show 1 and 2 and 3 .

Then I want send this data ( 1 and 2 and 3 and ... ) to other page with my form . how can I do this ?

My sender form :

<form action="/form" method="post">
   <input type="text" name="number" />
   <input type="submit" value="GO" />
</form>

The suberglobal $_SESSION still works in D8 and is used by core several times.

For a correct Drupal 8 way see this change record. It shows how you access the session variable through the request object. But it doesn't show how to get the request object.

So this is an example for accessing the session in a form handler:

use Symfony\Component\HttpFoundation\Request;

  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {

    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);
    $form['counter'] = ['#markup' => '<p>#' . $value . '</p>'];

In a controller or form you can pull the request from the route parameter stack by putting a typed parameter Request $request in the build method.

If you are in a procedural form function get the request from \Drupal:

$request = \Drupal::request();


Output a Menu with just needed classes for ul and li,. Nothing more Normally a drupal menu is being rendered like this:

xxx

yyy

zzz

I want it to be rendered as for a particular menu:

xxx

yyy

zzz

So I have the following in my template.php

function mymod_menu_tree__menu_about_us($variables) {
  return '
' . $variables['tree'] . '
';
}

function mymod_menu_link__menu_about_us(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $class = "";
  $classes_of_this_li = $element['#attributes']['class'];
  if (in_array($classes_of_this_li, 'active-trail')) {
    $class = 'active';
  }
  $output = l($element['#title'], $element['#href']);
  return '
' . $output . $sub_menu . "
\n";
}

The ul is rendered as i want it to be. But the active class for the li is never there. Something must be wrong with below part

if (in_array($classes_of_this_li, 'active-trail')) {
    $class = 'active';
  }

Any idea?

Try switching the parameters to in_array. in_array takes the needle first and the haystack (array) second.

Edit: unless that was a typo...

Edit

PHP Docs for in_array().

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

  Searches haystack for needle using loose comparison unless strict is
  set.


Give a specific user role the ability to give a user a role but not the 'administrator' role I have a set up using drupal 7 where, as a super administrator, I can add a user with a role of 'manager' (who can also add users to his shop) but I want to also give 'manager' the ability to specify if the user he wants to add will have either of the two simple roles (one to create/add data and one to view reports on sales only) say, 'sales-agent', 'sales-report'. Currently, in my setup, the manager can specify all roles including the 'administrator' role which I should have access only as a developer/super admin.

I have been looking around for modules to fit this but my time is running out.

Thanks for all your help. Drupal is great!

There is a perfect module for you - Role Delegation - and there is a stable 7.x release as well. Here is an excerpt about it from the module's project page:

... allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.


drupal7 custom form drop down show 0 I get a problem with my dropdown that shows "--select--","0","foods","meals" when I developing custom form with Drupal 7. The purpose of my dropdown is used to show "foods" and "meals" from category table. How does this "0" come from? I am hoping anyone suggestion to fix it.

function subcategory_form($form, &$form_state= NULL, $my_object= '', $subcategoryId, $name, $categoryId) {

     $category = db_select('category', 'cat')
    ->fields('cat')
    ->execute();

    $rows[] = array();
    while($data = $category->fetchAssoc())
    {
        $rows[$data['id']] = t($data['name']);
        dpm($rows);
    }

    $form['category_name'] = array(
    '#type' => 'select',
    '#title' => t('Category'),
    '#options' => $rows,
    '#default_value' =>t($categoryId),
    '#description' => t("Please select category."),
    '#required' => 'true'
  );

  return $form;
}

The code $rows[] = array(); will become a row in the array itself and will not just create an array as you probably want.

Change $rows[] = array(); to $rows = array();


Change article Status based on Workflow module I have Workflow set up properly. But when an article is created, it is set to Published automatically. It doesn't appear to the public though, unless the Workflow status is set to Live.

Is there a way to customize the status to be more specific (e.g. say "Pending Review" when the workflow is in Review status, then say "Published" when workflow is in Live)?

Thanks.

First, install the Rules module.

I would highly recommend watching the Rules video series at NodeOne by the incredibly talented Johan Falk.

With the Workflow module and the Rules module installed and configured we can create a rule that automatically publishes (or unpublished) content based on it's current workflow state.

To ensure our content is not published by default, we will need to change a few things.  Visit example.com/admin/structure/types (if clean URL's are enabled) and click edit next to the content type you're working with. Scroll to the "publishing options" and uncheck "Published" so new content is not publicly visible by default.

Next, create a new rule.  Available at example.com/admin/config/workflow/rules/reaction/add once the Rules module is installed and enabled.

Configure your new rule to react on the event: "Workflow State Has Changed" and click save.

Next, add a new condition.

Choose the "Check workflow transition" condition.

Configure which transition you wish to react on.  For example, if you have created the workflow states "Pending Approval" and "Published" you would choose "Pending Approval" under "Old Workflow State" and "Published" under new workflow state.

Now we can automatically trigger actions once Rules detects a workflow transition from "Pending approval" to "Published".  For example, we can trigger an email to editors, publish a node or just about anything else.

Next we need to add an action.

There are dozens of built in actions, and you can even add your own.  One that you may specifically be looking for though is "Publish content."

Rules and Workflow work very well together in this sense and will likely be able to do everything you need.

I hope this helps. If I misunderstood your question or if I got too off topic I'll try again. :)


How to develop a page which displays data from more than one content type/table how do I develop a view/page which displays the data like below.

I have the Image, blogger name ( this is my join field) , profile photo and details as one content type(table)
and Blogs are in different content type (table). Blogs content type has also blogger name.

I'm newbie to drupal and we are using Drupal 7.

Bloggers are not going thru user registration process and as admin's we enter the blogger details as bloggers content type (for those who enter more blogs).

Any help/hints on how to accomplish this

As mentioned by the commenters to your question, use the Views module. Here's some documentation to get you started.

In general, it is an enhanced query/list/menu builder, with which you can build most of your site's general pages, blocks and lists.

You can join multiple tables (or content types) in any way Drupal's structure lets you, and output the results as

a table of columns and rows (one record per row),
a grid with multi records per row,
short lists used to make menus,
and so much more.

Views should be in any newb tool chest of modules (opinion). It's invaluable for examining your site content, and in learning Drupal's content relationships (after you get beyond it's learning curve). It's now even in Drupal 8 core.


Create tpl file for webform I have created a form using webform module. Is there any way to create tpl file for this form?

webform-form-node_id.tpl.php is working fine. Here my problem is node_id will deffer on dev,qa and production etc server.

Please suggest so that a single tpl file can used for all instance.

You can use 'node--webform.tpl.php' template for all webform nodes.


What does the menu_masks variable do? When I was building a feature (as in Features), I noticed the menu_masks variable. I have read menu_get_ancestors() and _menu_router_save() but I still don't understand what it does.

On a more practical level: When I'm building a feature which defines the menu's for my site, should I export the menu_masks variable too?

menu_masks is a Drupal variable used to find the possible ancestors of a menu item. It contains an array of values that are calculated from the paths defined from modules; each values is essentially a binary number where the digit is 1 when the path part doesn't contain a placeholder, and 0 when it contains a placeholder. For example, the number for node/%node/edit is 9 (101 in base 2), while the number for admin/structure/types/manage/%comment_node_type/comment/fields is 123 (1111011 in base 2).
The reason why numbers are used is avoid comparing strings; plus those numbers are easily sorted in a way that a number matching a path without placeholders is placed before a number matching a path with one or more placeholders. (The number for %/%/% would be 0, while the number for admin/appearance/list is 13.)

Notice that menu_get_ancestors() doesn't return the ancestors of the path passed as argument, but the possible ancestors. Passing array('node', '12', 'edit') to the function, I would get the an array containing the following values, as result.

node/12/edit
node/12/%
node/%/edit
node/12
node/%
node

In my test site, only the third, the fifth, and the sixth are paths defined by the modules I installed.

You don't need to export the menu_masks variable: Its content is very specific for the site and it is re-calculated when menu_rebuild() is called.
Drupal is still able to work correctly even in the case menu_rebuild() is not yet called, and that Drupal variable has not been set. You should not notice any performance issue, but if that would be the case, you can call menu_rebuild() or force Drupal to call that function; if you have the Devel module installed, you can easily force Drupal to rebuild its menus.


Adding class to nested UL in menu I'm creating my menu using view along with Bootstrap to create a mega menu style navigation.
I'm having a problem with the nav showing expanded at times when you come to the site and or refresh. not all the time but more than I'd like.
I am using: _menu_link like such:
function MYTHEME_menu_link(array $vars) {
  if ( $vars['element']['#theme'] == 'menu_link__user_menu' ) {
    $vars['element']['#attributes']['class'][] = '';
  }
  elseif ( $vars['element']['#theme'] == 'menu_link__main_menu' ) {
    $vars['element']['#attributes']['class'][] = 'dropdown mm-menu-fw';
    $vars['element']['#localized_options']['attributes']['class'][] = 'url-link';
  }
  return theme_menu_link($vars);
}

This gives me the following HTML markup.

    MY LINK

You might get into the sub menu element with the ['#below'] object. not tested.

<?php

   /**
    * Implements theme_menu_link__[MENU NAME].
    */
   function YOURTHEME_menu_link__main_menu(&$variables) {

        $element = $variables['element'];
        $sub_menu = '';

        $element['#attributes']['class'][] = 'dropdown mm-menu-fw';
        $element['#localized_options']['attributes']['class'][] = 'url-link';

        if ($element['#below'])
        {
         $sub_menu = $element['#below']['#attributes']['class'][]= 'NEED-TO-ADD-CLASS';
         drupal_render($sub_menu);
        }

       $output = l($element['#title'], $element['#href'], $element['#localized_options']);

       return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";

 }
?>


How do I print the title in page.tpl.twig? I am trying to display title and other fields in page.tpl.twig. {{ title }} doesn't display the title, but {{ page.content }} displays all the content.

How do I print the title in page.tpl.twig?

For title page-title.html.twig can be added in page.html.twig title of the page is not explicitly available by default.


Changing navigation depending on authentication status How can I change my menu items depending on whether the user is logged in or not? For example, I would like my secondary navigation to have a "sign in" link if the user isn't authenticated and "log out" if the user is authenticated.

Thanks!
Jane

Check out Menu per Role Module. This module allows you to restrict access to menu items based on user roles. Once enabled, there will be a new fieldset that allows you to restrict access by role. The fieldset also appears in the node edit form.


Custom tpl.php for custom content types rendered through another tpl.php I have a custom module which displays multiple content types in tabs. My module uses a custom tpl.php which renders the tabs and the contents(of multiple types).

The challenge is to have custom tpl.php for each content types I render. The theme file node--TYPE.tpl.php works when I directly hit a node of a TYPE. But it is not used when I rendered the node content using the below code,

    $node = node_load($aTab['nid']);
    $view = node_view($node, 'full');
    $rendered = drupal_render($view);
    print_r($rendered);

What is the suggestion to have my module to render each content types using their custom theme file.

You shouldn't be printing it with print_r(), just try print.

$node = node_load($aTab['nid']);
$view = node_view($node, 'full');
print drupal_render($view);


Reduce latency in loading a page in Drupal 6 I have activated cache in Drupal, and the Devel module.
The total time in all queries is less than one second, but the latency is 4.34 seconds.

Can anyone explain the latency? What happens during the latency time?

I am using IIS, Php 5.25, Wincache, and MyIsam.

The database query time is just the database interaction, don't forget that PHP takes time to process its own logic.

If the majority of the page load time is outside the database you should install xhprof to actually profile your PHP functions individually to see where the damage is being done.

Basic tips for improving PHP performance - install a module like Cache Router to take caching out of the database and put it somewhere else like in memory or the file system.

Install APC or similar on your server to improve PHP performance.

Cache object load calls wherever possible, this is handled much more easily in D7 thanks to the Entity Cache module, but it is possible to do in D6. Persistent caching of node_load() can really be your friend.

Avoid configuring your site to load a lot of tpl.php files on page loads - "fields" rendering mode in Views can do this.

Avoid "slow" core functions - some taxonomy functions can be very slow in D6, be aware that user_load() is not even statically cached so it can be expensive if you call it a lot.

Avoid eval()'d code as it runs much slower as well as being a potential security risk - This is anything using the PHP input filter.

Disable all "UI" modules. If you're running a large number of modules it is very easy for one of them to be doing more than it "should" be, so you want to start whittling the total number down if possible. Unfortunately, modules smart enough to split their logic into "core" and "UI" often aren't the culprits for performance problems but it's worth doing anyway since it is so easy to do.

If it isn't PHP or the database that is slowing things down, your server could be under too much load and doesn't have the processing power to keep up with incoming requests. If you can process X number of requests per second and have 2*X incoming requests then your pages will load about 1/2 as fast.

Make sure you have enough RAM to run your site comfortably, if your server starts "swapping" things can degrade very quickly.

Page Caching does not help at all for authenticated traffic, only anonymous traffic. Make sure that your block caching settings are correct for every custom block that you've created. It might be worth trying the auth cache module.

Unfortunately there are many, many ways to slow a site down so these tips are not really comprehensive. I used to have a bookmark to "56 tips" that you could basically review your site with and at least triple the speed but it was pulled offline at some point in the past couple of years :(

Also, you might want to try swapping to innoDB as the row-level locking can speed things up drastically over myISAM in some cases.


How do I update existing Nodes field through Import without having to delete all content and re-importing everything? We built an application for a client of ours to track appeals and cases of a legal case. There are currently over 2,000 entries in the system. After we built the app, it was requested we add four more fields for allocation amounts. We added the fields, but he would like to now import the content (which he has already put in a csv format, in proper order for an import).

We originally used Node Import module to import all of the content (I believe 1700 of the 2000 entries were entered through the initial import). However now that we have added extra fields, Node import does not have functionality to import into empty fields, mainly I believe because it does not have the ability to identiy unique identifiers and see that an entry already exists for that Node title.

Node Import Update module, from what I read in the description of the module should be able to do it. However after installing this module and doing the import again, it does not work, instead it creates duplicative entries.

In Node Import Update module's known issues page (http://drupal.org/node/813978), it says one needs to go in and update the node type you want to import. I do not know what value it is asking for here. The name of the Content Type in which the fields are in? This is what I currently have it set to. I know Title is correct - not sure about the node type:

Set custom data
     * These should/could be defined in admin
     *
     */
    // Node title as unique identifier
    //$IMPORT_UNIQUE_ID_NAME   = 'title';               // Import field that holds the unique identifier
    //$IMPORT_UNIQUE_ID_IS_CCK = FALSE;                 // Is the identifier a CCK field?

// CCK field as unique identifier
$IMPORT_UNIQUE_ID_NAME   = 'title';  // Import field that holds the unique identifier
$IMPORT_UNIQUE_ID_IS_CCK = FALSE;    // Is the identifier a CCK field?

$IMPORT_NTYPE            = 'node';   // Node type to be imported
$IMPORT_UPDATE_DATETIME  = TRUE;        // Settting: update date/time value?

Sorry if it is long winded - however I wanted to ensure I was complete in describing the issue as I really need to get this wrapped up for my client. Thanks!!!

I'm pretty sure you'll be happy with the excellent Feeds module, which does this every day for thousands of sites. More advanced/customizable techniques are available with Migrate module, which always requires code, but gives enormous flexibility. Both will allow you to update existing nodes. Had you used them for your initial import, you'd be done now. I think you still may be able to use them as long as you have a unique identifier on your existing nodes.


How do Pressflow Drupal sites handle user Cookies? Is this something handled by Drupal? What PHP, Apache, Varnish settings affect cookies?

Additionally, what's the difference in cookie handling between plain-vanilla Drupal and Pressflow?

I was seeing that in drupal_session_commit() boostrap.inc calls session_destroy():

  session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

  In order to kill the session altogether, like to log the user out, the session ID must also be unset. If a cookie is used to propagate the session ID (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

Apparently in Pressflow drupal_session_commit() gets called on every page like this:

// Perform end-of-request tasks on every page.
drupal_page_footer(), common.inc
    // Write the session, and open one if needed.
    drupal_session_commit(), bootstrap.inc
        // If our user is anonymous, Pressflow "Destroys empty anonymous sessions"
        // Destroy all data registered to a session
        session_destroy();
            // Called by PHP session handling with the PHP session ID to end a user's session.
            sess_destroy_sid($sid), session.inc

What implications, if any, does this have for user tracking in software like Omniture and Google Analytics?

See related post to cookies here: https://stackoverflow.com/questions/871283/how-do-tracking-cookies-work

Link to Pressflow documentation.

Cookies/sessions are handled by both Drupal and PHP. Drupal register some functions that PHP will call, when certain things need to happen, like destroying a users session. PHP handles most of the basic stuff and Drupal override some of it, store users sessions in the database.

I'm not familiar with Omniture but if it's anything like GA, a users session/cookie wont effect tracking at all. Cookies are used to identify the user, so they don't have to type in their username/password at every page. Without cookies, Drupal wouldn't be able to tell the users apart and would need some other form of identification, like a login for every new page load.

This is why, some people try to steal cookies, as that is the same as having the user log in and leave the computer, given the thief full access.


How to get newly created node ID after Feeds importing? I programmatically executed feeds importer to create new nodes. I have to set some fields programmatically after importing. I check the hooks in feeds.api.php, and didn't find a solution. Is there any way that I can get the newly created node ID by the importer?
Thanks

I found the solution. Use $entity NOT $entity_id in hook_feeds_after_save.


Administrator notification on user registration Administrator is not notified when a user registers on my D7 site, while the registrants do receive a message. On the D6 version of the site it worked. Here's the setup:

Drupal 7.10
User registration is upon admin approval.
Contact users works.

I can't find a flag anywhere to turn on notification to administrator. Google search and search on this site has not turned up a solution. Is this capability in core, how do I turn it on. Do I have to use additional module?

Thanks.

First, go to /admin/config/system/actions. In the section "Create an advanced action", choose "send an email" and click on "create". It takes you to a page where you need to enter a recipients email address, (enter the Administrator's email address here), subject and message. Click Save.

Second, go to /admin/modules and enable the Trigger module.

Third, go to /admin/structure/trigger/user. In the Section "Trigger: After creating a new user account" Choose "Send e-mail" in the select box. Click Assign.

Example Message:

A user has created an account.

Details:
 - Username: [user:name]
 - Email: [user:mail]
 - Time: [user:created:long]

Activate their account by going here: [user:edit-url]


how to upgrade drupal 7 site to universal analytics what happens if a user upgrades to universal analytics on their google analytics admin page, yet we are still using the drupal 1.4 module, which according to the documentation does not support universal analytics

I found out that there will be no effect in the meantime on the existing google analytics behaviour, just that the new UA functionality will not be available.


To show content as links I want to display 10 contents of same content type as links in a single view. Is it possible? How?

views is the module you are looking for. It will allow you to list your contents filtered by content type as links. Look at this tutorial before you start.


How to output a custom field in my template? In my content type I have created a custom field field_image_style which is a list (text).

How can I print its value in node.tpl.php?

print render($content['field_image_style']);

This doesn't work?

(What I actually want to achieve later is to use the selection the user made in field_image_style to apply a specific image style to the images of the content element.)

EDIT: Somehow the Zen theme was the reason. With my own Stark based theme it works like it's supposed to.

This is a perfect use case for the Field Formatter CSS Class module.

After adding a text list, radio, or taxonomy field to a content type, you then put the field on the view mode you would like for the class to be on. Use the CSS Class formatter and what level you would like to apply the class (generally node is fine), then you can add your CSS rules for whatever you want.

For example, you can change the individual caption background color on slides in a rotator, or specific stylings per post in a blog feed.


Move content from field to field collection I'm working on a site where a current content type has six image fields, six title fields & six content fields. One field from each (one image, one title & one content) all make up one group, so in total there are six groups of these.

Is it possible to move these into a field collection? I just think it'd be tidier, make more sense & make it easier to maintain.

Also if this is possible, not only how do I do it but is it even wise to move content from a 'normal' field to a field collection like this?

You can do it with 3 step

In your content type, creat new field collection
Write one module, use function hook_node_presave(). In this function, you can copy data from old fields to new field collections.
Go to page admin/content. Select your content type. Select all node. In tab UPDATE OPTIONS chose Publish selected content and submit. This action to do run code your module write in step 2.


Ternary operator not evaluating checkbox values I am using Drupal 7. I have created a form using the Form API, in which I defined several checkboxes. The form sends its contents in an email and this works fine at the moment as long as I simply output the values of the fields, with the checkboxes outputting the value if checked (e.g. Elderly) and 0 if not. In making up the body of the email I want the zeros to be omitted and only the values of the checked boxes to appear. I have tried to achieve this by using a shorthand ternary operator to include some html if the box is checked and not if not. I can't get this to work. Here's how I've defined the checkboxes in the form itself:

$hometypes = array(
            'Elderly' => t('Elderly'),
            'Disabled' => t('Disabled'),
            'Council tenant' => t('Council tenant'),
            'Home owner' => t('Home owner')
            );

        $form['personaldetails']['survey']=array(
            '#type'=>'checkboxes',
            '#title'=>t('Please indicate your situation by ticking the appropriate boxes'),
            '#description'=>t('You can tick a box by clicking on it once'),
            '#options'=>$hometypes
            );

Here's where I set up the variable $elderly:

$elderly = $form_state['values']['survey']['Elderly'];

And here's the section of the submit function that is not working:

  .($elderly == 'Elderly' ? 'Elderly

 	 ' : '').

This returns the 'True' value regardless of whether the box is checked or not. If I change it to be:

  .($elderly <> 0 ? 'Elderly

 	 ' : '').

it returns the 'False' value regardless of whether the box is checked or not.

This may be a bit of a newbie question, but that's because I'm a bit of a newbie! Any help gratefully received.

Solved it!

I redefined the keys for my checkboxes as values rather than strings. Like so:

$hometypes = array(
        1 => t('Elderly'),
        2 => t('Disabled'),
        3 => t('Council tenant'),
        4 => t('Home owner')
        );

remembering to change this:

$elderly = $form_state['values']['survey'][1];

which means that this:

($elderly == 1 ? 'Elderly

 	 ' : '')

works perfectly.


Is there a way sort View by results of "Options" Rate/Voting API widget? I'm using the Rate module to allow voting on whether or not a given node is "Helpful" or "Unhelpful". I have a view with all nodes of this type, and the view includes a field for the Rate widget. I am having no problems displaying the widget itself, and the voting is working perfectly. However, I cannot for the life of me get any type of sorting functionality to work.

I've tried all of the sort types having to do with Vote, and all of them sort the nodes in no relevant order. It seems that the problem arises because I am using the value-type of "Options", and suggestions that I have found seem to require the value-type to be "Points". However, I'd much rather have user select between "Helpful" and "Unhelpful" than to use a thumbs up/down or +/- system of voting.

Does anybody know how I could sort by "most helpful" and "most unhelpful" and keep the value-type of "Options"?

You have to add a relationship Content: Vote Results with proper data filters

Value-type: Points
Vote-tag: Your rate widget vote tag
Aggregation-function: Number of vote

Then in views sort criteria add

(Vote results) Vote results: Value (desc/asc)


How do I write an additional field formatter for an existing field I would like to write a new field formatter for an existing field type. I don't want to replace any existing formatters but offer a new option.

Or am I better off using a theme_preprocess_field() to do minor alterations? But this seems to be harder to maintain and I'd like to keep my content editors options open (and in the GUI).

Can someone point me to an example of the proper way to do this?

Personally I'd say a formatter is the better solution.

There are only two hooks you need to implement:

hook_field_formatter_info()
hook_field_formatter_view()

For example:

function MYMODULE_field_formatter_info() {
  return array(
    'my_formatter' => array(
      'label' => t('My formatter'),
      // The important bit...
      'field types' => array('field_type'),
    ),
  );
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'my_formatter') {
    foreach ($items as $delta => $item) {
      $element[$delta] = array('#markup' => $item['value']);
    }
  }

  return $element;
}

For a more in-depth look, download the Examples module and look at field_example - there's plenty of code and documentation there to get you on your way.


How do I get the user ID for the currently logged-in user? I want to get current user object (user information) in Drupal 8.

I know in Drupal 7 there was a global $user variable; I want to know how I can get current user object in Drupal 8.

$user = \Drupal::currentUser();

See the Drupal class. There are a lot of helper methods; most of them are shortcuts for services, so you don't have to call \Drupal::service() directly.

Note that the current user is not the user entity, it is just user proxy. You can get some basic information from it but fields or other entity-specific logic is not present. To access the user entity you have to load it manually:

$user = User::load(\Drupal::currentUser()->id());

Unfortunately there is no direct method like \Drupal::currentUser()->getEntity() :(


Programatically Update a Module Is it possible to programatically update a module in Drupal 6? In otherwords, run an update as if running from update.php. I assume so. I looked at update.php and saw the function

update_do_once($module, $version, &$context);

I can't say I understand what $context is, and I can't get this working even after doing a full bootstrap. I get no errors, just nothing happens.

Has anyone every done this before?


Keep menu open for custom content entities I am writing modules that define content entities in Drupal 8. The Drupal console creates the menu items for the list builder. I would like the menu to stay open (having the menu-item--active-trail class) when I access the view or edit form page of, say, the content entity with id 4.

The breadcrumb navigation works perfectly out of the box, but the menu is completely closed for the content entity with id 4.

I am ok with writing a Menu Plugin or using a contributed module.

My solution turned out to be the contributed module Menu Trail By Path: because I can fine-tune the actual URLs in all of my entities' YAML files, I can define the hierarchy easily.


Is it OK to remove field values or revisions by deleting individual lines from the field table in the database? I have been testing my site (with revisions enabled) for several days now and I have noticed that my field related database tables are filling up with revision info.  Can I simply delete these line items from the field table or are there other entries that I need to be aware of?

It is better to Use the Node Revision Delete module to delete and manage your revisions.

  The Node Revision Delete module allows you to manage the revisions of the Node according to your choice. It helps you to keep the specific number of revisions for the node. This module provides you the flexibility for applying the revision delete for the specific content type and run it on the specific time. You can manage your settings from the Node Revision Delete Administration Page.


How to add reviews to the book I've two content-types "Book" & "Review". I want users of role reviewers to add reviews to any book they desire.

How I did it?:

I've added entity-reference to Book from Review with (auto-complete) widget. This just allows reviewers to add review node and select book from auto-complete. Who does that way? I'm not satisfied with it.

How I want it:

I've a page for every book /book-details/title-of-the-book, where I want to provide a link/button which says Add Review and then it should show them the fields of Review content-type and reviewer fills it and submits. His review is submitted. and the same page shows list of all reviews for that book.

How to achieve this in drupal-7?

Add review content type form while viewing book content type is viewed by using hook_nodeapi().

Create one field on review content type(node reference of book node).
Add that node_form in book content type view with $form_state of the book node id.
Create a view for review list with a filter of book content type and use this block under book content type view.


How to hide the text format field set using css? I followed several recommendations and decided to go with using CSS to hide the text format. I don't want to use another module to do something minor like this. Just want to hide text format for this particular form.

When I look at source I see:

<fieldset class ="filter-wrapper form-wrapper" id="edit-conditions-format">
blah blah blah
</fieldset>

Then on top of my form render function I do:

drupal_add_css('
        #edit-conditions-format {
            display: none;
        } ',
      array('group' => CSS_THEME, 'type' => 'inline'));

I have cleared cache and the text format is still available. Any tips?

Your code is correct. Just add it to a custom module, and it will work. Most likely it doesn't work because the admin theme is not the same as your front end theme.

Your module would take as little as this:

YOUR_MODULE.info:

name = Your module.
description = Description.
package = Custom
core = 7.x
version = 7.x-1.0

YOUR_MODULE.module:

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'ID_OF_THE_FORM_YOU_WANT_TO_ALTER') {
    drupal_add_css('
      #edit-conditions-format {
          display: none;
      } ',
    array('group' => CSS_THEME, 'type' => 'inline'));
  }
}

That's it. You can fetch the empty boilerplate here or if you want to do it properly, have a main custom module where you do all the extra customizations. You can have a look at mine here.

Or you could create a child theme of the admin theme, but that will likely take as much effort as creating a custom module.


After enabling Calendar the Next/Prev buttons are off to the side How can I get these two buttons in a better place to make them useful?  Currently they reside overlapping the sidebar and calendar almost right in the middle of it.  I've looked at documentation and I can't figure it out. I'm using drupal 7.  Thanks

CSS is your friend.  Find the id and/or class of these offending buttons and override their positioning in your theme.


I want to use this font family: PTSansRegular I want to use this font family: PTSansRegular for my website.

Do I have to instal the module: @font-your-face ?

or is there another easier way to insal it for my site?

(I found it here http://www.afontz.com/font/paratype/pt-sans/regular/)
(i'm using boilerplate subtheme)

thanks alot!

You have two options, doing it using a module such as @font-your-face or just simply doing it without a module.

Download the font from the site you specified above.
Open the CSS from the folder and check the different styles of fonts.
Copy the font folder to the CSS folder in your theme's directory.
Open .info file of your Drupal theme and add the stylesheet link from
the font folder.
Use the font-family of the currenlyt downloaded font in your
stylesheet.
Clear your cache.


RSS item list in block with dates I need a module which can fetch rss titles + publish dates and show them in a block/teaser. I tried aggregator and it does some of the job, but you cannot show publish dates in the list. The "read more" link should go to the original RSS or custom URL. It is important that all links link to the original url in the RSS and not to any view in drupal. Any suggestions for modules or other solutions?

If you're just trying to display an RSS feed (rather that import the entries into your site's actual database and then show in a view), then I would use Feedburner, which will help you get the html code to publish any RSS feed.

Get a Feedburner account
Create a new feed to manage, using the feed's URL on the front page screen
Under the 'Publicize' tab, go to 'BuzzBoost' and activate that service at the bottom of the page
Once it's activated, you can get the embed code.  Just paste that code into a brand new block, and place the block whereever you want!

p.s. Further down that same page (the Publicize -> BuzzBoost page, I just cut off my screenshot too early), you can customize the feeds settings, such as should you display a date, and if so in what format, and how many characters of the post teaser to display, etc.  Play around with them to get the feed listing you want!


how to define ECK form url I am using ECK
I create one form through  entity->bundle->feedbackform->managedfield
my form is created, but how to get form path,
current path is of my feedback form is:-
admin/structure/entity-type/feedbackform/feedbackform/add
but this path is not for anonymous user. i want to show my form to anonymous user with some simple path

Assuming you have a module called 'helloworld', and entity type called 'vechile' and a bundle called 'car'.Here is some code that should do the trick.

/**
 * Implements hook_menu().
 */
function helloworld_menu(){
$items['feedbackform'] = array(
'page callback' => 'example_my_eck_form_page',
'access arguments' => array('Access feedback form'),// permission
'type' => MENU_CALLBACK,
);
return $items;
}

function example_my_eck_form_page(){
   module_load_include('inc', 'eck', 'eck.entity');
   $bundle_name='car';
   return eck__entity__add('vechile', $bundle_name);
}

function helloworld_permission() {
   return array(
    'Access feedback form' => array(
      'title' => t('Access feedback form'),
    )
  );
}

Access feedback form is a custom permission so you still would have to give that permission to the  users from admin to be able to access the path.


Custom drupal module does not appear on the extend page I have created a custom module, yet it does not appear on the extend page.
I have my_new_block.info.yml file in modules/custom/my_new_block/:

name: My New Block
description: Create own blocks.
package: Garage

type: module
core: 8.x

dependencies:
  - block

In addition, when I try to install any drupal module with composer, it also is not recognised in the extend page.
What can be wrong?

There was a preceding issue with installation, I had several drupal projects under Projects folder, the newer project tried to access modules in the directory of the older one. Probably, the paths have somehow mixed, leading to the problems with modules installation and database connection(it was not described in a settings.php file). After the disabling of the previous projects and reinstallation of the current one, everything has been working properly.


Private File System and Externally Modified Files I have a D7 site that includes a few hundred nodes that have PDF attachments that use the core file field and the private file system. The site uses a custom module to dynamically watermark these PDFs and we're going through an update that requires each PDF to be updated to use a new layout.

In order to minimize downtime, what I was hoping to do was pull the site to a development environment, directly edit the PDFs that are stored in the private file system and then push the updated files and changes to the watermarking feature back to production.

All seemed like a good plan, but I'm finding that Drupal will no longer serve the updated files after they've been modified. No error messages in the logs (Drupal, PHP or server) and the site just times out when you request new files from /system/files/...

I haven't been able to find any documentation or relevant issues on the subject, but I'm wondering if Drupal's private file system is failing to deliver the file due to changes to the timestamp or file size?

Has anyone run into this before? I'm hoping there's a workaround that does not require that we update hundreds of nodes by editing and manually re-uploading each file one at a time.

Thanks much!

The files won't be served if the entry in the file_managed table for that file does not have the correct filesize.


Is there any performance implications in calling a view programmatically and set necessary filters? I have a view that list some items depending on the current node loaded. I also want to add few exposed filters to the view. The exposed filters cannot be shown to users directly. I want to provide a separate set of filters (to display) for users and based on what user selected, I want to set one or more filters of the view.

For example: I want an option for user to show only nodes that are not older than 7 days, 14 days etc so I will provide a list with All, 7 days, 14 days etc and when user select any of these, I want to set the exposed filter for node created time and with the calculated value - the date 7 days or 14 days or so from now.

There are several filters like this - ie based on what the user selected, we need to apply different filters in view.

To implement this, I plan to implement a block, in which I can programmatically call a view

$my_view_name = 'the_view';
$my_display_name = 'block';
$my_view = views_get_view($my_view_name);
$my_view->set_display($my_display_name);

if ($option == FIRST_OPTION) {
  $my_view->exposed_input['filter1'] = $option1_calculated_value1;
  $my_view->exposed_input['filter2'] = $option1_calculated_value2;
}
else {
  $my_view->exposed_input['filter1'] = $option2_calculated_value1;
  $my_view->exposed_input['filter2'] = $option2_calculated_value2;
  $my_view->exposed_input['filter3'] = $option2_calculated_value3;
}

$my_view->execute();
unset($my_view->exposed_widgets);
return $my_view->preview();

Is there any problem in using this method? Is there any other way to do this? Is there any performance implications in using this method? Will views caching etc work in this case? I use Drupal 7 and Views 7.x-3.7

Definitely not an issue unless you overload the view (but you can do that with the UI also - so no difference there).

On our production architecture we have views UI disabled and all the views are in code under version control however we also have a content team that needs to build 'lightweight views' that pull data from a product catalog and displays it in a particular way. Unfortunately we don't want them running direct SQL or using views UI as they don't completely understand what it all means so we just programmatically create these views and expose a UI to them that they understand. Things like:

What design they want on it
How they want the sorting of the dataset
Whether they need 'no results' text
etc.

Some caveats to doing more complex versions of this are:

Looking out for timing issues. I.e. not having an option available at that call point
Ensuring the correct structure is used. Example: $view->use_ajax vs $view->display[$dispay_id]->filters['use_ajax'].

Neither the less, it is all definitely possible and scales without issues.


How to check in a rule if the data from a field collection has changed? I want to add a rule (using the Rules module) for printing a message after changing a field in a field collection.

The field collection consists of the following three fields:

Reference to Version (type: Entity reference)
Related Entities (type: Term reference)
Related Properties (type: Term reference)

What I am using for Rule (I have attached a print screen from the rule

EVENT: "Before saving content of type X"

CONDITIONS: Here I am using NOT Data comparison, but it is useless...

ACTION:"Show a message on the site"

How can I check if the data from a field collection has changed?

Processing field collections is always fun, and even more fun to do so with the Rules module. My favorite sample to refer to (for actually doing so) is contained in part 1 of my answer to "How to iterate over all field collection items in an eMail body using Rules?".

Have a look at comment #2 of the issue about "Field Collection does not work with Rules' 'node-unchanged' option", which states:

  ... For example:

  Create a content type with a field collection that contains an integer field.
  Create an "After updating existing content" rule for that content type.
  Add a "Show a message on the site" action that prints the integer field attached to node:field-collection and node-unchanged:field-collection.

  The printed value for node-unchanged is wrong. It shows the changed value.

So far the bad news, read on in comment nr 3 of that same issue, which is like so:

  The reason that node-unchanged and node both show the same (new) field collection values is that the node stores a reference to the field collection. The field collection is a separate entity. Changes to it can be caught by the rules events for field collections. The "after updating an existing field collection item" event gives the correct unchanged and new values.

With this explanation in mind, have a look at this rule (in Rules export format):

{ "rules_verify_updates_to_field_collection_items" : {
    "LABEL" : "Verify updates to field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "field_collection" ],
    "ON" : { "field_collection_item_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "field-collection-item" ], "field" : "field_reviewers" } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "field-collection-item-unchanged:field-reviewers" ] },
          "ITEM" : { "previous_reviewer" : "Previous reviewer" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "field-collection-item:field-reviewers" ],
                      "item" : [ "previous-reviewer" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Reviewer [previous-reviewer:name] was removed from the list of reviewers in field collection item with id [field-collection-item:item-id]." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "field-collection-item:field-reviewers" ] },
          "ITEM" : { "current_reviewer" : "Current reviewer" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "field-collection-item-unchanged:field-reviewers" ],
                      "item" : [ "current-reviewer" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Reviewer [current-reviewer:name] was added to the list of reviewers in field collection item with id [field-collection-item:item-id]." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

Some details about the above rule:

Rules Event: After updating an existing field collection item. Note that this is different from the Rules Event you're using!
Rules Condition: Entity has field, for a field with machine name field_reviewers, which is a multi value entity reference field (to users).
Rules Actions:

The 1st loop (related to field-collection-item-unchanged:field-reviewers), will discover all removed reviewers.
The 2nd loop (related to field-collection-item:field-reviewers), will discover all added reviewers.

Obviously, for this rule to work you'll also need the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?").

Here is a demo of this rule (= some Drupal messages shown after I added/removed some user references in 2 field collection items (with id = 5 and 6):

Reviewer Hillary.Trump was removed from the list of reviewers in field collection item with id 5.
Reviewer UltraBob was added to the list of reviewers in field collection item with id 5.
Reviewer Donald.Clinton was removed from the list of reviewers in field collection item with id 6.
Reviewer Dries.Buytaert was added to the list of reviewers in field collection item with id 6.
Reviewer Pierre.Vriens was added to the list of reviewers in field collection item with id 6.

To finish: you're question may require a slightly different set of Rules Conditions, i.e. since you want to compare some field before the update (= unchanged) versus after the update. But if you're using the same Rules Event and Rule Condition (= Entity has field, for your field collection field), you should be able to perform such comparisons also.


How to use data in fields from one node to create a new node of different content type? I have a content type called "Submit a photo" where anonymous users can upload a photo alongside with their name, email and short description. And I have another content type where an admin uploads images and publishes them as "Looks", and Looks are more complicated content type, with image tags, categories ...

Than I have a view which lists all of the submitted images so that an editor can pick and create new node "Look" using existing fields. But I'm looking for a way to somehow pre populate fields in that new content type with fields of "Submit a photo".

So editors can review all the images that are submitted by anonymous users. If they like one, they click “Add new Look” or something like that, which opens a new “Add Look” form using that image.

Should I look at nodereference or something like that?

Have a look at the Node_convert module. From it's project page:

  adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability to convert the node from its current node type to another node type. The module provides the means to transfer all the field values of the current node type into fields on the destination node type, or discard them.

I'm using Node_convert already for long time, works great. It allows for implementing a lifecycle (or workflow?) to start from a node that is only just something like an idea (or suggestion, question, issue, abstract, etc). So that would be like your "Submit a photo" content type. When the node's content evolves (read: the more effort/details added to it), I convert its content type to finished products like (eg) a recipe, a redbook (already from my Drupal 6 days a few years ago). In your case it'd be the "Look" content type.

By combining it with an access module such as Content Access (my preference) or Taxonomy Access Control you can make it more restrictive to give access to it. E.g. public (anybody) to start from, then "authenticated", and in the end only for roles such as "subscribers", "students", etc.


Export Users with custom fields? I need to set up a semi-regular export of people who have signed up on our website. We're using Drupal 7. I can do a simple export of the Users table, but that doesn't include the additional custom fields we've added.

Is there a module already available in D7 that handles exporting the user database with the custom fields associated with these records?

If not, is there a simple query I can do to identify the custom fields associated with the registration process at runtime? I'd like the export to still work if my customer decides to add a new field.

I know that this question has already been answered, but thought I'd point out the Views Data Export module for anyone looking for a contributed solution rather than a bespoke one. This module allows you to define Views that generate CSV files for export. We're using this with Drupal 7 for a client so that they can export all users and their associated custom fields. It's working well.


Domain Access: Edit admin/domain/content/ display settings, filters etc I am using Drupal Commerce and Domain Access module and I wonder where I could be able to edit how page admin/domain/content is displayed. I would expect to find a View page which is utilised by this module to show content and to allow to add filters and fields.

I have got a multi-domain site with thousands of products and I need to filter content by manufacturer or other field and to assign all products with desirable keywoord to selected domains.

Am I missing anything? I have not found any corresponding View.
Thank you for an answer

Domain Access does not provide a view like you want.
You could try the Admin Views module which overrides the standard content admin page with a view.
Also, Domain Views module which integrates domain access with views.


Blocks display in the wrong place and can't be turned off I'm experiencing problems: Some of my blocks are appearing in two blocks at the same time. Some blocks appear when disabled, even if I disable the block is still appears in one of the locations. It's happening with several blocks but not all.

This is what the footer looks like:

Drupal 7.34 running locally Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3

The theme is BigWig

Block caching is switched off. I've used the "Flush all caches"
button and deleted everything in the cache DB table.
I only have 4 blocks displaying, the "business info" (currently duplicated), "copyright info" (appearing correctly) and "main page content" and "System help".
I've checked the theme code and the "Powered by Drupal" block is a block and not hard coded. But the block is disabled.

After nearly going insane I noticed that the module, "Context", was overriding my blocks.


How do I redirect users from Japan to a certain subsite? I want users from Japan to be redirected to www.example.com/test2 when they hit www.example.com/test1. In the menu only Test1 is visible.

What tools do I need? I tried to insert a PHP script into the header with the 'Add to Header' module, but for that I need the directory of the sites, which I do not have.
I can also set Geo Rules, but then I have two sites with different URLs which are invisible and unaccessible for those excluded, but the 'Access denied' message is not preferable.

You can have country based redirection to any internal, or exernal path using the Context, Context GeoIP, and the Context Redirect modules.


Ubercart: has an order been paid? Are there any good Ubercart hooks or other API features so I can learn about whether my Ubercart orders have been paid at all?

Basically all I need is a function that would tell me if an order invoice has been paid-in-full or not.

You can use
uc_payment_balance() function to know how much the customer still owes to you.

  uc_payment_balance($order)

where $order - the order object


How to place facet block in views page header? (not regions) I've created a search with Search API module and Facets module. I've added two taxonomy term name fields to my search index and created two facets for those fields. Just for testing I've placed the facet blocks in my main content area, and fulltext search and faceted filtering are working as expected.

Now I want to place the facet blocks in the header of the view, and not in a page region. I've checked the block source file and ID of the facet blocks is facet_block. Facet blocks are derived blocks, so my best guess was that the block ID should be facet_block:MACHINE_NAME_OF_FACET.

I've added a Global: Rendered entity - Block to the header of the view. As block ID I've entered the schema from above, e.g. facet_block:museum for my "museum" facet.

However, the facet block doesn't show in the views header. (The same facets placed via block layout still work fine.)

Can anybody tell me how to render facet blocks inside a view header?

(I'm looking for a no-code-solution, without preprocessing or editing templates)

Firstly, I would recommend that you consider placing the facet block right above the view instead of performing a surgery on views :D

That said, here's what I think might work:

Solution 1: Views Header

Views allows you to attach rendered blocks in the views header.
In the views UI, click the Add button in the Header configuration.
Then choose Rendered Entity - Block and choose the facets block you want to display

Solution 2: Attachment Before

Write a hook_views_post_build()
In this hook, render the facet block as the attachment_before of the view.

See this answer about rendering blocks programmatically

You might face some difficulties with views caching, etc, but you can fine-tune the views build to alter the caching rules.
If you don't like the idea of Attachment Before, you can also consider adding a header item with a custom token like @facet:foo@ and then replace this custom token with a rendered facet block in hook_views_pre_render()

I hope this helps!


No response from Services Entity API when added '.json' to the end of alias While configuring Services module, when I add '.json' to the end of the resource alias I get an emtpy page. Other resources that are not provided via Services Entity API output json the same way. The Services Entity API module have no documentation in this direction. Any ideas?

Edit: Also adding '.xml' gives empty response which points to that I am doing something wrong:)

Okey,

You shouldn't add the suffixes like .json or .xml to the end of the alias name like you do with some other resources if the resources are provided by services_entity module. Adding the suffix directly to end of the whole url solved it.

example.com/endpoint/resource_alias/resource_id.json ie:
example.com/api/entity_node/5.json


using twig | replace filter in a view I'm using textbox replace in a view for an ICAL and I need to get the special characters to render. Right now calendars like Google Calendar just shows the encoded characters instead of the decoded characters. I want ' instead of this ' .

right now it's not doing anything. I've tried multiple ways to pull this off using  |render or using replace | but nothing works. It still just shows up with the encoded characters. example below

{% set special_1 = '&#039;' %}
{% set result_1 = "'" %}
{% set special_2 = '&amp;' %}
{% set result_2 = '&' %}

{{ title_1|replace({ (special_1): result_1, (special_2): result_2 }) }} - {{ field_sport|replace({ (special_1): result_1, (special_2): result_2 }) }}

You can write try custom Twig_Extention

In yourmodule create service

yourmodule.service.yml

services:
  custom_replace:
    class: Drupal\yourmodule\TwigExtension\Custom_Replace
    arguments: ['@renderer']
    tags:
      - { name: twig.extension }

src/TwigExtension/Custom_Replace.php

<?php

namespace Drupal\yourmodule\TwigExtension;

/**
 * Class Custom_Replace.
 */
class Custom_Replace extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'custom_replace';
  }

  public function getFunctions() {
    return [
      new \Twig_SimpleFunction(
        'custom_replace',
        [$this, 'custom_replace'],
        ['is_safe' => ['html']]
      ),
    ];
  }

  /**
   * {@inheritdoc}
   * @param $search can a array [`word1`,`work2`] or string `word`
   */
  public function custom_replace($string, $search, $replace = '') {
    return str_ireplace($search, $replace, $string);
  }
}

In template yourpage.html.twig

{{ custom_replace('word','',string) }}


drupal_goto() not remove url path of 404 page I have a search form which returns to search page.

drupal_goto('/searchyour/trips', array('query' => $query));

this is work fine if a user in active page. search url will replace as eg: example.com/searchyour/trips

But if user in 404 page (example.com/nopage) and click search, search url will set to example.com/nopage/searchyour/trips I want to change this to example.com/searchyour/trips.

I'm new to drupal. Help me to solve this. :-)

Hope this will help you,

In Drupal 7 , you can check whether the page is 404 page or not. If it is a 404 page then change the drupal_goto $path parameter.

drupal_get_http_header : Gets the HTTP response headers for the current page.

  $status = drupal_get_http_header("status");
  $path = ($status == '404 Not Found'){
    //change the path from example.com/nopage/searchyour/trips to example.com/searchyour/trips
    drupal_goto('/searchyour/trips', array('query' => $query));
  }else{
    drupal_goto('/searchyour/trips', array('query' => $query));
  }


Is there a Drupal module that implements a (+/-) button with a counter textbox at the side? Can you implement a (+/-) button with a counter textbox at the side with Drupal like a shown below?

A very simple way of implementing this, like using an existing module, is much welcome. I am also open for answers implementating this using hard coded scripts.

There is already a module that gives you a vote up/down button, just like the one we have here on SE: https://drupal.org/project/vote_up_down.

  Allows votes on some drupal entities and provides the base for implementing votes on other entities.

It is still under dev for Drupal 7, but IMHO quite usable.  If you find any problems, it will probably be less work to help the developers fix those, compared to reinventing the wheel.


How to open jquery dialog on menu click I would like to open a jquery dialog that asks a question before taking the user to the desired page (ie do some page set-up before they get there). The catch here is that I would like to open the dialog when the user clicks the menu item. I am not sure how to go about this. Could someone point me to some examples where this is done or what I need to do? I am using Drupal 7.

Thanks.

You can use dialog ui or colorbox, just attach this scripts to the page and add custom click event for menu item to open popup. Or you can use ctools but it's more complex.


Yo Dawg, I heard you like $view->execute() I've created a View of all the views that Drupal knows about, whether they reside in code or in the DB. It works great, tells the user about each view, its tags, its displays, its base table, its fields if they exist, and its path.

I'm doing this by overriding execute(&$view) in a custom query handler. A very truncated version of what I'm doing:

foreach(views_get_all_views() as $zview) {
    // Examine each display of each view.
    foreach($zview->display as $display) {
      $row = new stdClass();
      ... // Set the things on $row.
      $view->result[] = $row;
    }
}

Now I also want it to tell the user about each View's query.

If I do this it works (for the last of the many Views):

      $zxview = views_get_view($zview->name);
      $zxview->set_display($display->id);
      $zxview->pre_execute();
      $zxview->execute();
      dpm($zxview->query->query()->__toString());

but I have to do it outside of the foreach() that goes through each view. If I try to do $zxview->execute() inside foreach(views_get_all_views() as $zview) { ... } I get

PHP Fatal error:  Maximum function nesting level of '100' reached, aborting!

This makes sense, sort of. But, so how can I list the query being executed for each view next to the name of each view, within a view? (I'm already excluding views defined by the module defining this view of views.)

I searched on that error and you can increase the limit from 100 to something larger.
Increase the value of xdebug.max_nesting_level in your php.ini:

xdebug.max_nesting_level
Type: integer, Default value: 100
Controls
the protection mechanism for infinite recursion protection. The value
of this setting is the maximum level of nested functions that are
allowed before the script will be aborted.

Try setting it to 200

xdebug.max_nesting_level = 200

Thanks to Stack Exchange for the answer!


How do I get content to display using Views and Panels? I've created a custom view to display two different content types and now want to override the node display with this new view. I tried using this tutorial to do so with Panels, but I always get no content. Not a completely white screen, just a title and nothing beneath it. I am able to add other content using Panels directly, so I think it must be a problem with the way Views and Panels are interfacing. Any idea what I need to do to fix this?

I have tried:
- changing the output format of the view to 'Panel Fields' (as opposed to 'Content').
- clearing and re-clearing my browser's cache.

I'm using Drupal 7.12, Chaos Tools 7.x-1.0-rc2, Panels 7.x-3.2 and Views 7.x-3.3

For Views to work in panels, you should create a Content Pane in your view.

You will likely be using a contextual filter if it's a node / user / taxonomy view so add it, and check provide default: content id from url (for a node).

Then in the Pane Settings section, click Argument Input. You will see your contextual filter listed. Choose "From Context", "Content ID".

Your view should now work as expected.


Views - Clicked element + corresponding content I have a content type which contains the following fields

title
text body
image

An I need to achieve something like below

The 4-image grid is a view which covers 50% of the page. The green coloured box represents the clicked image. I need the text-area right next to the view to contain the the text corresponding to the image which is clicked.

Is it possible to achieve this using views alone?

Step 1: Create the View, the block and the required fields (order matters).

Block's instructions (page can be different):

Format:

Grid
Number of columns: 2

Fields:

Nid: Exclude from display
Title:

Link this field to the original piece of content: Unchecked
REWRITE RESULTS -> Rewrite the output of field -> Output this field as a link -> Link path: ajax-link/nojs/[nid]
Link class: use-ajax

Image:

Link image to: Nothing
REWRITE RESULTS -> ... Same as "Title"
Link class: use-ajax

So, the title's or image's url should have this structure: hook-menu-registered-path/nojs/argument

Step 2: Create a custom module and implement the following code.

/**
 * Implements hook_menu.
 */
function custom_module_menu() {
  // A menu callback is required when using ajax outside of the Form API.
  $items['ajax-link'] = array(
    'page callback' => '_custom_module_response',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 *  Callback function.
 *
 * @param int $nid
 *   Either a valid node id or 0 (zero) if not available.
 *
 *  @param string $type
 *   Either 'ajax' or 'nojs. Type is simply the normal URL argument to this URL.
 *
 *  @return string|array
 *    If $type == 'ajax', returns an array of AJAX Commands,
 *   otherwise, just returns the content, which will end up being a page.
 */
function _custom_module_response($type, $nid = 0) {
  $output = _custom_module_node_load($nid);
  if ($type == 'ajax') {
    $commands = array();
    // Selector: A jQuery selector string, either a .class or #id.
    $commands[] = ajax_command_replace('.selector', '
' . $output . '
');
    $page = array('#type' => 'ajax', '#commands' => $commands);
    ajax_deliver($page);
  }
  else {
    $output = isset($output) ? '
' . $output . '
' : t('Node does not exist!');
    return $output;
  }
}

/**
 *  Node loader function.
 *
 *  @return string
 *   The themed node in its define view mode.
 */
function _custom_module_node_load($nid = 0) {
  $node = node_load($nid);
  if ($node) {
    $pre_rendered_node = node_view($node, $view_mode = 'full');
    return theme('node', $pre_rendered_node);
  }
}

Step 3: Load the necessary library. I chose the template.php file to do it.

/**
 * Implements template_preprocess_views_view.
 */
function custom_theme_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  if ($view->name == 'my_view_name') {
    // drupal_add_library is invoked automatically when a form element has the
    // '#ajax' property, but since we are not rendering a form here, we have to
    // do it ourselves.
    drupal_add_library('system', 'drupal.ajax');
    $output = '
' . $vars['rows'];
    $output .= '
';
    $vars['rows'] = $output;
  }
}

Now, should only the body field must be displayed (or a certain set of fields) I suggest the definition of a view mode per case, then define that view mode to the node_view function.

Note:

Ajax framework's "magic" class: use-ajax

  By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call. When using this method, the href of the link can contain '/nojs/' as part of the path. When the Ajax framework makes the request, it will convert this to '/ajax/'. The server is then able to easily tell if this request was made through an actual Ajax request or in a degraded state, and respond appropriately.

Ref.: Drupal examples modules, How to use Drupal 7's built-in Ajax Framework


Getting current node paragraphs content from block I'm trying to build a block to insert on the side of the page that would list all "paragraphs" titles (from paragraph module) and link to them via an anchor (a little bit like the book module does but inside the same page)

For now i managed to get the list of paragraphs :

$node = \Drupal::routeMatch()->getParameter('node');
$paras = $node->field_paragraphes;

but can't get to the list of fields and their values inside that paragraph.
When i loop over them all i seem to get is an EntityReferenceRevisionsItem or at best an array like :

array (size=2)
  'target_id' => string '8' (length=1)
  'target_revision_id' => string '12' (length=2)

But i can't find their fields and values ?

Thanks a lot !

Paragraphs are separate entities, the field just stores the reference. To access them, you can do something like this:

foreach ($node->field_paragraphes as $item) {
  // Access the paragraph entity like this:
  $item->entity;
}


Show page with child terms when clicking parent term I have a vocabulary with the following structure:

Vocabulary
Parent term 1
    Child term 1.1
        Node tagged with child term 1.1
    Child term 1.2
        Node tagged with child term 1.2
Parent term 2
    Child term 2.1
        Node tagged with child term 2.1
    Child term 2.2
        Node tagged with child term 2.2
Parent term 3 (no children)
    Node tagged with parent term 3
    Node tagged with parent term 3

With very limited knowledge I managed to create a view displaying the top-level terms. I would like to click on one of this terms and go to a page displaying either the child terms of the selected parent or, if there are no children, the nodes tagged with that term. After much trial and error all I get when clicking a parent term is a message of 'There is currently no content classified with this term' when I really want to display its children.

In a desperate attempt I created different vocabularies for the terms with child terms and the terms with just nodes underneath. Then I used Views to create different blocks based on the vocabulary name and placed those blocks using the Context module, but this seems like a long shot and I'm sure there's a more straightforward way to accomplish this. By now I have tried several combinations with Taxonomy Menu, Taxonomy Display, arguments and relationships in Views, etc. and I'm not any nearer.

I posted this at the Drupal forums but with no luck yet, I hope someone here can help me figure this out :)

Follow these steps

Create a view
Add a relationship "Content: Tags", (Tags is vocabulary name I want to show content for)
Add a contextual filter "Content: Has taxonomy term ID (with depth)" (you can provide a depth of taxonomy term here to display content, if set to 0 it will show content tagged with that particular term id only, if 1 then that particular term id + its first child term content)
And provide proper value for this contextual filter.

Here is the screenshot of view I've created:

Hope this helps.


Block machine name is in use that is not available I have a Site Branding block I style in my theme. To do this I give it a specific machine name, in this case: sitelogo

On a site using that theme I am trying to create this block but when I try to edit the machine name of the block to sitelogo I am getting the following error:

The machine-readable name is already in use. It must be unique.

An actual block with that machine name does not appear to exist, or at least I cant find it on the site.

Is there a way to force the deletion of that machine name so I can re-use it? I am pretty sure I didn't create it and I need block to have that specific machine name...

Block machine names must be unique in the system, not only in the theme.

When you know the machine name of a placed block you can delete it in UI:

/admin/structure/block/manage/sitelogo/delete

This will of course remove the site logo from one of the other themes.


How to vary classes depending on content type? In my page.html.twig template file, I'm looking to set classes depending on the content type the page is being viewed. I pretty much have two options, if the page being viewed is a program page, then I want one style applied to the div, if it's anything else, then the other style can be applied.

{%
  set aside_classes = [
    node.content-type is 'program' ? 'program',
    node.content-type is anything else ? 'standard'
  ]
%}

I know the above code is not proper but it's an example of what I'm trying to achieve.

I would then have the following code below on my div:

<div{{ content_attributes.addClass(aside_classes) }}>

Am I going about this right or is there a better way to achieve this?

EDIT:
Here are my kint variables. Not sure if this helps at all?:

Not sure about page.html.twig. Would have to dig around...

In node.html.twig:

{%
  set newClassNameVar = [
    node.type.entity.label == 'Program' ? 'Program' : 'Not Program'
  ]
%}

or:

{%
  set newClassNameVar = [
    node.bundle == 'content__type' ? 'set-yes-class' : 'set-no-class'
  ]
%}

use debug such as {{ dump(_context | keys) }} to see what is available and best suits your use case.


Individually Print Exposed Filter Elements/Options I'm using Better Exposed Filters on a view and want to individually print the elements/options within the 'widget', rather than all of them at once.

For example, lets say my options are: Red, Yellow, Green, White and Black, I want to be able to print Red, Yellow and Green in one , then White and Black in another.

From this:

To this:

The the template appears to only allow for an all or nothing approach:

    <div class="views-widget">
      <?php print $widget->widget; //this prints everything?>
    </div>

I imagine I could print the entire widget a number of times, then hide specific elements using CSS, but I feel this would create a a bit of a performance hit.

I've also tried separating options into different filters, but more than one exposed filter crashes my site as soon as the user selects options in more than one filter.

I found a fairly reasonable solution to this - there may be better ways, but so far it works without any performance hit that I have been able to detect.

It seems as it's a fairly complex multidimensional array, you can only render an entire widget or not. So to do this you need to create different versions of the widget, with different options inside them, and render them in their entirety.

Step 1: Copy the form array (the widget) into a new array and create another array containing just the options

$formArray = $form['colours'];
$allColours = $form['colours']['#options'];

Step 2: Unset all the options from the new array, which is now just a shell, then create a few copies of it

unset($formArray['#options']);
$justColours = $formArray;
$justShades = $formArray;

Step 3: Cycle through your array containing just the options, and distribute them back into the shells you created

foreach ($allColours as $id => $result) {
    if ($id >= 0 && $id <= 2):
          $justColours['#options'][$id] = $result;
    elseif ($id >= 3 && $id <= 4):
          justShades['#options'][$id] = $result;
    endif;
}

Step 4: Render your new arrays where you need 'em

print render($justColours);
print render($justShades);

Snap!


Render View or Block not Working in Drupal 7 So i have made a view and a block for a carousel.
I want to call this view or block in my template. (panels-pane.tpl.php).

I have tried to call the view with this function :

<?php $view = views_embed_view('carousel', 'carousel-block_1'); print $view; ?>

Unfortunately this is not working. Variable $view is NULL

I also tried to call a block in this template file with this function :

$block = module_invoke('views', 'block_view', 'carousel-block_1');
var_dump($block); // Empty ;s

Also not working..

The Delta ID is right. See Screenshot below for more information.

Do i something wrong?

Full page code with other view render (also not working):

<?php
// @codingStandardsIgnoreFile

/**
 * @file panels-pane.tpl.php
 */

?>

<?php if ($pane_prefix): ?>
  <?php print $pane_prefix; ?>
<?php endif; ?>
<div
  class="<?php print $classes; ?>" <?php print $id; ?> <?php print $attributes; ?>>
  <?php if ($admin_links): ?>
    <?php print $admin_links; ?>
  <?php endif; ?>

    <?php $view = views_embed_view('downloads', 'downloads-product_downloads'); print $view;     var_dump($view); ?>
    <?php print render($title_prefix); ?>
    <?php if ($title): ?>
    <<?php print $title_heading; ?><?php print $title_attributes; ?>>
    <?php print $title; ?>
  </<?php print $title_heading; ?>>
<?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($feeds): ?>

      <?php print $feeds; ?>

  <?php endif; ?>

  <?php print render($content); ?>

<?php if ($links): ?>

    <?php print $links; ?>

<?php endif; ?>

<?php if ($more): ?>

    <?php print $more; ?>

<?php endif; ?>

<?php if ($pane_suffix): ?>
  <?php print $pane_suffix; ?>
<?php endif; ?>

I hope views will never use hypens. May be you typed wrong.

Views always use underscores.

<?php $view = views_embed_view('carousel', 'carousel-block_1'); print $view; ?>

I think it should be

<?php $view = views_embed_view('carousel', 'carousel_block_1'); print $view; ?>

As per your template.php

<?php $view = views_embed_view('downloads', 'downloads_product_downloads'); print $view;     var_dump($view); ?>


Installed Revisioning Module, how do you make it default to create new revision? I just installed the Revisioning module, but all my existing nodes are set to: "Modify current revision, no moderation", but I would like it to be set as create new revision by default. I don't want my users to manually click this when they are editing a node.

How do I make it by default to create a new revision for existing nodes?

Creating new nodes is not an issue as its already set by default to create a new revision.

You can alter the node edit form following the Revisioning's implementation.

/**
 * Implements hook_form_alter().
 */
function myModule_form_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['#node_edit_form'])) {
    if (isset($form['revision_information']['revision_operation'])) {
      $form['revision_information']['revision_operation']['#default_value'] = REVISIONING_NEW_REVISION_NO_MODERATION;
    }
  }
}

/**
 * Implements HOOK_module_implements_alter().
 *
 * Ensure our hook runs after revisioning_form_alter().
 */
function myModule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    $group = $implementations['myModule'];
    unset($implementations['myModule']);
    $implementations['myModule'] = $group;
  }
}


DrupalDateTime class not work I try to use "DrupalDateTime" class in my theme to show native date and time in custom format based on special TimeZone in my nodes.
According to this article: New Datetime API

Drupal core and contributed modules should use the DrupalDateTime
class in preference to the PHP DateTime class or to functions like
date(), gmdate(), strtotime(), etc.
the class incorporates the IntlDateFormatter into its format() method,
if the IntlDateFormatter is available, and otherwise falls back to
wrapping formatted output with Drupal's translation system. The
IntlDateFormatter requires additional information, which can be passed
in a settings array.

And then I add below code to MyThmeName.theme:
Note: Be sure to add use Drupal\Core\Datetime\DrupalDateTime; at the top of any files that use this class.
function MyThemeName_preprocess_node(&$variables){
  $node_date = $variables['node']->getCreatedTime();
  $date = new DrupalDateTime($node_date, 'UTC');
  $date->setTimezone(new \DateTimeZone('Asia/Tehran'));
  $variables['date'] = $date->format('Y/m/d'); }

I'm sure PHP intl extension was exist! I cleared comment before this line in php.ini file:
;extension=php_intl.dll

I get below error:
Exception: DateTime object not set. in Drupal\Component\Datetime\DateTimePlus->__call() (line 308 of core\lib\Drupal\Component\Datetime\DateTimePlus.php).

Update:
I'm following kiamlaluno solution carefully
but the result not changed and date is shown in the English language yet and howsoever I try I can't get an appropriate result to show date and time in my native calendar, where is the problem, is there other parameters that should be set.
if (isset($variables['node'])) {
  $date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), new \DateTimeZone('Asia/Tehran'), ['langcode' => 'fa']);
  $variables['date'] = $date->format('Y/m/d');
}

Thanks for any help.

The code you are showing is wrong because DrupalDateTime::__construct() is expecting a string, while you are passing an integer, which is what Node::getCreatedTime() returns.

Instead of DrupalDateTime::__construct(), you should use DrupalDateTime::createFromTimestamp().

$date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), 'UTC');

Since the static method also accept a \DateTimeZone object as second parameter, your code could be similar to the following one.

if (isset($variables['node'])) {
  $date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), new \DateTimeZone('Asia/Tehran'));
  $variables['date'] = $date->format('Y/m/d');
}

Since you seem interested to get strings in a specific language, you should also set the language code.

if (isset($variables['node'])) {
  $date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), new \DateTimeZone('Asia/Tehran'), ['langcode' => 'the language code for the language you need']);
  $variables['date'] = $date->format('Y/m/d');
}


phpunit test: drupalGet a public node returns 404 Simply trying to get a node.

$this->drupalGet('node/25250');
$this->assertSession()->statusCodeEquals(200);

But this returns 404. I can browse to that node anonymously. Why is it returning 404?

BrowserTestBase do not run against your installation, they do a new installation and then run against that.

There is no content, no modules, pretty much nothing there by default, everything you need to need to create and install.

If you're looking for a way to run tests against your installation, you might be able to override the set up and tear down process. Or look at using behat: http://behat-drupal-extension.readthedocs.io/en/latest/intro.html