Relationships Between Nodes on Field I'm trying to work with some information out of our enterprise system to create an employee directory, and I have a question regarding how I can relate nodes together.

I have a content type called Employees, and it has a number of fields, including Employee ID, First Name, Last Name, etc.

I then have a content type called Positions, and it has a number of fields, including Employee ID, Title, etc.

I'm trying to figure out how I can link the Positions and Employee nodes together on the Employee ID field rather than the nid.

Any help would be appreciated. Thanks!

If you're looking for a relatively simple option, Entity Reference is probably best:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field Four widgets: Two implemented on top
  of the Options module (Select and Radios/Checkboxes), Two autocomplete
  widgets (one with one text field per entry, one tag-style with
  comma-separated entries in the same text field) Two formatters: A
  "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.) A "Rendered
  entity" formatter, that renders the references entity using a
  configurable view mode Integration with Views (for both forward and
  backward references) Integration with Entity Metadata (and as a
  consequence with Search API and the like) Integration with Devel
  generate Integration with Feeds and Migrate (>= 2.3) for painless data
  import

EDIT #1

To set up the view as described in comments:

Create the view for Employee Content Type, and make settings how you desire
Add a Relationship to Entity Reference: Referenced Entity for the entity reference field, Require this relationship

Now you have access to the fields in the referenced (position) content type and can display them in your view.  One thing of note, Title field may not work from Position, so you may have to include a separate field for the Position Title. Otherwise, everything should work as a normal view


What to attach event listener to in Drupal behavior I have a use case where I need to listen to the insertIntoActiveEditor event in the insertIntoActiveEditor event in the Insert module, but with this code:

(function ($) {

/**
 * Custom behavior to generate image style derivatives on S3 when an image is
 * inserted into the WYSWIYG editor.
 */
Drupal.behaviors.generateDerivative = {
  attach: function(context, settings) {
    $(document).on('insertIntoActiveEditor', function(event, data) {
      var test = 'a';

    })
  }
}
})(jQuery);

I'm getting an error that says

Uncaught TypeError: $(...).on is not a function

on this line

$(document).on('insertIntoActiveEditor', function(event, data) {

I thought I had that syntax correct, but apparently I don't. Do I need to change my selector to be the Insert button (the same as is used in the module JS)? I"ve tried changing it to

$('input[value="Insert"]').on('insertIntoActiveEditor', function(event, data) {

but I still get the same error.

Thanks.

The cause was pretty basic - this is in the admin theme, which in Drupal 7 is set to use jQuery 1.4.4, and .on() wasn't added until 1.7. I switched to using .bind(), and it works fine now.


Which is the better module for shopping cart? I would like to use a shopping cart module in my site.

Can any one suggest which would be the better one with basic functionality like displaying content (media), cost, adding to cart, billing, etc. It must include all necessary features of a shopping cart.

Will Ubercart fulfill the basic requirements?

From the sounds of it, you actually want a whole e-commerce system, not just a shopping cart.

Ubercart will do this for you, but the general trend now is to go with Drupal Commerce (project page | Commerce homepage).

Both modules will allow for shopping carts, as well as integration with a variety of payment service providers.  I'd personally go with Drupal Commerce.  It seems a little more difficult than Ubecart at first glance, but once you get over that you'll realise it is much more flexible/powerful.

Try using the Commerce Quickstart installation profile to get yourself familiar/started with it.

There are a lot of good videos for Commerce as well such as Selling Content with Drupal Commerce using Content Access and Roles from the Commerce Guys.

Lastly, there is a blog post here that weighs up the pros and cons of each system (although it is from 2011)

Edit:

You might find the getting started guide useful also.


Disable comments in nodes specific taxonomy terms are attached to I know it is really easy to disable comments if your content is organized by content type, but what if it is organized by taxonomy, is it possible to disable comments on all nodes with, say, the term 'news' attached to them? If so, how?

For anyone not already a seasoned Rules user, here are detailed steps / a worked example for @Wheelz's approach.

This answer shows you how to enable comments when a specific taxonomy term is present and to disable them when that taxonomy term is absent. As per @Wheelz's answer it requires the Rules module. These steps have been tested against 7.x-2.2.

Create a new Rule called, e.g. 'Enable comments when tagged blog'
Add an event of the Before saving content type (use the 'React on event' dropdown and under the subdivision Node, select Before saving content). Save.
Add a condition to test for the presence of the taxonomy field that will control whether comments are allowed.

Add a condition of the Entity has field type (use the 'Select the condition to add' dropdown and under the subdivision Entities, select Entity has field)
Select node (saved content) from the 'Data selector' dropdown. (Or type node into the 'Data selector' field.) (Don't be tempted by the node:... (saved content) option. It's not what is needed here.) This specifies the type of entity for which you want to check for the presence of a field. In this case we want to check for nodes.
Select the field to check for. The dropdown will give you a list of machine names (lower case and with underscores), e.g a field labelled 'Tags' might have the machine name field_tags. (If necessary look up the machine name for the relevant field in your the 'Manage Fields' tab of the relevant content type(s).)
Save

Add a condition to test for the taxonomy term that will enable comments.

If your taxonomy field can only have one value, then select a condition of the Data comparison type. Otherwise select a condition of the List contains item type.
Select the field to test using the 'Data selector' drop down. This is a two step process. First select node:... (saved content). When you do this, the dropdown items change. Select node:<your field's machine name - but with dashes not underscores>, e.g. node:field-tags. (Don't be tempted by node:field-tags:... (Tags) - that's not what is needed here.)
Continue
If the next page isn't showing a 'Value' dropdown, click on the 'Switch to the direct input mode' button.
Use the 'Value' dropdown to select the taxonomy term for enabling comments, e.g. 'Blog'.
Save

Add an action that will enable comments

Add an action of the 'Set a data value' type.
Use the 'Data selector' to select the comment mode, This is a two step process. First select node:... (saved content). When you do this, the dropdown items change. Select node:comment (Comments allowed). Alternatively, you can directly enter node:comment into the 'Data selector' field. If you let you let your mouse hover over `node:comment (Comments allowed)' entry in the dropdown you will see a helpful tip: Whether comments are allowed on this node: 0 = no, 1 = closed (read only), 2 = open (read/write). This helps with the next step.
Continue
If the next page isn't showing a 'Value' field, click on the 'Switch to the direct input mode' button.
Enter 2 into the 'Value' field. This sets comments to 'Open (read/write)'.

The rule just created will switch on comments when the chosen taxonomy term is present. But if that taxonomy term is later removed the comments will still be open. To turn off comments when the taxonomy term is absent, first clone the rule just made and then make a couple of small tweaks.

From the main Rules configuration page, click the ‘clone’ link for the rule you have just created, e.g. 'Enable comments when tagged blog'
Change the name of the rule, e.g. to ‘Disable comments when not tagged blog’. Save changes.
Edit the ‘List contains item’ condition.

Check the ‘Negate’ box. If the original condition succeeded, i.e. evaluated as TRUE, when the Tags field included the term ‘Blog’, this modified condition will succeed only when the Tags field does not include that term.
Save.

Edit the ‘Set a data value’ action. Replace the value 2 with 0. Save.

This second rule switch off comments when the chosen taxonomy term is absent.

Note: if a 'List contains item' gives an Error: The data type of the configured argument does not match the parameter's list requirement error, then your term reference field is set to allow only one value. You will need to delete the List contains item condition and replace it with a Data comparison condition instead. In the complementary case where Data comparison condition is used when a List contains item condition is needed, errors will be generated when the rule is run and the rule will not work.


Is there any way to connect Acquia Cloud intance with issue tracker? As in question, I'm looking for a way to connect any issue tracker with a development site hosted by Acquia Cloud.

I want to have a connection between git commits and issues.

Is this possible in Acquia?

I use the combo of BitBucket/JIRA. There are many people that like GitHub's issue tracker too. Acquia has tutorial on setting up either service as a 2nd remote repo. Either service will give you a way to track issues against your commits.


OG: How to import 2 related nodes from CSV files using Migrate module? I would like to import 2 related nodes (Organic Group and OG group content)
from 2 CSV files using Migrate module
but I cannot find a proper CSV migrate class example or module. I use Drupal 7.

OG Group
  |
  |--OG group content

file formats:

(a) OG Group file
=============================================
gid | group_title | group_body | group_admin

(b) OG group content
==================================
nid | gid | node_title | node_body

relationship:

{a.gid} 1..(one-to-many)..* {b.gid}
{a.group_admin} *..(many-to-one)..1 {users.uid}  // group admin is one of existing users uid that should have the OG group administration membership rights

Where can I find a sample CSV migration class for Migrate module ?

Migrate OG is for D6 only
Migrate Extras contains classes for OG for D7 but I could not find an example for this scenario.

Okay so I'm assuming that you haven't used Migrate before. If you'd like some background reading take a look at the slides for the presentation I'll be giving at DrupalCon in Denver: http://denver2012.drupal.org/sites/default/files/slides/Migrate_0.pdf It should help you understand some of the concepts.

One thing that's important to point out is that you'll need two migrations:

Using (a) and MigrateSourceCSV as a source and—assuming the groups will be nodes—MigrateDestinationNode as a destination.
Using (b) and MigrateSourceCSV as a source and MigrateDestinationOGMembership (as you noted part of Migrate Extras) as a destination.

The CSV files are actually really easy to use as a source. You can see an example of it in the Migrate docs: http://drupal.org/node/1152158

In your case you could setup the source for (a) with:

// The definition of the columns. Keys are integers, values are an
// array of field name then description.
$columns = array(
  0 => array('gid', 'Id'),
  1 => array('group_title', 'Title'),
  2 => array('group_body', 'Body'),
  3 => array('group_admin', 'Admin'),
);

// Instantiate the class using the path to the CSV file and the columns.
$this->source = new MigrateSourceCSV('path/to/a.csv', $columns);

You'll also need to know something about your source when you setup the Map because it needs to create a field to store the source ids in... since gid's are basically nid's you can just cheat and use that source's schema definition:

$this->map = new MigrateSQLMap($this->machineName,
  MigrateDestinationNode::getKeySchema(),
  MigrateDestinationNode::getKeySchema()
);


The update.php doesn't want to run it's complete course I updated core Drupal (D7.14) and all seems to running perfectly. Only some updates for the database are required. So I run the update.php and I get through the first stages and I can see the pending updates when I am on the Review updates page. But when I continue (press the button). It seems to get stuck. I don't get to next screen, it just keeps on loading. In one browser I get a blank screen but that's it.

Happened to me too. One update took a lot of memory on my shared host. I tried it several times during the Day until I got Lucky.  Maybe a glance in the Apache log Files will help?


Why isn't the user #1 able to edit the user details? I have one site in Drupal 6. When I log in as user #1, and I visit the page at user/[uid]/edit, I am not able to access this page. I get an access denied error.

Can any one please tell me what may be the problem, and the solution?

This is probably a conflict/misconfiguration of some module (or permissions) you have installed on the site and that deals with users or permissions.

Super user (uid: 1) has all privileges, whether or not the admin role exists.

Make a dev version of the site and start disabling modules one by one to find which one caused this.

Which modules do you have installed? Any custom modules? Is there anything in the database/error log?


Is there a module that lists which tables are created, owned or modified by a particular module? Is there a module that lists which tables are created, owned or modified by a particular module?

I need something that can show me what tables are created or modified by when new modules are installed.

Since Drupal 7, tables should get created by modules using hook_schema(), because these tables will also get removed when uninstalling the module.

You can find these tables by executing the code below, or by using the Schema module (https://drupal.org/project/schema):

$schema = drupal_get_schema(Null,TRUE);// Get List Of all tables.
  ksort($schema);// Sort Ascending
  foreach($schema as $table => $value){
    print_r($table."<br>");
  }

All well written modules should create tables only using hook_schema, and should not alter tables in other modules.

If you suspect that other tables got changed, you can find this in the .install file for each module. Look for the database layer calls like db_add_field or even db_create_table.

For a list of all these, consult the Drupal documentation:
https://api.drupal.org/api/drupal/includes!database!database.inc/


How do I set a picture as a background image/wallpaper? I've been trying to set a picture as a background image/wallpaper. I added the module 'Background Images' but am confused since it hasn't done anything. I tried pointing it to a new content type I created that has an image, but nothing happened. I installed Dynamic Background which did what I wanted to happen, but only for admin...

So without any access to the CSS files, is there a way to set a picture as a background wallpaper? I don't have access to the website's CSS, not even through FTP yet.

My knowledge on Drupal is very limited, so if you could have detailed explanations that would be great

Try out Live CSS module

  Edit CSS live within the page, and save the changes back to any css
  file if you have write access.


How do I deploy a Page Manager page using code? I've created a Page Manager page using a Panels layout and a single Variant to act as the desired page. I'd like to store the settings in code for deployment to a different server.

Using Features to export the Page Manager (page_manager_pages) component appears to have done this, however the newly deployed page variant's content tab is empty. The page settings have come through, but the page contents don't show up, even though they're clearly in the featurized module code. The desired content for the page variant is in the file myModule.pages_default.inc, in the function myModule_default_page_manager_pages().

The result upon deployment is that the Page Manager page is created, and appears in /admin/structure/pages, but the Content tab for the page variant is empty. I need the code the provide the many blocks I placed, configured, and saved within the development environment.

I've also tried exporting the entire page or just the variant and importing that, and get exactly the same results.

What code or step am I missing, please?

My setup:

Drupal 7.52
Panels 7.x-3.6
Page Manager 7.x-1.9
Features 7.x-2.10

aha. This problem was caused by a forgotten dependency within the Page Manager page. Instead of using a default layout such as 'two column,' I'd used the Bootstrap layout provided by the Panels Bootstrap Layouts, and then forgot about it. Features didn't add Panels Bootstrap Layouts as a dependency, it remained disabled after deployment, and the dependent page content didn't show. After I enabled Panels Bootstrap Layouts, the content items showed right up within the variant's Content tab.

So if your feature or your Panels/Pages import doesn't recreate the entire setup, review the original for any options that might be provided by another module.


Use services in controller I am trying to create a custom service and call it from a controller that is being used on a route.
I use simple code, so I think I am missing something

The membership service:
https://gist.github.com/betz/6e0cb7ce2712793711d4c9ed99a3a697

Controller:
https://gist.github.com/betz/a9aa9db636cd9b9bffea3b4e255fb1df

services file:
https://gist.github.com/betz/25aeb579c265bfba83a0e891aa883bf8

routing file:
https://gist.github.com/betz/577a411a8ede77ecc0be614044ec1a44

The error I get:

  RuntimeException: Controller
  "Drupal\hsbxl_members\Controller\Test::test()" requires that you
  provide a value for the "$container" argument (because there is no
  default value or because there is a non optional argument after this
  one). in Drupal\Core\Controller\ControllerResolver->doGetArguments()
  (line 165 of
  /var/www/drupalvm/web/core/lib/Drupal/Core/Controller/ControllerResolver.php).

So it seems the ContainerInterface $container is missing when the controller is being initiated. But how do i do this? Confused.

Cheers!
Tom

In this example you should inject dependencies via the controller create method, pass the container there, and return an array. The first item in the array is the service you’re passing to the constructor.

Then, add a constructor that expects this object as an argument, and then set $this->membership to the container object you passed as an argument. This should also be a protected member of the class.

But to see your example actually work first, remove the container from the test method and remove the line about $memebrship. Clear cache and hit that route to see Hello world!

Here is a similar question demonstrating this: How do I use dependency injection on \Drupal::moduleHandler() to a Controller?


Do a render foreach loop on a regular field? I have a regular field with multiple values,
If i do

render( $fields['field1'] )

It prints

Field1_value1
Field1_value2
Field1_value3
etc

Am trying to get it to output like this

[Field1_value1]
[Field1_value2]
[Field1_value3]
etc

To add [ and ] to the output.
I thought of using a foreach loop, but the field array is like such

'#title' => 'xxxx',
'#type' => 'xxxx',
...
'0' => <array>,
'1' => <array>,
'2' => <array>,

How can I get it to loop throught the [0], [1], [2] etc only?

Note: I have no control on how many multiple values the field may have, so I have to loop.

Another solution that worked well for me: Display comma-separated list of taxonomy terms?

You can make use of the power of field.tpl.php.

$field_values = element_children($fields['field1']);
foreach($field_values as $field_value) { ... }

I was looking for the answer to this too, and ended up hunting through the render() function. It wasn't too far down the chain: drupal_render() calls element_children().

  element_children

  Identifies the children of an element array, optionally sorted by weight.

  The children of a element array are those key/value pairs whose key does not start with a '#'. See drupal_render() for details.


How to render field attribute in foreach I have a link field with multiple values. I want to display the link title for each of these fields. I can print the slide link titles individually but not using the foreach.

Currently I have:

<?php $slideshow_counter = 0;
    $slide_link = $node->field_slideshow_link;
    print $slide_link['und'][0]['title'];
?>
<?php foreach ($slide_link as $link) : ?>

<?php print $link['und'][$slideshow_counter]['title']; ?>

    <?php print $slideshow_counter; ?>
    <?php $slideshow_counter++; ?>
<?php
if ($slideshow_counter == 4)
    break;
endforeach;
?>

As I understand your question, I recommend you to use for statement, you can do this:

<?php $slide_link = $node->field_slideshow_link['und']; ?>
<?php for ($i = 0; $i < count($slide_link); ++$i): ?>

<?php print render($slide_link[$i]['title']); ?>

<?php endfor; ?>

This will print all your titles...


Redirect node/id to node/path-auto-alias Using Drupal 8

I need to set various links between my content types and so far I'm setting the link using their path-auto-generated-alias, but that's terrible practice because if I change the pattern one day I will have to change every single existance of the out of date url alias.

I've seen plenty of answers for Drupal 7 with module Global Redirect but it states that it's deprecated for Drupal 8 and to use Redirect instead. I installed the module and I'm presented with this:

I have no idea what's amitted in there, tokens? If someone could direct me to a documentation where I can learn to use the module I'd really appreciate it since I'm at a loss.

The reason why I'm in that part is because I have the following Global Settings and it's not redirecting /node/id to expected Path Auto URL alias.

Found my mistake, you can't have Check access to the redirected page enabled in the global REDIRECTS.


What's the difference between the 2 different Rules pages in admin? What's the difference between the Rules shown under Structure > Content Types > My type > Rules and Config > Workflow > Rules? The first one is from Entity Rules (= "Instead of adding entity related events to Reaction Rules you are able to select which Rules will fire from the bundle management page").

These pages don't look the same. When do I use one instead of the other (to send emails when nodes are added/edited)?

Entity Rule is not alternate to Rules

It simply acts as component which is, it allows you to set certain conditions and action on it and then this component can be picked by rule to run on certain event.
It gives another interface for rules action on "Entities" so you do not have to have rule administration permission if you belong to a role who has administration permission for certain entities.

  When do I use one over the other (to send emails when nodes are
  added/edited)?

If you want a user role with administration permission of content, and you do not want to confuse or simply give them permission to see all rules on site but you still want them to configure their entity specific rule, use entity_rule module.
You can also it for sanity of configurations, as it will bundle rules specific to entity on entity page, keeping default rules page more cleaner.


custom script to migrate d5 to d7 can any one suggest the custom script to migrate the contents,views and content types from D5 to D7. We already tried with normal conversion process like d5=>d6=>d7 but we facing many errors and contents and views are not imported correctly.

This should help: Direct Drupal 5 to Drupal 7 Migration in 24hrs.

So, rebuild the views and content types on the Drupal 7 site, then use a custom script (like the one provided in the article, or one you write yourself), or the Migrate module to move the data.


Breadcrumb is not visible I am a newbi to drupal.I installed breadcrumb in my website.It is showing in all pages but one page it is not showing the breadcrumb.I created the page using panels module.

You can try Custom Breadcrumbs module.

  Many new features have been added including support for Views, Panels,
  Taxonomy vocabularies and terms, paths, and a simple API that allows
  contributed modules to enable custom breadcrumbs for module pages and
  theme templates. These are implemented using optional, independent
  submodules that depend on the main Custom Breadcrumbs module.

  In addition to breadcrumb visibility, this version provides an option
  permitting PHP code snippets to be used in forming the breadcrumb
  titles and paths. Multiple languages are also supported.

Another option is Panels Breadcrumbs module.

  Panels Breadcrumbs allows you to set your breadcrumbs directly from
  Panels configuration, and also allows you to take advantage from
  Panels arguments and contexts as placeholder tokens.


I need to render just the submenu I need to print the current nodes submenu somewhere on the page. Inside my page.twig.html file I have this markup:

<div id="children-menu">
  {{menu_children}}
</div>

Inside my mytheme_preprocess_page() function I have this which rendering all the submenus.

function mytheme_preprocess_page(&$vars) {
  if ($vars['node']->id()) {
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
      array('callable' => 'toolbar_menu_navigation_links'),
    );
    $tree = $menu_tree->transform($tree,$manipulators);
    $subtrees = array();
    foreach ($tree as $element) {
      $link = $element->link;
      if ($element->subtree) {
        $subtree = $menu_tree->build($element->subtree);
        $output = drupal_render($subtree);
        array_push($subtrees, $output);
      }
    }
    //dpm($subtrees);
  }

}

I was looking into using manipulators, but that wasn't working. How can I render JUST the current nodes submenu using this function? Again, what I have now is rendering all the submenus and I need just the current one.

I managed to grab just the child submenu of the current page. Each subtree has a getRouteParameters() fn that contains the node ID that it links to. I simply test if that route param node id == the current pages node id.

function mytheme_preprocess_page(&$vars) {
  if (isset($vars['node']) && is_numeric($vars['node']->id())) {
    $nid = $vars['node']->id();
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
      array('callable' => 'toolbar_menu_navigation_links'),
    );
    $tree = $menu_tree->transform($tree,$manipulators);
    $subtrees = array();
    foreach ($tree as $element) {
      $link = $element->link;
      if ($element->subtree) {
        $routeId = $element->link->getRouteParameters()['node'];
        if ($routeId == $nid) {
          $vars['menu_children'] = $menu_tree->build($element->subtree);
        }
      }
    }
  }
}


How do I avoid the maintenance screen on database errors? As I'm working on a D7 site, I'll occasionally hit a database-related bug in my code. When this happens, I get thrown to a version of my site's maintenance page; the error information doesn't show up on the page, but just in Watchdog. This makes sense for a production site, but it's a pain during development. Is there any way to turn this behavior off, so that the error messages show up on the page I'm working on? Thanks!

If you have a serious / fatal database error, you're probably not seeing the 'maintenance page' but the db_offline page which usually displays errors direct to screen. What kinds of database errors are you experiencing?

Assuming your site is not in maintenance mode, few things you can check and set:

Check the settings under admin/config/development/logging and make sure you have it set to display 'all messages'
Make sure you have php set to display errors -- you can add the following in your settings.php file to increase your error_reporting level:

error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


Is there a way to add variants to a mini panel? I am trying to organize my content as follows, but I am not certain if it is proper to use variants (if there are variants for mini panels) this way.  Suppose I have a page A.  I would like to easily re-use A as a block in other pages, say as a block with a portion of the content of A and a read more link and placed in a sidebar of the front page.  Note that I want to do this for a few hand-selected pages, and I hope these blocks can be moved around easily like panes.  So I was thinking if I can do the content of A in a mini-panel A', and use A' in both A and the front page.  But that way I must have two ways to render the mini-panel A'.  So how do I add variants to A'?

Minipanels don't support variants, however, you can achieve a similar result by adding visibility rules to show/hide minipanel panes on certain pages, according to specified conditions.

Though more simple options are possible, an example using PHP for a visibility check is here


How to add pager at the bottom which allow shifting between views? I am looking for how to add pager in the complex set of view content.
In my case,
- I have 5 views with different titles, and have 10 items in each views.
- Now, I want to divide each view in 2 pages, so 5 items on each page, so that 5 views will have 10 pages in sum.
- and these all 10 pages has to be connected by single pager 1,2,3....10.
- So on Page-1 View-1 title and its 1stpage and on Page-2 same title and half content of View-1 as described above (5+5).
- and on Page-2 Views-2 with its title and on Page-3 views-2 title and half content of Views-2..
- So, on till views 5. (Please see First image for easy understanding)

Now, what I tried, (1) I added views in views using Views field view module, So I had Main Views which have that 5 views as field and can set 1 item(1 view) per page, so each view will go on each page, but again for dividing each that inside view/sub-view in 2 parts I have to add pager to that each 5 views with 5 items,....So on in the final product MainView(inside Sub-view) will have two pagers....I tried and attaching the Screenshot in the second image.

And Second point, Probably everybody would have seen the Drupal Documentation section of drupal.org. At the bottom the following type of PAGER (shown in attached image- 3) which allow the shift from one topic to other topic. Will it be possible in the above case.

Create 10 different page views. Example:

In Page View1 click on add page

In your view pager, select  Display specified number of items.

Then add an offset of 5 (so your view will start from row 6)

If you're going to make changes to anything make sure you select this page override, otherwise it will make changes to all your page views. (On previous screenshot, see my pager options, I forgot to do that. Should be this page override)

On your footer Add Global text area. (remember this page override)

Then use html to create your own pager. (this is for view 2)

1 2 3 .... Next > Last >>

Then change code accordingly for view 3. (remember this page override)

Now we will need to hide the real pager.

Under Advanced, click on theme info. Then click on Display Output and copy the entire code that's there.

Create a new file and paste the code there.

Now find and delete the <?php print $pager; ?> line.

Now rename the new file to views-view--[view name goes here]--page.tpl (In my case my view is called sadfsafd)

Note: Do not use views-view.tpl.php as your template name, because that will affect all of your views, and we don't want that. By using views-view--sadfsafd--page.tpl I am only affecting the sadfsafd view.

Then upload views-view--[view name goes here]--page.tpl to your sites/all/themes/template folder.

Now clear/flush Drupal cache.


How can I show country icons in the select list provided by the countries module on the edit page? I am using the 2.x series of the Countries and Country Icons modules.  They are both installed properly on my site.

I have a country field called "Nationality" on the user profile page.  I would like to show the flags in the drop-down list (the select widget) when users are editing their profiles.

There is an example of how to show countryicons with user info in the Country Icons documentation but this is for displayed comments, not an edit form.

Basically, what I want is to give the look that the Language Switcher Dropdown module does (screenshot on module page), but for a country field.

Following MotoTribe's suggestion, I filed a feature request which is already in progress.  Exciting!


How to pass fields values How to pass float field value from node(content type A) to another node(content type B)?
which content type B referenced to content type A by using reference from url widget.
thanks

First of all: This introduces redundant data into your DB. Generally this isn't a good idea.

If you must for some reason:

You can implement hook_node_presave for content type B. You get the fully populated $node. This gives you the possibility to load the referenced node type A and grab the value you want to set in B.

Maybe you want to consider to implement the same for content type A. This gives you the possibility to propagete this value every time it changes.


Calling get_theme_setting from php-as-css file I'm developing a Drupal 7 theme, and I'm using a php file as my theme's css file, in order to be able to use variables to simplify colour changes across the entire css.

I've also defined some theme settings in the theme-settings.php

What I want is to be able to call get_theme_setting() from within my style.php file, and use the theme settings to determine CSS attributes.

I recommend you to take a look to less css:

http://lesscss.org/

In fact there is a drupal module for this:

http://drupal.org/project/less

I used it a project and works great.


Clone Colorbox Image Link with JQuery I need to clone a colorbox image link (the first of all colorbox links on the loaded page) and add it onto a div-tag. how could I do that with javascript/jquery? thnx!

I found this solution:

        $('#main-stuff').append('

').css("cursor","pointer");
        $('#bgImgOverlay').click(function() {
            $("a[rel='gallery-all']").colorbox({open:true});
         });


How do I hide the title when creating/editing a specific type of content? Here's what we'd like to do when create/edit node of specific type of content (we have 2 specific types, let's call them "type A" and "type B"):

hide the title (= the user can change all fields but not the title)
show a combo box to choose an item (lot of items, and this field is a long name)
depending on the type of the content, when validating the node, update the title like this: title = name of the item + " - " + type of the content

Example:

User creates a node of "type B". He chooses the item called "The item XYZ long name" and validates => the title of the node is auto-magically created: The item XYZ long name - Type B.

Any idea how to do this (I don't know how to hide the title when creating/editing a node as well)?

A great module you can use is Auto NodeTitle :

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

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

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


Matching content with views I have 2 roles. Each role can create a certain content type. Both content types are using the same taxonomy terms in several fields:

Content type 1: Project
- Field: Service Type (Term reference)
- Field: Cost (Term reference)

Content type 2: Preferences
- Field: Service Type (Term reference)
- Field: Cost (Term reference)

Role 1 can create unlimited projects (1:n), while role 2 can only create 1 preferences node (1:1).

Now I want to create a view for role 2 users, displaying all the projects that match their preferences. I know this is done by certain relationships in the view. I just can't figure out which ones to set.

Thoughts?

You'll need a relation from the 'settings node' to the taxonomy term, and then from the taxonomy term to all other nodes.

The corresponding relations are called Content: Taxonomy terms on node and Taxonomy term: Content with term (which only becomes visible after adding the first one).

From there you can apply filters to the nodes. The relations you select for the filters distinguish between the base node and all linked nodes.


Cannot use the alias "/libraries" I am trying to make a node have the alias "/libraries" but I get a Page Not Found error which looks to be returned before Drupal has fully bootstrapped (I don't get the usual Drupal 404).

I checked a few other sites and they seem to have the same issue. Is there some reason why I cannot use this alias in Drupal? Would it have anything to do with a "libraries" folder in the root of the project?

Edit: It does appear to be because I have a "libraries" directory in the docroot which contain various JS libraries for CKEditor and other modules that need them.

So what is the fix here? I assume if I change the directory to anything else, those plugin paths will break. I could add Libraries API maybe, but I don't know the status of that module, but it still means any module that has a libraries.yml file that looks for /libraries..../file.js still won't work.

In this actual case, /libraries is a View (or could wind up being a node with a View block on it) that lists all libraries in the system, and thats what I want the URL to be.

For anyone looking in the future, this will solve it.

Add this to your htaccess file:

# Allow the alias "/libraries" to work without breaking actual assets in the libraries directory.
RewriteRule ^libraries$ /index.php [L]

Just before this block:

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

I also had to add an .htaccess file to the libraries directory. Inside of that, I had to do:

DirectoryIndex ../index.php
DirectorySlash off

Now I can create an alias for /libraries and not introduce and endless redirect loop, and physical assets (CKEditor plugins) can still be loaded correctly from this directory.


Ctools multistep form cache I, like other people on here it seems, have been trying to build a multi-step form using this tutorial about how to use the Ctools wizard to do so. My ultimate goal is to replace the registration form with my own multi-step sign up. The problem I am having is that at the moment I am mostly just 'regurgitating' the information on that tutorial link, without truly understanding how the data is passed between the forms, or the manner in which it is stored.

I've read some of the comments on that page and it seems to indicate that the cache object is overwritten after passing through each step, which is no good to me.

The tutorial never really touches upon the submit process and how you access the form items you've created throughout the steps. I know what I want to do with all the information when it's collected and ready, but I think I'm still a little fuzzy on how you retrieve the information.

If anyone has any knowledge about how to use the Ctools multistep wizard so that I can understand and process the user inputs, that would be great

Thanks

I've just gone through the same thing myself, but without using CTools.

While I don't currently have time to write a comprehensive tutorial (which is what's really necessary, as most of the examples out there suck big time) - perhaps on the coming weekend - I can give you an overview of how I've done it. My scenario involves an existing form (for Entity Creation via the Entity Construction Kit).

First and foremost, I'm modifying the form via hook_form_alter(), but you can do the same thing in any form builder (for, say, a custom form). For simplicity, I'll refer to my implementation of hook_form_alter() as the 'form builder.'

The first thing my form builder does is determine the current 'state' of the form. I define 'state' as a single, distinct step of the form. I check for current state by looking for $form_state['current_state'] and defaulting it to a default (first step) state if not found.

It is important to understand that the data in $form_state will persist between steps of the multi-step, so when we trigger the rebuilding of the form, we can see what state we came from and act accordingly. So, we've set the $form_state['current_state'] to a default state (step1) and added the form elements we wish to display for this state into $form. (If you have other elements in $form which you don't want to show, set their #access property to false.) Now we can view the form and see our elements - great.

The next step is adding a new state and switching to it upon form submission. When the form is submitted, our submit handler looks at $form_state['current_state'] and figures out how to proceed. We can look at $form_state['triggered_element']['#value'] to figure out which button was clicked to submit the form, and act accordingly. Let's say our button in step1 was 'Next,' we can identify this click in the submit handler and do the following:

Save the current form values ($form_state['values']) into $form_state['step1_values'].
Change $form_state['current_state'] to be step2.
Rebuild the form by setting $form_state['rebuild'] = TRUE;

When the above events happen, the form builder will be called again, and now your $form_state['current_state'] will be set to step2, so you can identify this and show different form elements. Rinse and repeat for more form steps.

The tricky part I encountered was moving 'back' to a previous state and re-populating the form with previously submitted values. For some reason I had the impression that this would work 'automagically, because Drupal,' but no dice, I had to do it manually. This is no simple task, but (luckily for you!) you can get away with a single line of code:

form_set_defaults($fields, $values, $form);

... where $fields is an array of machine names for the fields you want to populate, $values is the data you saved in $form_state['step1_values'], and $form is the current form, which is accepted by reference and modified. As for the function itself, it's available as part of the form component in my DevTools module.

Disclaimer: form_set_defaults() was only tested in my own use case of a textfield, textarea, a series of checkboxes (referencing a taxonomy), and a couple FiveStar widgets. Your mileage may vary.

This should get you most of the way there!


Moving PayPal Payment iFrame to Checkout page The Problem

Hi, I'm trying to move the payment iframe from its own page to the main checkout page so that I just have a one page form for checkout. I followed the directions here but wasn't able to get it to work (ie. I moved the 'review' section to 'disabled' and move the 'payment' section to 'checkout' in configuration).

The Current Status of My Situation

I'm using the Drupal Payflow Link module, and I have all my items in my checkout pane in store configuration. However, when a user goes to the checkout page they fill out all their information and also choose what payment method they want to use, but the actual entering of the payment information (credit card for example) still happens on the 'next' page. I want everything on ONE page.

Question

Anyone know how to make this happen with PayPal Advanced Payments/PayFlow Link so that entering the credit card details also appears on the main checkout page?

This actually just isn't possible. The iframe depends on having a completed order object, which you can't possibly have (or know for certain) if it's on the same page as fields placed to collect user input to complete that order. The same is true for all redirect, tokenized, or iframe based payment solutions.


How to create a view area handler I'm building a Drupal Commerce store. On cart view I need to display some additional information.

I want to create area handler like Commerce Order: Total. It should do some php logic and display the results.

Can anybody give me some advice how to build such a handler? The documentation didn't gave me much information.

You need to create a custom module and override default area handler using hook_views_data_alter().

The default implementation of order total handler placed here.


Why is form submit handler not called when calling form_set_error? I want to know where in Drupal documentation it is listed that submit handlers are not called when form_set_error has been called.

I don't see it in form_ser_error api, nor in FAPI Quickstart guide and FAPI reference.

Looks like I'm missing some simple thing.

submit handlers are only invoked if there are no validation errors. Calling form_set_error() results in a validation error.

From the quickstart guide that you linked:

1. A submit function is called only if a submit button was present and exists in the $_POST, and validation did not fail.


Basic "empty" entity type? Is there a module that provides an empty entity, to which I can add my own fields. I guess it would include just an Entity-ID as a primary field, and work with other entity modules.

For me, nodes have too much baggage included: title, nid, vid, publishing options, author and date.

You should really check out the Console project.
https://www.drupal.org/project/console

It allows for command line creation of modules, and will generate entities for your module.

Here's a video explaining it all in 5 minutes.

https://www.youtube.com/watch?v=agcqTEr5_48

navigate to the modules directory in the drupal root in your command line tool

enter command: bin/console generate:module enter the name for your module

enter a machine name for your module hit enter for the default path

enter a description hit enter for defaults for rest of questions

enter command: bin/console generate:entity:content

enter the name of the module you just created

enter a class name for the Entity you are creating


How to make PHPUnit test in a Module? I'm not very much knowledgeable about making PHPUnit and Drupal testing setup.

I am having problems regarding database calls.

I tried to setup phpunit test.

Inside my module/some_module. I installed phpunit by running

composer require --dev phpunit/phpunit ^8

This is my module/some_module/composer.json

{
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "require-dev": {
        "phpunit/phpunit": "^8"
    }
}

This is my module/some_module/tests/SampleTest.php

<?php

use PHPUnit\Framework\TestCase;
use Drupal\nat\Controller\SampleController;
use Drupal\Core\Controller\ControllerBase;

final class SampleTest extends TestCase
{
    public function testCanFilterData(): void
    {
        $this->getMockBuilder(ControllerBase::class)
            ->getMock();

        $class = new ReflectionClass(SampleController::class);
        $method = $class->getMethod('filterData');
        $method->setAccessible(true);

        $obj = new SampleController();
        $args = [1, 2, 3];
        $method->invokeArgs($obj, [$args]);

        print_r($foo);
    }
}

This is my module/some_module/src/Controller/SampleController.php

<?php

namespace Drupal\some_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class SampleController extends ControllerBase {
    public function index()
    {
        $ids = [1, 2, 3]
        $data = [];

        $data['some_data'] = $this->filterData($ids);

        return [*
            '#theme' => 'test_template',
            '#data' => $data,
          ];
    }

    private function filterData($ids)
    {
        $connection = \Drupal::database();
        $query = $connection->query("SELECT
                id, name
            FROM products
            WHERE id IN (:ids[])",
            [
                ':ids[]' => $ids,
            ]
        );

        return $query->fetchAll(\PDO::FETCH_ASSOC);
    }
}

When I ran phpunit tests/NatTest.php, I am getting this error:

1) NatTest::testCanBeCreatedFromValidEmailAddress
Error: Class 'Drupal' not found

So my question is how can I test this? I can't mock Drupal because I actually want to execute a database query from Drupal. How can I do this?

Automated tests describes the different tests and makes clear which test should be used, in a Drupal environment. In particular, it says:

Unit tests: Test functionality of a class if the Drupal environment (database, settings, etc.) and web browser are not needed for the test, or if the Drupal environment can be replaced by a "mock" object.
Kernel tests: Test functionality of a class if the full Drupal environment and web browser are not needed for the test, but the functionality has significant Drupal dependencies that cannot easily be mocked. Kernel tests can access services, the database, and a minimal mocked file system, and they use an in-memory pseudo-installation. However, modules are only installed to the point of having services and hooks, unless you install them explicitly.

If you are testing a class that should insert data in the database, the test should be a Kernel test, which means:

The base class of the test should be \Drupal\KernelTests\KernelTestBase
The namespace of the test should start with (in your case) \Drupal\Tests\some_module\Kernel, and it should be placed in the some_module/tests/src/Kernel directory or a sub-directory

For example, the DatabaseBackendTagTest class implements a Kernel test that accesses the database.

  public function testTagInvalidations() {
    // Create cache entry in multiple bins.
    $tags = [
      'test_tag:1',
      'test_tag:2',
      'test_tag:3',
    ];
    $bins = [
      'data',
      'bootstrap',
      'render',
    ];
    foreach ($bins as $bin) {
      $bin = \Drupal::cache($bin);
      $bin->set('test', 'value', Cache::PERMANENT, $tags);
      $this->assertTrue($bin->get('test'), 'Cache item was set in bin.');
    }
    $connection = Database::getConnection();
    $invalidations_before = intval($connection->select('cachetags')->fields('cachetags', ['invalidations'])->condition('tag', 'test_tag:2')->execute()->fetchField());
    Cache::invalidateTags(['test_tag:2']);

    // Test that cache entry has been invalidated in multiple bins.
    foreach ($bins as $bin) {
      $bin = \Drupal::cache($bin);
      $this->assertFalse($bin->get('test'), 'Tag invalidation affected item in bin.');
    }

The code shown in the question just reads data from the database. (I don't see code writing the database.) Keep in mind that the database used from tests isn't automatically populated; if the purpose of the test is verifying the controller outputs the correct data, the database table needs to be filled with the data. That is normally done from the setUp() method, which could also initialize a property with the connection (for example with $this->connection = Database::getConnection();) if the data is the same for each test, or at the beginning of the test method, if each test needs different data. (For example, testCanFilterData() could test the controller filter the data in the database and testCanFilterWrongData() could test the controller doesn't output completely wrong data or out-of-the-set data.)


How do I conditionally override views cache using preview? I'm attempting to embed a view but need to disable the cache in this instance while leaving it enabled in other instances. I'm attmepting to do this using code but nothing I've tried seems to work. Here is my code so far:

  // Get the view and attach the handlers with the build call
  $view_object = views_get_view($view_name);
  $view_object->set_arguments($view_args);
  $view_object->build($view_display);

  // Manually editing the cache here does nothing
  //$view_object->display_handler->options['cache']['type'] = 'none';

  // Override option breaks the view object and the get plugin does nothing.
  $view_object->display_handler->override_option('cache', 'none');

  // Prints tell me that the previous two lines have not actualy changed the cache method.
  dsm($view_object->display_handler, 'display handler');
  dsm($view_object->display_handler->get_plugin('cache'), 'get plugin cache');

  // Returns the cached copy of the view despite changing the option.
  $view_object->execute($view_display);

Any views experts out there know how to override this cache option?

ADDITION:

This works:

$view=views_get_view('to_c_or_not_to_c'); // or whatever your name of your view is
$view->display['cached']->display_options['cache']=array('type' => 'none'); // 'cached' is the display name of the view that is normally cached but here we are going to set it to none
return $view->preview('cached'); // returns the rendered html of that display (if you need arguments, they can be passed here as an array in a second argument

ORIGINAL:

May the great drupal gods strike me down for this answer, but....

$view_object->live_preview=TRUE;

will cause drupal to ignore any cache()ing that may be set and a very quick look doesn't seem to show much other side effects (other than some query capturing)


Using Drupal 8 Feeds with Xpath parser, can I concatenate two attribute values that appear in a single tag? I have a dataset content type and an xml structure like this:

<dataset>
   <purpose>blah blah</purpose>
   <abstract>blah blah</abstract>
   <authors>blah blah1, blah blah2</authors>
   <ordered-authors>
      <author>blah blah</author>
      <author>blah blah</author>
      <author>blah blah</author>
   </ordered-authors>
   <tags>
      <themes>
         <theme name="xxx" rank="1"/>
         <theme name="yyy" rank="1"/>
      </themes>
   </tags>
</dataset>

I want to get the multiple attributes of each theme tag into a form like:
xxx-1, yyy-2, etc.
which will be used as entity references for each dataset, whether as an array, or a list that I then implode via a tamper. In Drupal 7 there were "dummy" fields to hold temporary values - I could create extra fields in the content type for this purpose but so far, that hasn't helped me find any way to query the xml and/or use available tamper options to combine the nested attributes to get a usable array of concatenated values (short of giving up with the feeds interface and moving to migrate). ANY help or suggestions would be appreciated!

Well, I have a solution but it's not elegant. I used this query:
//theme/@name|//theme/@rank

and Imploded the resulting array to get theme1,rank1,theme2,rank2, etc,

then used a regex to replace every odd comma with a dash:
/(\w+)\W*,\W*(\w+)/
$1-$2

and then Exploded back to an array.

Would still like to know if there's a better alternative.


Contextual filter with a block view I have a page view("/news") with contextual filter for the topics ("news/design","news/coding"...) which are taxonomy terms and this worked fine. Due to some changes for the mobile theming, I need a block view instead of the page view, but I can't get it to work with the filters.

With the old filter settings I get all my articles in "/news", but the filter I am using changed the default value from the filter to "taxonomy term ID from url";  I now see an empty page for "/news" (this is now a simple page with the block view included) and a "site not found" for "/news/design" etc. In the preview of the view, everything works fine.

These are the settings for the view.

In general, the reason this block isn't working is that a block does not have an assigned path and the contextual filter does not have a path to work on.  To connect the block to a path return to the contextual filter settings and in the section What to do if the URL is not available select Provide default value and select Raw value from URL from the dropdown box. From the Path Component box select the position in the URL that your contextual filter gets its value.

In your specific case you have told the view to interpret the URL as a taxonomy term and that is probably not the format of your URL (taxonomy/term/tid). The Views UI is a bit misleading in that it suggests that the alias can be used in the contextual filter when it does not.  Drupal converts the alias to the base URL value when it calls the view and that is what is directly available in the contextual filter.  To use the alias you must specifically inform it as described above.  Views is powerful, but a bit tricky to use.  One tool you can use if you have some experience with SQL queries, is to turn on the display of the queries in the View preview display in the Settings tab.  This will tell you what views is trying to do when the view is called.

More can be found on this issue at this question


How do I make a single page use ssl in Drupal 7? I have a form I created with Webform, and I need it to be secure.  I don't need a login for everyone, only SSL for that one page.  Is that possible?  How do I use https:// for that one page?

Take a look at the Secure Pages module. The module enables you to:

A small process which will redirect the required pages to a SSL version of the page.

To make use of it, take into account though that your webserver / webhost will need to support SSL and it should be configured for your site.


Module conflicting with jQuery I've set up a simple hide-show.js file for my website and I'm working on a module as well.
Problem is, if my module is active, the jQuery for the page doesn't work, is there something I need to do to 'close' my module after writing or anything?

Edit: My console does not show any errors. And with jQuery I mean the functions on the page (i.e. clicking on a hide-show button does nothing).

<?php function maps_markers_init() {

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
}  else {
        $latitudes = db_query('SELECT field_latitude_value FROM {field_data_field_latitude}')->fetchCol();
        $longitudes = db_query('SELECT field_longitude_value FROM {field_data_field_longitude}')->fetchCol();

        json_encode($latitudes);
        json_encode($longitudes);

        require(drupal_get_path('module', 'maps_markers') . '/maps_API.php');
    };};?>

maps_API.php contents:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[api key]"></script>

Also, hide-show.js contents:

$ = jQuery.noConflict();

($(function(){
        $(".collapse_btn_down").click(function(){
            $(".mid_div").fadeToggle( "800" );
            $('.buurtkiezer').toggleClass('buurtkiezer_solo');
            $('.content_wrap').toggleClass('content_wrap_solo');
            $(this).toggleClass('collapse_btn_up');
            $(".legenda").css("margin-right","20px");
            $(".legenda").css("margin-top","-80px");

        });

}));

Is the issue just with the hide-show js script or is it with jquery in general? In other words, are you experiencing jquery issues all over the site after you enable the module or is it just on the page where your hide show js needs to be activated?

Overall, your question is a little vague. Just include more details and we can give you a better answer.

Lastly have you looked at the developer tools in whatever browser you are in to make sure there are no errors?


How can I check the user status of node author in Rules condition? I set Content is going to be saved for Rules Event.

And then the following code in Execute custom PHP code for Rules condition.
But it seems to return always TRUE no matter if the user account of node author is Active or Blocked.

return $author->status = 0;

How can I check the user status of node author  in Rules condition?
I would like the condition which returns TRUE when the the user status of node author is Blocked.

You need to use the double equation sign. What your code does right now, is that it assigns the value 0 to $author->status.

Here's updated code:

return $author->status == 0;


users online status issue it is a Author Status Issue: let's to show either a user is online or offline. If a user is online then it will show >Online if offline then like this >OfflineSo how to show it?

User Stats is a good basic plugin that provides this functionality within Views and Rules. Install the plugin, then add a field or filter to your views results.


Combine recent and popular items in Views I need to show 2 popular and then 2 most recent items, and again next 2 popular and next 2 recent items in Views.

Any idea how to do this?

You can create two separate views which will display two 2 popular items and  2 most recent items and use script below that will print content from these views on the page.

for ($i = 0; $i <= $n; $i = $i + 2) {
  $popular = views_get_view('popular');
  $popular->set_display('block');
  $popular->set_offset($i);
  $popular_content = $popular->preview();
  print $popular_content;

  $recent = views_get_view('recent');
  $recent->set_display('block');
  $recent->set_offset($i);
  $recent_content = $recent->preview();
  print $recent_content;
}


What date format is this? Or is it even a date? I'm working with a Drupal 8.3.6 setup done by someone else and I have a date format that doesn't make sense to me. I'm interacting with it thru MySQL Workbench.
The best I can tell,
1499287512 = Wed, 07/05/2017 - 23:02
and
1501079338 = Tue, 08/22/2017 - 06:25
BUT there's no guarantee of that.
In any event, 1499287512 and 1501079338 appear to be in a date placeholder; numbers like it appear in users_field_data.fields, created, changed, access, login.

Those are dates stored as Unix timestamps, which are essentially the number of seconds since midnight, January 1st, 1970 UTC (the epoch is 1970-01-01T00:00:00+00:00).

As far as Drupal is concerned, they are proper fields on those entities, either TimestampItem, CreatedItem, or ChangedItem fields.

Keep in mind that the timestamp always refers to that epoch and always is referenced to UTC; there is no real thing as a Unix timestamp in a local time zone.  When working with them in Drupal it is always best to use DrupalDateTime objects, and use it methods for computation (which will inherit from \DateTime).


Drupal 7 js compression generating 6 files I'm using drupal_add_js and drupal_add_library to add some js to my site. But when I turn on the drupal js compression, drupal is aggregating the files but it's generating 6 files and Yslow is saying that it's too much files. Is there any way to force drupal to aggregate more the files? It'd be great if drupal 7 generates only 2 or 3 files per page.

Surprisingly, the larger number of files can actually save bandwidth on subsequent requests, something that YSlow doesn't take into account.  Aggregating everything into a single giant file is really only optimal for visitors that load a single page and no others.

I wrote an article explaining the details in Drupal 7: Taking control of CSS and JS aggregation.

To reduce the number of files, you can try the Core Library module. The article above also has some example code that will group the files together using hook_css_alter() and hook_js_alter().


Custom Block Can't Invalid the Cache I wrote a block in Drupal 8 to render a menu based on the http headers of the request, which contains the users' information from the idp. This menu is supposed to be different from user to user, but currently it is cached once it is generated when the very first user login to the website.

I have tried setting the cache max-age to 0, but it didn't seem to work at all. Then I tried the session of the cache contexts, but still those pages visited by previous users are cached. Neither did header:custid.

Here is a sample code

class MyBlock extends BlockBase{
  public function build () {
    return array(
      '#cache'=>array('contexts'=>array('session')),
     '#markup' => ...,
    );
  }

 ...
}

Thanks in advance for any help!

I wrote a block in Drupal 8 to render a menu based on the http headers
  of the request, which contains the users' information from the idp.

If you want to build a new page for every request then there is no point in using the page cache, so I would uninstall the core module Internal Page Cache.

Edit: Just read in drupal planet, BigPipe will be available in Drupal 8.1, then you have a perfect solution for this. But in the meantime running a site without page cache for anonymous users is fine, you still have the dynamic cache and can use the cache tags.


Group result and display count in a view I want to create a view and group the result like display only 1 record and along with it display the count of the similar records along with it. Can i do it in views with out writing any code. i.e. result should look like

Football (3)

Tennis (6)

Cricket (4)

My example is based on 1 Content Type and 1 field (City).

FIELDS. Add 2 same fields in fields area you wanna group and show counter.
FORMAT. Group by required field

PAGER. Set 0 in Pager area.
ADVANCED.
Enable aggregation in advanced settings

COUNT. Enabled 'count' for second field (which is not used to group)

Sorting. Set sorting as your group field.

FINAL

This is how looks my view

RESULT


Using Entity Reference to show a view within a node I have a content type of Authors that I want to attach to the bottom of article content type. One person will be entering all the content and they need to be able to select which author box will show at the bottom of the article.

I have been able to do this with entity reference and the display shows the rendered entity. But I have a view I would like shown instead of the rendered entity and I can not make that happen. I was able to associate the author view using the Entity Views Attachment but it associated with the UID of the account signed in when the post was created how can I instead associate it with the entity reference select list field?

Assuming there is an entity reference field in articles that points to the content type "authors", and the view will be show on the article content type..

In your view, you should be able to add the relationship "Entity Reference: ReferencED entity" for that field name.

Then you can add your fields from the authors content type and make sure you point to the referenced entity in the field's settings.

You'll also need a contextual filter for NID "Provide default: Current Node".


Fatal error: Call to undefined function menu_load_all() I have (D7) code that uses menu_load_all() to get a list of menus to pass as options for checkboxes to the admin interface of a module I'm writing.

To test and make sure my little snippet was returning the correct values for menu titles, I pasted it into a block of eval'd code in the content of my staging site, and it was fine. It returned a nice little array of titles and so I straight copy/pasted it into my module's code.

Now when I enable my module, I get this error:

Fatal error: Call to undefined function menu_load_all()

WTH? Why did this work in eval'd and not in my module, and what do I do to get my module access to this API function?

Full code of module available for your perusal.

The only thing I can of is that you're calling menu_load_all() in hook_install() or hook_enable(); all system module files aren't necessarily included when those hooks are invoked.

If that's the problem, you can force the file with the function to be included by adding the following line of code to the top of your hook_enable()/hook_install() function:

module_load_include('module', 'menu');


How to restrict completion of only one field within a field group Is there a simple way to have several fields within a field group; such a way that only one field in the group can be populated.

Example use Case
Field group is called 'Insert Media'.

The group contains
- an image field
- an audio field
- a video field

The user may complete one field, but can not complete multiple fields within the group.

I have not expressly done the exact use case you've requested. I recommend you look at the following blog post describing the Drupal States API, including newer additions made to that API for ORing and XORing conditions:

http://www.metaltoad.com/blog/drupal-7-form-api-using-states-multiple-conditionals-and-or-and-xor

For simple multiple-condition clauses the States API follows this convention:

'[field-selector]' => array('[evaluate]'),
'[field-selector2]' => array('[evaluate]'),

For more complex conditional logic you can write the following array structure:

array('[field-selector]' => array('[evaluate]')),
'[OR/XOR]',
array('[field-selector2]' => array('[evaluate]')),

Be aware that the version of jQuery being used on your site could be important for these conditionals to work (again see the blog post).

If the above does not meet your needs I recommend you look at the Field Conditional States module:

  The working states that are supported by FCS are:

  visible / invisible - Hides/Shows a form element
  enabled / disabled - Grays out a form element
  required / optional - Makes a form element required to be able to submit the form
  checked / unchecked - Checks/Unchecks a checkbox (of course only applicable to checkboxes)

  Fields to which these states will be applied, are called target fields
  or controled fields.

  To trigger these states there is a different set of trigger states
  (not to be confused with the states described above) that will trigger
  a state when applied to a control field:

  empty - Triggers when the control field is empty
  filled - Triggers when the control field is not empty
  checked - Triggers when the control field is checked
  unchecked - Triggers when the control field is not checked
  value - Triggers when the control field's value is equal to a given string
  !value - Triggers when the control field's value is NOT equal to a given string

  All of them are supported as long as they make any sense for the
  widget of the used control field. For example it doesn't make any
  sense to wait for a text field to be checked or for a checkbox to have
  the value "Hello World". So most (if not all) fields will only use a
  subset of these trigger states.

Note: that the states api and the field condition module are clientside modules -- they don't enforce the validation on the server. You'll likely also want to use a custom form validation function to assure that only 1 field is provided upon form submission.


How to display multiple nodes of a content type on a page displaying a parent node? I have a content type called PRODUCT.  Each of these product's has an entity relationship to one or more other PRODUCT items that are similar.  When a user views a PRODUCT, using the themed output for that PRODUCT, I would like to display the other similar PRODUCT's below it.

Initially I used the entity full item display option in the content output and that worked fine, but I really need each node in a  tag of its own and not have the one product group the related product items under it in the output which is what the entity display filter does.

Entity Display Output....

  ...

     ...

     ...

But what I would like is the following.

  ...

  ...

  ...

Where is the best option to create this type of output?

Just use a Views Attachment to attach another view After your first view.

Another similar option is the Entity Views Attachment module:

  "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

  The placement of the view in the entity's content can be reordered on the "Field Display" administration page for that entity, like other fields added using the Field UI module.

So the nice thing about the EVA module is that it allows you to easily place and manage the View from the Field UI of your content type. Thus, making the administration of this tacked on view a little bit easier for site administrators.


Filter Criteria "Workbench Moderation: Current" only works on published revisions? I added the following filter criteria to a View:

Workbench Moderation: Current

However, after not seeing the output I expected, I realized that this filter only displays a revision if the revision is both current AND published. If a draft is currently current, then it is ignored by the filter.

Is that a bug?

Thanks,

Stephen Gilson

I found the answer in this post: https://drupal.org/node/1947732

From that post:

"The key is when you create the view, you need to set it to show content revisions rather than content. They mysql query used when showing content revisions is different than when showing content. One pulls data from the node table, the other pulls from the revisions table. The latter is what you want when dealing with revisions. In my testing so far, the Workbench Moderation: Current filter works fine in a content revision view."


Get the default value of a variable I want to display the default value of a variable when no value is set. I checked the Drupal 8 documentation pages, but I couldn't find any information about the default value.

In Drupal 7 if variable value is not set then default value is displayed.
variable_get('variable_name', 'hello');

If "variable_name" is not set at that time, hello will be returned.

Now for Drupal 8 I am trying the following way.
$config = $this->configFactory->get('module_name.settings');

$config->get('variable_name', 'hello'),

I am not getting hello.

Your module ships with a default config; it gets installed. Now your config has the default value; if someone overrides it, it doesn't have one anymore. $config->get('foo') doesn't have a default value.


Debugging #AJAX and FormAPI What is the easiest way to view current $form_state variables while working with #ajax?
Is there a way I can get dpm() to update automatically on each AJAX load?
If it matters, I'm testing AJAX on a Node Submit form.

Using dd($form_state); within the callback function works beautifully.

On linux you can tail -f /tmp/drupal-debug.txt to see the $form_state in real time. (Or whatever the temp directory for your site is set to, often something like sites/yoursite.com/files/tmp.)

Otherwise, you can find drupal-debug.txt in your systems /tmp/ directory.
http://ratatosk.net/drupal/tutorials/debugging-drupal.html#dd


How can I change the name of migration database in database array? For a Drupal migration from d7 to d8, I have to define my source database to be called 'migrate' in the settings.php as below. My question is: how can I define the source as something other than 'migrate',  where is that set up?
`$databases['default']['default'] = array(
  'database' => "db",
  'username' => "db",
  'password' => "db",
  'host' => $host,
  'driver' => "mysql",
  'port' => $port,
  'prefix' => "",
);

$databases['migrate']['default'] = array(
  'database' => "drupal7",
  'username' => "db",
  'password' => "db",
  'host' => $host,
  'driver' => "mysql",
  'port' => $port,
  'prefix' => "",
);`

migrate is the default key used by the SqlBase class which is the base for the D7 source plugins. Its documentation explains in detail how it determines what key to use and how it can be changed. Of relevance:

As described above, the default source database is $databases['migrate']. If the source plugin needs another source connection, the database connection parameters should be added to the $databases array as, for instance, $databases['foo']. The source plugin can then use this connection by setting 'key' to 'foo' in its configuration.

So update the source.key value in your migration configuration to foo then re-import that configuration to change the default key used for that migration source.


View filter based in text not in number I have a field in an entity that is an Entity Reference with widget Select list.

I have created a view and I want to be able to filter by that field in text format, but when I try to configure the filter I get the options to do it as if it were a number (is less than, is equal to...) and not as a text (contains, start with...).

Any idea of what I am doing wrong?

Edited:
Here is screenshot of the filter:

Thanks!

Entity reference fields store the ID of the referenced entity. They don't store anything else about the referenced entity.

You have an Entity reference towards nodes and the data that the ER field stores is the node ID. That is why when you add a filter for that ER field you get the "number" options, because the ID is a number/integer.

But there is a way to add a filter that filters results based on other properties of the referenced entity. When you need extra information you add the Relationship based on the ER field. This introduces all other available info about that entity into your Views.

In your case, you want to add the Relationship for your ER field (Content referenced from fiscal_certificates). Require it if you only want results that don't have that field empty.

After you add the Relationship you can add the Title filter, but make it use the Relationship for the ER field. Title is a text field so you'll get the text options (Contains...).

If you don't use a Relationship on that filter it will search through Titles of your "original" items, but if you use the ER Relationship it will search through the referenced node titles.


Returning code in views search tpl but ONLY if user clicked 'search' button and results were returned I have a Views-based search page on my site. I've created a views-view-search--tpl.php file to customize the order of elements on the page. I have a specific block I'd like to return but ONLY if a user has already clicked the search button and results were returned.

Here's the code I'd like to return based on that condition:

  <?php if ($feed_icon): ?>
   <div class="feed-icon">
    <?php print $feed_icon; ?>
   </div>
  <?php endif; ?>

I guess I probably need an 'if' statement or something before that block but I'm not sure how to reference if results and/or if user clicked the search button...

Anyone know how to do this?

This should probably be done in a pre-processor rather than a template file, but I'll stick to the question as asked, for now:

<?php if (!empty($view->exposed_input) && !empty($rows)): ?>
 <?php if ($feed_icon): ?>
  <div class="feed-icon">
   <?php print $feed_icon; ?>
  </div>
 <?php endif; ?>
<?php endif; ?>


How do I programmatically add text to a page? I am starting to write my first drupal module, but I need help on how to add content / text / data to the screen? I was able to add tabs and a url with hook menu, but I am unsure of how one goes about adding data you want to put there. If I wanted to say "hello world", what function / hook do I use to do that?

function sky_view_menu(){
    $items = [];
    $items['admin/skyview'] = array(
        'title' => 'Skyview Settings',
        'type' => MENU_NORMAL_ITEM,
        'access callback' => TRUE,
    );
    $items['admin/skyview/tab1'] = array(
        'title' => 'Skyview',
        'type' => MENU_DEFAULT_LOCAL_TASK,
        'access callback' => TRUE,
        'weight' => 0,
    );
    $items['admin/skyview/tab2'] = array(
        'title' => 'test1',
        'type' => MENU_LOCAL_TASK,
        'access callback' => TRUE,
        'weight' => 1,
    );
    $items['admin/skyview/tab3'] = array(
        'title' => 'test2',
        'type' => MENU_LOCAL_TASK,
        'access callback' => TRUE,
        'weight' => 2,
    );
    return $items;
}

You're looking for the page callback, which is:

  The function to call to display a web page when the user visits the path. If omitted, the parent menu item's callback will be used instead.

For example:

function sky_view_menu() {
  $items['admin/skyview'] = array(
    'title' => 'Skyview Settings',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => TRUE,
    'page callback' => 'MYMODULE_skyview_admin_page',
  );

  $items['admin/skyview/tab1'] = array(
    'title' => 'Skyview',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'access callback' => TRUE,
    'weight' => 0,
    'page callback' => 'MYMODULE_skyview_admin_tab_1',
  );
  ...
  return $items;
}

function MYMODULE_skyview_admin_page() {
  return [
    '#markup' => t('Hello world'),
  ];
}

function MYMODULE_skyview_admin_tab_1() {
  return [
    '#markup' => t('Hello tab 1'),
  ];
}

The function name itself is arbitrary, but for the sake of sanity it's best to name it as something that represents the route behind it.


Custom Key Value fields in a content type I am searching for functionality similar to the Double Field module only for Drupal 6.

Does anyone know of a suitable module or if not, could you outline an approach to creating this functionality?

Thanks, apologies if this is poorly explained.

I realise I'm answering my own question here but I've done some digging and come across the TableField module.

Does anyone have any experience with this?

It appears to do something along the lines of DoubleField.


Fixed Image into a View (Drupal 6) I would like to know if it's possible to put an fixed image into a dynamic View in Drupal 6, it'll be something like that:

[exposed filter]

[fixed image]

[view field 1]

[view field 2...]

Thanks.

I assume you want to add this image for each view row?

Then you would need to add "Global: Custom text" as a new field, and put your image HTML into it.


Node titles disappear sometimes when using tokens with Autonodetitles There are instances where the node titles disappear for updated nodes. The site uses organic groups with APC for caching data. The drupal version installed is 7.18 however most modules including entity, token, entity token etc are up to date. The site has few custom modules and rules enabled but they do not affect the node title. I suspect there may be issue with cache which results in instances when node titles are not populated. Please do suggest ways in which I would be able to figure out the exact issue.

Upraded the site to latest version of Drupal. The problem got resolved automatically.


Field Collection Views and Blocks I've assembled a content type with a Field Collection (image, text and link). I installed the Field Collection Views module and duplicated the view it came with. I added a block display to the view and in the Content Display set the name to the view machinename and the id to the block machine name.

It works fine on my node page but the block won't show up when I place it on the page. How do I go about getting it to render?

Turns out I was going about this the wrong way. I didn't need the "Field Collection Views" module. In views I chose relationships and added "content: the_name_of_my_collection_field" then I could just add the fields to the view like normal.


CKeditor doesn't format the body value I am building a website in Hindi language. I was given a Database containing rows of title and body. I created a node for each row using this code :

$query = db_select('hindi', 'n')
      ->fields('n', array('title','body'))
      ->execute();

foreach($query as $item) {
    $title = $item->title;
    $body = $item->body_value;
    $values = array(
        'type' => 'article',
        'uid' => 1,
        'status' => 1,
        'comment' => 0,
        'promote' => 0,
        'language'  => 'hi'
    );
    $entity = entity_create ('node', $values);
    $ewrapper = entity_metadata_wrapper('node', $entity);
    $ewrapper->title->set($title);
    $ewrapper->field_body->set(array('value' => $body,'format'=>'full_html'));
    $ewrapper->save();
}

The nodes are display very well in the node view page, like this

But Ckeditor  doesn't perform the text formats (line breaks and ...). Like this

What is the problem?

More information

This is the result of Firebug when inspecting the Body value of the CKEditor

According to my experience
 causes this problem ,my solution for this is to replace all
 with
  before saving in body field

So try

$body =   str_replace("
", "
",nl2br($item->body_value));


How to add multiple terms to a taxonomy via feeds and tamper I am importing nodes with taxonomy terms for one vocabulary. I have a set of terms that I would like to use that are set up with their own columns.

I know feeds tamper can explode a set of data in one column using a delimiter and apply that to a term, but I need each taxonomy term to be in it's own column. This is easier for readability for the people who are setting up the database.

How can I do this?

Thanks!

Feed Tamper gives you a feature to import multivalued field data using any separator like comma(,) using implode plug-in

If you have csv file like below

You need add implode plugin for that field in tamper tab in feeds form

For a detailed tutorial refer this Awesome link!!!!


Using only alias URL for a page If I've got a page that originally has a node (ie node/20) for the URL and then if I've assigned its own custom URL (ie website.com/landingpage) I'm finding that I can still access the page by using its node number.
Ideally I'd like to have it so a user can only access the page via the custom URL and never the node so is there a way I can configure a node so it cant be used in the URL to reach the page?

You can use the Redirect module for this: https://www.drupal.org/project/redirect


How to re-run javascript core code for content loaded with jQuery's ajax()? I'm trying to AJAXify page loads using .load()/.get() methods and the main problem I'm currently stuck with is that the loaded content isn't being processed by the relevant javascript code.

I've tried upgrading to jQuery 1.7 and addind this scary workaround: https://stackoverflow.com/questions/11442723/how-to-convert-bind-pass-through-to-on-to-delegate-like-right-inside-jqu , but the problem is not in the bind() calls AFAIU.

Something with Drupal.behaviors?

The simplest way to reproduce the issue is to take a page's #content.innerHTML that is normally being processed by JS (/admin/structure/block) and replace the #content HTML with it. This way the resulting HTML is the same but [for me] it's not processed by JS functions.

Looks like Drupal.attachBehaviors(jQuery("#content")[0]); is working. Some issues still exist though. Like the absence of relevant behaviors when loading from different page.

Taken from https://drupal.stackexchange.com/a/3193/7177


Problems with Contextual Filters & Menu Tabs I have created a collection of views (base) that collects identifies a category of articles and a second single view (tabs) that creates tabs to filter the content into sub categories for all base views using contextual filters.

I have created two vocabularies to contain terms for Section and part.
A sample base uses the path /division/SectionTerm.
The path for the tabs view is /division/%1/part.
Each page of the tabs view has a filter to a specific part term.

The idea is to have a series of menu tabs that display different related content related to a section.  This works fine in a test without the contextual filter, but the tabs do not show when I change to contextual filters for the tabs view although the preview is showing correct results.

I am having a similar problem having a view block using relations appear.  See separate question post.

I am doing something similar, I think, but it is driven by Taxonomy Menu.  For what it is worth (for any other researchers), I have set a contextual filter and a relationship:

Contextual filter settings:

And my relationship (see 1st screenshot) setting is just default:


Theme the landing page after saving new content I have a content type Testimonials and like any other type, it gets displayed after you save it. Is it possible to theme that page into something that says Your Testimonial has been saved! instead of displaying the data? I only need this for this specific content type.

EDIT: @googletorp
Am I doing this correctly? I placed this code in my custom module enchance.module (activated) but I'm still getting the same page: the full version of the published testimonial instead of being redirected to <front>.

function enchance_form_alter(&$form, &$form_state, $form_id) {
    //dpm($form);
    if ($form_id == 'edit-testimonials-node-form') {
        $form['#submit'][] = 'testimonials_redirect_success';
    }
}

function testimonials_redirect_success(&$form, &$form_state) {
  // Use the drupal_set_message solution.
  drupal_set_message(t('Your Testimonial has been saved!'));
  // Redirect to custom page solution
  $form_state['redirect'] = '<front>';
}

// I'm not being redirected to <front>

with hook_form_alter you could for the form for the node type add a submit handler that will redirect to a custom page. Alternatively you could use drupal_set_message.

function module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form id for the node form') {
    $form['#submit'][] = 'my_custom_submit_handler';
  }
}

function my_custom_submit_handler(&$form, &$form_state) {
  // Use the drupal_set_message solution.
  drupal_set_message(t('Your Testimonial has been saved!'));
  // Redirect to custom page solution
  $form_state['redirect'] = 'url/to/page';
}


How to fix incorrect forum post count when using internalization and locale? Using (among several other contrib modules)

Forum
Locale
Advanced Forum
Internationalization

My forum topic nodes are set to be localized and I've set translations for the Forum Vocabulary and all the terms. The forums work well with Internationalization after I modified some of the views and added a 'Content: Language (= Current user's language)' filter.

However the Topics count in the main forum page is incorrect, it doesn't take into account the language, so we  see a higher count than we should.

For example:
https://freshwaterwatch.thewaterhub.org/forum

The 'Meet & Greet' forum has five topics but when you enter you only see two topics: https://freshwaterwatch.thewaterhub.org/forums/meet-and-greet

What happens is that if you click on the French language you see one and two more in the Spanish language, that's why the count for the forum is 5 but you should instead see a count of 2 when browsing the site in the default english language.

Does anyone know how to solve this or a workaround?

Look at advanced_forum_statistics_topics (check your advanced_forum version)

return db_result(db_query('SELECT COUNT(DISTINCT(nid)) FROM {forum}'));

You can use preprocess forum_statistics and instead of advanced_forum_statistics_topics(); use your own function to select only nids which relate to the current language.


How to give user opportunity to select attribute by checkbox I use exposed filters in Views to give user opportunity to chose attribute of product. After his checking filtering starts automaticly.
But problem is that format for chosing is drop menu. Is it possible to use checkboxes or radio buttons? It will be more userfriendly....

Better Exposed Filters seems to be module you need:

  The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively. Description fields and Select All/None links can be added to exposed filters to make for a better user experience.


Entity View Attachments (EVA) with multiple contextual filters? I have the following content types which are also organic groups;

Country (group)
Region (subgroup of country)
Area (subgroup of region)
Neighborhood (subgroup of area)
Facilities (subgroup of Neighborhood)

I have a a leaflet map view as an Entity View Attachment with these Entity content settings;

Entity type: Node
Bundles: Country
Arguments: id

I would like create country maps showing all of its corresponding subgroups ie: Regions, Areas, Neighborhoods and Facilities.

Unfortunately I have only managed to get the "Region" content type appearing on the map using the "OG membership: Group ID" as a contextual filter argument and using "current og from context" for "When the filter value is NOT available".

Any ideas for how I can use multiple arguments?

Querying the configured multiple contextual filter isn't working as i expected first and I spent lot of time to figure out why, then finally the solution was found:

Instead of Content: The name of Taxonomy (taxonomy_vocabulary_#) you need to select Content: Has taxonomy term ID Contextual filter and enable Allow multiple values to able to use multiple values in the form of 1+2+3 (for OR) or 1,2,3 (for AND).
If You have another Contextual filter configured, you can separate the query with "/".


Generate unique ID in hook_redirect_form I'm trying to write custom payment method for a custom bank gateway (off-site method). bank service expect me to send unique ID for each pay request per bpPayRequest() call.

currently I sending $order->order_id, but its wrong because: if first request fails this orderId is not unique for second bpPayRequest() call. so I should create unique ID which is related to $orders. Is there any commerce way for this question?

$parameters = array(
  ...
  'orderId' => $order->order_id,
  ...
);
$result = $client->call('bpPayRequest', $parameters, $namespace);

$unique_id = $order->order_id . '-' . microtime();

The advantage of this is you can explode on the - later and get the order id back again.


How do you change rules settings on the fly? I want to be able to modify a rule based on a setting choice made by a user, but I don't want to expose the form for setting the rule that you see at

admin/commerce/config/payment-methods/manage/<payment_method>/edit/<action_id>

because it contains some sensitive information such as our company's secret key for connecting to the payment gateway.

I have figured out that this UI is governed by a rule, and this particular setting is stored in the rules_config entity in its data field.  I want to be able to directly manipulate this field, but I am unfamiliar with the format and do not want to mess up the entire rule.

Is there a way to do a entity_import and change the rule with the new settings on the fly?  It seems like all of the hooks are only for when the module loads/installs.

There are likely several ways of peeling the proverbial potato, depending on what you're actually trying to do:

See if the rule's callback function has some sort of hooks to allow you to change the data there. This is the easiest way to do anything and the least invasive.
Implement hook_rules_config_execute(). This hook gets called during the invocation of the rule and it appears to give you a chance to modify the rule before everything gets executed.

Not generally recommended but also possible:

Alter the rule's callback to call a new custom callback which wraps or replaces the original function and sets the configuration that you want.


Disabling text field for all users / roles is there an easy way to disable (readonly) fields in the backend for ALL users and roles (also superadmin).

I already found a module -> https://www.drupal.org/project/disable_field but this module allows superadmins to edit the fields.

Why do i need this?

Because the 5star rating module isn't ported to D8 yet i need a solution to realize a 5star voting in D8 with the vote data (5star rating) from an old drupal installation.

My thought was to work with a field collection, where i want to import the main 5star rating values from the old site into the new installation.

Afterwards i want to build a custom 5star voting.

The users should not be able to change this values in the field collection.

Any ideas?

Regards

M.

I don't know why would you need to disable any fields in the first place (that's not turns out from your post), but if you need 5 voting field, you could easily create it:

You may need just a part of them or all of them:

Creating a custom Field


Composer does not install Calendar Module Hi I am having trouble migrating my local site to development (two seperate servers). I believe the reason being is because I can not install an unstable Calendar Module, which I have on my local but not on my development. In my development site I git pull successfully and checked the repo https://www.drupal.org/project/calendar/releases/8.x-1.x-dev was running. I did composer require 'drupal/calendar:1.x-dev'. I also have "minimum-stability": "dev" in my composer.json.

When I run drush cr I get:

  [error]  The "calendar" plugin does not exist.

So it seems that I do not have calendar module downloaded. I check my composer.json file and have

"require": {
    "drupal/calendar": "1.x-dev"
},

but when I run

composer update

I get

./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

and nothing gets downloaded. Am I missing anything?

Any help or pointers would be helpful! Thanks in advance.

Is the module installing and working locally? I've had a similar issue with dev modules before. The problem is that they will ship with a .git directory and sometimes when I try to commit the module to my project's git repo it won't be committed because of the .git in the submodule. I bet if you navigate to the calendar directory on your server it will be empty.

A solution to this is to remove the .git directory from the submodule, e.g. /modules/contrib/calendar/.git before committing to your project's repo. If you've already committed, git will probably still try to ignore the directory after you remove the .git from the submodule, but you can remedy this by using git rm -r --cached modules/contrib/calendar (or whatever appropriate path). Then you can git add and git commit the submodule.