allow user to set some css settings through UI The user wants to be able to choose some sizes and colors for the look of the site. These are css rules. I have a vague vision how this could be done by a module, but maybe there is already something like this?

What I need is to have some form with fields as combo boxes, allowing the user to choose from several values. E.g. allow him to choose from {red, blue, yellow} for the "Background of the News title", which happens to be .news-header-background class.

After he saves, the module would re-create a user.css file which is loaded as the last file in the theme (so it overrides my theme settings).

So the tasks for each role are as follows:

the user fills the fields on a form choosing from pre-defined values
the administrator pre-defines these values and also assigns a css selectors to each field in the form (directly in files, no need for GUI for this)
the module re-creates the css file

One important point is that the interface exposed to the user must be dead simple. No technical jargon, no options, only text that he fully understands, like "Background color of the News title". Second point is that the values he can choose are presented as combo boxes, so they are limited. Third point is that the module should enable validation hook for the values he enters (or be written so that it's easy to hack and validate).

Since the solution I reference in my first answer was created, I have learned new things. If I were to do the same things again, I would base it on a similar principle, but I would use Panels per pane "CSS Settings", to add CSS classes instead. See: How does one theme a panel (or add a style)

This should allow for much broader customization of content.
A problem with this approach is that Panels UI is hardly "customer friendly".
I would solve that by a custom form, on a dedicated admin page, that simply loads the pane settings from the database, overwrites them, and saves them back.


How to use DefaultSelection::getReferenceableEntities in custom controller? My Goal:
I want to create a customized entity_autocomplete form field to better fit my needs compared to the default one - making some modifications to the HTML and JS that's being used, as well as how submissions are handled.
Specifically, I want to do something like this but I need more control over the backend, and everything...
What Drupal can do:
Drupal's default entity autocomplete already lets the user type 2 letters, and it finds all entities that contain these 2 letters.

My Problem:
Unfortunately I have trouble figuring out how to use the existing "search feature" if you will call it that.
Some Considerations:
I looked into using search API, but this was similarly overwhelming. Considering that this functionality I'm looking for is already built into Drupal, I figure I can just re-implement it, without any additional modules, right? Really, I'm just re-designing the UI. And even if I need to beef it up in the future with a faster, resource saving search engine, I can just replace that aspect of my module/controller. (If someone can point out how to use Search API to do what I need, I'd be happy to listen)
What I've done so far:
I have already created my own custom route that points to a JSON controller which will accept the search parameters.
Based on all my research I figured I need to add use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection; to the top.
I see that DefaultSelection::getReferenceableEntities seems to do exactly what I need it to do.
However, the constructor for this class has 9 different parameters, many of them classes which I know nothing about.
But there is a create method, which apparently allows you to inject configuration data, but also it requires a ContainerInterface.
So here's where I'm lost...
How exactly do I make use of DefaultSelection::getReferenceableEntities in my custom controller?

Okay, it took me over 2 weeks to get to the bottom of this, but turns out, that DefaultSelection::getReferenceableEntities is just a wrapper for Drupal::entityQuery. This becomes especially clear when realizing that DefaultSelection::getReferenceableEntities makes a call to DefaultSelection::buildEntityQuery. And this method is only a complicated way to make a customized query.
So for my purposes, all I had to do was learn about entity queries. Here's how I ended up performing a search:
For taxonomy terms
            $query = \Drupal::entityQuery('taxonomy_term');
            $query->condition('vid', 'my_taxonomy_terms'); //select the collection
            $query->condition('name', $search_term, 'CONTAINS'); //searching the title for a search term
            $term_ids= $query->execute();
            $terms = \Drupal\taxonomy\Entity\Term::loadMultiple($term_ids);  //process the nodes however is desired

            $result = [];

            foreach($terms as $term){
              $result[$term->id()] = $term->getName();
            }

            return $result;

For other entities and nodes
            $query = \Drupal::entityQuery('node');
            $query->condition('field_somefield', 'somevalue'); //optional condition to filter results by
            $query->condition('title', $search_term, 'CONTAINS'); //searching the title for a search term
            $node_ids = $query->execute();
            $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($node_ids); //process the nodes however is desired

            $result = [];

            foreach($nodes as $node){
              $result[$node->id()] = $node->getTitle();
            }

            return $result;

Reference: https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3AentityQuery/8.2.x


Why I cannot change views page title using views_post_render? I have view that uses url args: parent term id and term id/ids, so the url structure is like page/%/%

Title pattern for this view is: %1(%2)

However I have few pages with multi tids as second argument, so generated title is strange (very long). I am trying to change this title programmatically:

function bip_title_alter_views_post_render(&$view, &$output, &$cache)  {

    if ($view->name == 'kategorie_artykulow' && $view->current_display == 'page_9')
    {
        $args = explode(' ', $view->args[1]);
        if (sizeof($args) < 2) {
            return;
        }
        $title_pattern = 'Archiwum Oświadczeń Majątkowych w %dr.';
        $term = taxonomy_term_load($args[0]);
        if (! $term) {
            return;
        }
        $title = sprintf($title_pattern, $term->name);
        drupal_set_title($title);
    }
}

function bip_title_alter_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'views_post_render') {
        $group = $implementations['bip_title_alter'];
        unset($implementations['bip_title_alter']);
        $implementations['bip_title_alter'] = $group;
    }
}

but title remains the same, I am sure that I am altering proper view.

Adding another display to view is not good option for me, because I have a lot existing urls and if I create another display with the same url structure and different args config always first display is handling request.

edit

I changed my custom module weight in system table to 9999 and I still see that title is altered after my module hook :/ It's so annoying

I always use a hook_views_pre_view():

function mymodule_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "foo" && $view->current_display == "bar") {
    $view->display[$view->current_display]->display_options["title"] =
    $view->display[$view->current_display]->handler->options["title"] = "The New Title";
  }
}

This should then funnel up to be pulled in as the page title, but I never use views directly as pages.


Adding imagesloaded to packery module With many responsive designs it is not possible to assign image dimensions as they will be determined by the view-port dimensions. However some scripts, such as Packery, require image dimensions to be known to enable them to arrange items correctly, without overlapping or leaving large gaps. One solution often suggested (e.g. at https://drupal.stackexchange.com/a/77330/14365) is to use imagesloaded.

I have looked at other Drupal modules such as Views Isotope and Field Slideshow which both use imagesLoaded. They each implement it in a different way and I am looking for the correct way to add it in to the Packery module.

My understanding is that: First, a call to add the imagesLoaded script needs to be added to the module file. (The script itself is added to the libraries directory within a folder named 'imagesLoaded'). Secondly, the imagesLoaded() must be declared with the JavaScript file which currently contains:

(function($) {
  Drupal.behaviors.packery = {
    attach: function(context, settings) {
      for (var packery in settings.packery) {
        var $container = $('#' + packery);
        $container.packery(settings.packery[packery].settings);
      }
    }
  };

}(jQuery));

Within the above I need to add in:

$('#container').imagesLoaded( function() {
  // images have loaded
});

Does the way that imagesLoaded is added within the module effect if it becomes a function?
Adding the script side-wide is not really appropriate as it is only required in combination with the use of Packery. Does this mean it should be added in a certain way?

Super late but support for this request has been added in the latest commit of the Packery module: Commit 24856cf on 7.x-1.x by swim: Added imagesLoaded support on per settings basis.

Just toggle on/off on the settings page, and read the README.txt for the plugin placement. Here is a quote from the updated README.txt:

  ImagesLoaded support

  For imagesLoaded support please download the plugin from https://github.com/desandro/imagesloaded.
  Place the plugin in the libraries directory at sites/all/libraries/imagesloaded so that the file is at sites/all/libraries/imagesloaded/imagesloaded.pkgd.min.js.


Only one module implements hook_tokens()? I've declared a [module-name]_tokens() hook but when I output the contents of module_implements('tokens'), only my module appears in the list.
I know that there are many more modules that implement hook_menu(); why do I get only my module listed? Where shall I look for possible errors?

$hooks = module_implements('tokens');
print_r($hooks);

It returns the follwoing

  Array
      (
       [0] => token
       [1] => date
      [2] => domain
      [3] => entity_token
      [4] => facetapi
      [5] => logintoboggan
      [6] => name
      [7] => node
      [8] => scheduler
      [9] => system
      [10] => taxonomy
      [11] => token_custom
      [12] => user
      [13] => views
      [14] => field
      [15] => menu )

The only place which i see is it is cached, try clearing the cache or try the following

 module_implements('tokens', FALSE, TRUE)

The third params is reset to reset the cache.


I log in and then I am anonymous? I've been trying to debug an app where I am utilising ajax and trying to post content via services. However, I can't. What am I missing?

 $.ajax({
      url: 'http://7.webcinizim.com/services/user/token.json',
      type: 'post',
      dataType: 'json',
      success: function(token) {
        console.log(JSON.stringify(token));
        $.ajax({
            url: 'http://7.webcinizim.com/services/user/login.json',
            type: 'post',
            dataType: 'json',
            data: {
              username: "tolga",
              password: "tolga123"
            },
            success: function(user) {
              console.log(JSON.stringify(user));
              $.ajax({
                url: 'http://7.webcinizim.com/services/node.json',
                type: 'post',
                dataType: 'json',
                data: 'node[type]=page&node[title]=Hede',
                success: function() {
                  console.log("Node created");
                },
                error: function(err) {
                  console.log(err);
                }
              });
            });
        }
      });
  }
});

UPDATE: My query looks like this now and I am getting Invalid JSON:

$.ajax({
  url: 'http://7.webcinizim.com/services/user/token.json',
  type: 'post',
  dataType: 'json',
  success: function(token) {
    console.log(JSON.stringify(token));
    localStorage.setItem("token", token.token)
    $.ajax({
      url: 'http://7.webcinizim.com/services/user/login.json',
      type: 'post',
      dataType: 'json',
      data: {
        username: "tolga",
        password: "tolga123"
      },
      success: function(user) {
        console.log(JSON.stringify(user));
        $.ajax({
          url: 'http://7.webcinizim.com/services/node.json',
          type: 'post',
          dataType: 'json',
          data: {
            "node[type]": "page",
            "node[title]": "Hede"
          },
          headers: {
            "X-CSRF-Token": localStorage.getItem("token"),
            "Content-Type": "application/json"
          },
          success: function() {
            console.log("Node created");
          },
          error: function(err) {
            console.log(err);
          }
        });
      },
    });
  },
});

When using Services after login request in response You should get a X-CSRF-Token. You have to use it in header of next requests to keep "being logged in".
It should be in header for second (and all possible future) requests like:

headers: {
    "X-CSRF-Token":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    "Content-Type":"application/json"
}


Help solve this error: Class CommerceLicenseEntityController does not exist When I install the Commerce Licence module, in D7, I get this error. I think it might have to do with my Drupal installation, I'm not sure.
What steps can I take to find out what causes this?

The whole warning texts is (2 warnings):

Warning: class_implements(): Class CommerceLicenseEntityController does not exist and could not be loaded in entity_entity_info_alter() (line 1480 of /data/disk/o1/distro/002/drupal-7.54.2-dev/sites/testsite.com/modules/entity/entity.module).

Warning: in_array() expects parameter 2 to be array, boolean given in entity_entity_info_alter() (line 1480 of /data/disk/o1/distro/002/drupal-7.54.2-dev/sites/testsite.com/modules/entity/entity.module).

The error I got was a bit different, so this may not work for you. My error was

Exception 'ReflectionException' with message 'Class CommerceLicenseFile does
not exist' in [filepath]/entity_bundle_plugin.module:46

I disabled the Commerce License module and renabled it. I can now clear cache without error. Hope that works for you if you have not solved the problem.


How to get rid of added URLs when printing a Bootstrap-themed page? When I print a page from my Bootstrap-themed site, all the links (and images with attached urls) have a printed representation of the link inserted into the printed page, right after the linked object.  I can see some situations where this would be helpful, but for now it's just messing up my printed layout.  I smell jQuery at work here, but I can't figure out where it is or how I can turn it off.  Any hints out there?  Thanks!

Found it: it wasn't jQuery, but CSS3.  Down in bootstrap.css, we find:

@media print {
  ...
  a[href]:after {
    content: " (" attr(href) ")";
  }
  ...
}

Overriding the style with content:none handles the situation fine.  There are some similar :after clauses in there doing similar things, but this is working for now.


register users automatically I add a new text field that called real name(for entering the real first and last name).
And a "selection filed" that user can select his field between A to D.

Now for registration we have 5 field.

Email
Username
Password
Real name
"Selection field"

And I have an Excel file that contains about 500 users data(all data are in there such as user name and password and ...)

Now I need a similar code to register them automatically in my drupal site.

How?

Note:In the "selection field" the choice are such as First-one First-two and so on.

Example:this is a similar column in my excel file

Username     password     realname     Email     SelectionFild
12321        12321        Mr.Bin       -         F1

Note:in this example - in the Email means the user haven't Email address.
And F1 in the selection field means First-one.

You can use feeds module which import data, uses, taxonomy term into Drupal website using CSV file.

In module page:

  Import or aggregate data as nodes, users, taxonomy terms or simple
  database records.

  One-off imports and periodic aggregation of content
  Import or aggregate RSS/Atom feeds
  Import or aggregate CSV files
  Import or aggregate OPML files
  Create nodes, users, taxonomy terms or simple database records from import
  Extensible to import any other kind of content
  Granular mapping of input elements to Drupal content elements
  Exportable configurations Batched import for large files


select list - content outputs key instead of label Drupal 7 v. 7.34 - content type. In my content type I use at least 3 fields with select lists. In each case the key is output instead of the label. I would expect the label to be displayed to the user.
E.g. the field 'theme' has the following available options:

wedding|wedding first dance
dancepromo|let's dance

The content shows 'wedding' instead of 'wedding first dance' and 'dancepromo' instead of 'let's dance'.

What am I doing wrong ?
Should I change the key|label order to label|key ?

Go to the display settings for your content type, and look at the display formatter for the field. it should be set to Default. The other option is Key.


Center the open layer map when in edit mode i setup a map with openlayers, geofield, addressfield and geocoder.

I added a geofield to a node, with openlayers as the widget type, and use geocoder to get the geocode from addressfield.

when editing, user press the Find using Address field button and the map display with the marker if found.

the question: how to center the marker? If i set the zoom level higher (in Center and Bounds setting of open layer), the marker will not be shown (out of the visible map area).

you need to enable placeholderlayer in openlyers map with a marker of your choice. and then in behaviours you need to zoom to layer and enable placeholder layer and save.


Add custom action buttons to a view Suppose that I have a view that outputs a list of some content. Now I'd like to add some action buttons next to each content item, so that clicking these buttons triggers some custom action or redirect the user to another path (specific for that item).

I found a solution here that comes close to what I'd like to do, but that solution is based on D7 Add custom action buttons to view.
Without repeating the content of this link, could someone let me know whether that approach is still valid/good practice for Drupal 8?

In case it is the solution, how would you implement the functionality of passing the $nid of a list item to a different form via POST when clicking one of the action buttons ? Would this be part of the function function query() {...} in step 5 of the link ? If so, how would you approach this ?

Are there solutions that might be better suited to D8?

Drupal 8 lets you add 'DropButtons' to your View, which looks really good in UI.

add a 'Custom text' field for each action you want to provide - use 'exclude from display' and 'output as custom link'
add a 'dropbutton' field and select your custom links to be shown in it
profit


How to change payment state programmatically? I had created a custom module to update order state and payment state. In my controller I used the following code to change the order state of order.

 $order = \Drupal\commerce_order\Entity\Order::load($order_id);

 if ($payment_status === 'payment.captured'){
   $order->set('state', 'completed');
   $order->save();
 }
 else {
   $order->set('state', 'pending');
   $order->save();
 }

How can I now change the payment state of a payment which comes inside that order?

This is the screenshot of my payment. Now the payment state is pending. I want to change it to something else by using code, for example completed.

Try this:

use Drupal\commerce_payment\Entity\Payment;

$payments = \Drupal::entityQuery('commerce_payment')
  ->condition('order_id', $order->id())
  ->execute();

foreach ($payments as $value) {
  $payment = Payment::load($value);
  $payment->setState('completed')->save();
}


Limiting table rows viewed in CCK Table Field I'm using Drupal 6. The node has been created with 10 rows.

I'm looking for ways to make the table content viewed on the front page with 5 rows, where it has "more" link to the full node.

It can be PHP code to be placed in the block, or any other ways. Any suggestion are welcome including modification on other modules.

You need to focus on node template.
Override or create a tpl of your content type e.g. node-type.tpl.php
User $node object to access all your cck fields.

Also care about $teaser and $page flags to get the state of your node.

If $teaser is true then render 5 items from $node object. If $page is true then render all your items.


Shipping quote depending on order total I am a long time drupal user and a first time ubercart user. I apologize if this question has been asked in the past. I could not find the answer through google, ubercart.org or the forums here.

We are planning on shipping our product USPS flat rate. I would like the shipping cost to depend on the order total. Is this possible?

Something like this:

0-$99.99 - $5.99

$100 - $350 - $9.99

$350 - $500 - $11.99

$500+ - Free

I am running drupal 7 with ubercart 7.x-3.4

Thanks

Activate the following Übercart modules:

Shipping
Shipping Quotes
Flat rate

Go to http://yoursite.com/?q=admin/store/settings/quotes and click on "Add flat rate quote". Fill out the from and submit it. The next form should be the conditions form. Create the necessary condition(s), for example, 0 < order:order-total AND order:order-total < 100 as a data comparison. To enter the total values (i.e. float numbers) click on the "Switch to data selection" button near the bottom. Repeat this for all of your total ranges.


Alter a form in a block only if it is in a certain region In my template.php I'm trying to alter a form in a views exposed block, but I only want to do this if that block is in a certain region in my theme.

I'm using Drupal 7.

Is that possible? What php code would I use?

Here is what I'm using now:

function cmfzen_form_alter(&$form, &$form_state, $form_id) {

  // change the main search form
  // see http://drupal.stackexchange.com/questions/28404/easiest-way-to-add-x-webkit-speech-to-the-search-blocks-input-element
  // see http://adaptivethemes.com/html5-placeholder-text-for-your-drupal-7-search-field
  if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-site-search-page"){

    $form['site-search']['#type'] = 'searchfield';
    $form['site-search']['#attributes'] = array(
      'class' => array('search-site'),
      'placeholder' => t("I'm looking for..."),
      'speech x-webkit-speech spellcheck' => 'false',
      );
    // change form submit button

    $form['submit']['#attributes'] = array('class' => array('search-button'));
  }
}

use this code in hook_form_alter:

function cmfzen_form_alter(&$form, &$form_state, $form_id) {
    switch($form_id){
         case 'views_exposed_form':
         $region = 'NAME_OF_A_REGION';
         $blocks = block_list($region);
         kpr($blocks);
         //if the block is in the $blocks array do the changes.
         break;
    }
}

using block_list($region) you will get the blocks that are placed in a specific region, and it returns array of block objects (for more detail visit this page). Now check if the block you are looking for is in the $blocks array.


How to dynamically create Drupal 7 tables based on form API input values? I have an array with the data below:

arr_fields[0] = 'a bigint'
arr_fields[1] = 'b bit'

I want to structure it just like the array structure below:

$fields = array(
            'a' => array(
                'type' => 'bigint',
            ),
            'b' => array(
                'type' => 'bit',
            )
);

Below is the rest of the code and it's working fine.

$schema = array(
    'description' => t ('Contains a particular templates data inputted from the MyID Inputting System'),
    'fields' => $fields,
);

db_create_table('myid_template_' . $template_id, $schema);

I tried the code below to structure it like the above, but it throws an error

foreach ($arr_fields as $value) {
    $arr = explode(' ' , $value);
    $fields[$arr[0]] = array('type' => $arr[1]);
}

$schema = array(
    'description' => t ('Contains a particular templates data inputted from the MyID Inputting System'),
    'fields' => $fields,
);

db_create_table('myid_template_' . $template_id, $schema);

An error says:

PDOException: SQLSTATE[42601]: Syntax error:  7 ERROR:  syntax error at end of input
LINE 4: )
     ^: CREATE TABLE {myid_template_489} (
a ,
b
); Array
(
)
in db_create_table() (line 2720 of C:\xampp\htdocs\drupal-7.34\includes\database\database.inc).

How should I structure it?

foreach ($arr_fields as $value) {
    $arr = explode(' ' , $value);
    $fields[$arr[0]] = array('type' => $arr[1]);
}

UPDATE 1:

Here's my form input pass through AJAX POST method:

As I read the output of the error message, I suppose the values you are trying to parse do not contain the type of the database field.

Did you check your PHP error log as well? There might be PHP warnings, stating that $arr[1] is not set.

Verify your parsed values and make sure they contain the type information.

An additional note: I do not know your special use case. But creating a new table on each template might easily bloat your database structure. Maybe you find a better solution to store your information within one dedicated table, using your template ID as identifier and serialized arrays holding the information?


Determining current user's relationship to node author I'm currently using User relationships module, and setting the UR-Node access module so that nodes can only be viewed by users related to the author.

However, I want to have a public display version of the node for search engines, sharing links, and also for a button to say 'You need to become friends with x to see this node'.

So, I was thinking of using the User relationships API to determine the users' relationship, and output two different displays in the tpl.php file.

Does anybody know how to determine the relationship programatically? I'm stuck.

(I've done this in the Views I've made, it's just in the nodes, that I'm having trouble)

It looks like you can use the user_relationships_load() function. The following code will load all relationship objects that exist in the system between 2 users. From there you can inspect the relationships for their type/properties and make your decision based on that:

// Set up the user ids
global $user;
$current_user_uid = $user->uid;
$node_author_uid = $node->uid;

// Set up the parameters
$params = array('between' => array($current_user_uid, $node_author_uid));

// Get the relationships
$relationships = user_relationships_load($params);


How to create an article with "show on demand" part of the text of the article? What I am trying to do is like in the picture.
So I would have an article of same text of multiple language. When I click on the Flag/text link on top of the article, it should show particular part of the text of that language selected. All other texts should be hidden. Is that something easily achievable? Can anyone suggest how to go with it please?

For your use case, there is no module for it. You will need to use custom jQuery

SEE MY DEMO

For Example:

HTML

Merci

Thank you

jQuery

$( document ).ready(function() {
 $('.french-flag, .english-flag').css("cursor", "pointer");
 $('.french-text, .english-text').hide();

$('.french-flag').click(function() {
  $('.french-text').show();
  $('.english-text').hide();
});

$('.english-flag').click(function() {
  $('.english-text').show();
  $('.french-text').hide();
});

});

but in drupal you need to wrap your js code inside

(function ($) {
   // code goes here
})(jQuery);

So your Drupal JS code (example.js) needs to be

(function ($) {
     $( document ).ready(function() {
     $('.french-flag, .english-flag').css("cursor", "pointer");
     $('.french-text, .english-text').hide();

    $('.french-flag').click(function() {
      $('.french-text').show();
      $('.english-text').hide();
    });

    $('.english-flag').click(function() {
      $('.english-text').show();
      $('.french-text').hide();
    });

    });
})(jQuery);

To add/load your jQuery/java script to drupal, there are various methods, see/read Working with JavaScript and jQuery


How do I actually get a field value using field_view_value()? I simply want to get the value of a field and have been told I should use field_view_value.

To this affect I have created:

$field_text_items = field_get_items('node', $node_context->data, 'field_text');

$field_text_items_value = field_view_value('node', $node_context->data, 'field_text', $field_text_items[0]['value']);

But running dpm($field_text_items_value); just returns an array with:

#markup (String, 1 characters ) h
#access (Boolean) TRUE

I'm assuming, because my field's value begins with a 'h', the #markup is only returning the first character for some reason.

Running dpm($field_fcc_text_items[0]['value']); returns the correct result so I know thing field is fine.

I've looked at the documentation linked above, but to be honest a lot of it doesnt make sense.

Would anyone be able to point me in the right direction here?

Thanks

As a side question, why is field_view_value() preferable to just using something like $field_text_items[0]['value'] anyway?

You may have the field_view_value parameters wrong. Instead of the entity_type-> delta try loading the field first using field_get_items. Use the return value as the second parameter in field_get_items.

$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

I took that answer from the blog: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way


How to print the search results after form_submit, in a custom search module? I am creating a custom search block, I have created a form in the block. Here is my form_submit. I need to print a html table of some of the fields in the $result array. I am using Drupal_set_message(), I need to show the results in a table instead, so that user can print the page

$text = $form_state['values']['text'];
$query = db_select('table_1', 'n');
$query->fields('n', array('id'));
 $query->fields('n', array('phone'));
$query->fields('n', array('name'));
$query->condition('n.p_id', $text, '=');
$column_name = $query->execute();

I used an if statement in the form to check if submit is pressed and gave the results in the if block.

function hook_form($form, &$form_state) {
if (!empty($form_state['values']['text'])) {//here i am checking if the text field is empty
    $header=array('one'=>t('one'),'two'=>t('two'));//your header
 $query=db_query();//query
$column_name = $query->execute()->fetchAssoc();//fetchAssoc to get results in an associative array.
//here get the fields from $column name into rows
$row = array(
    array(
    'one'=>$column_name[""],
    'two' => $column_name[""],
    );
//your form elements after submit is pressed.
 $form['table']=array(
 '#theme'=>'table',
 '#header'=>$header,
 '#rows'=>$row,
 );

}
else {
//your original form here.
 $form['text'] = array(
'#type' => 'textfield'
 );
$form['buttons']['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit Button'),

);
  }
 return $form;
}

in you form submit add this

$form_state['rebuild']=true;


Date token to use user timezone instead of site timezone Our site is having users from different timezones and we are sending event notification emails using rules. We need to specify the event date-time in addressee's timezone.

So, is there any way to specify the the timezone within/along with date-time token?

Or, should I introduce a custom token for this purpose?

You can try date token with custom date formatting

[entity:field-event-date:custom:m/d/y T]

replace entity with appropriate token (node, etc.), and insert the name of your date field.

Refer to PHP:date - Manual for custom date formats.


How to properly use a JS library that inserts content into existing DIV? As with many JS libs i need an existing DIV for the lib to insert its content. I am trying to use the Chart.js library to inset a chart on a custom drupalgap page.

I eventually discovered the menu item page handlers and did this:

items['qleva_start_auth'] = {
  title: 'Home Auth',
  page_callback: 'qleva_start_auth',
  pageshow: 'qleva_start_auth_show',
};

in my hook_menu.

qleva_start_auth now only has the required empty DOM element:

function qleva_start_auth() {
  var content = {};
  content['my_stuff'] = {
    markup: '<canvas id="myChart" width="100" height="100"></canvas>'
  };
  return content;
}

and the pageshow callback has the code to set up the chart.

This seems to work great except that my chart is now on every page; added to the bottom of the content for that page.

What am i doing wrong?

You can likely use drupalgap_add_js() at the beginning of your pageshow implementation to add the Chart.js library:

function qleva_start_auth() {
  drupalgap_add_js('Chart.js');
  // ...
}


How to allow the user to change the language? I think I must be missing something here.

I have enabled the multilingual modules and added a language. It all seems to be working with respect to translating content - an admin can easily translate an individual page. However I can't see how to give an anonymous user the ability to change their selected language. I was expecting the multilingual modules to create Blocks that would allow a user to change their default language and which would notify them if a particular page is available in another language. So my questions are:

1) How do I allow an anonymous user to change their preferred language?
2) How do I alert an anonymous user to the fact that a particular page is available in another language?

You can find a detailed answer in step 5 of this guide: 5 Steps to Build a Drupal 8 Multi-lingual Site.

Basically, this is what you need to do:

Go to Admin > Structure > Blocks
Click "Place blocks" on the desired region
Click "Place block" next to the "Language Switcher" block
Click "Save block"
Go to a translated node and the Language Switcher will be working

As a sidenote mentioned in the comments of that guide: "You also need to have the url method enabled in the detection and selection page."


Edit Content with out seeing the information in text box Let me explain this.
Lets say you have a form that you fill out to create a record.

In order to fill this form out you have to be registered and signed in.
Any one can sign up.

This form includes couple peoples addresses and names.

Now any one can go and edit the form where they can see the info on the form.

The problem is that when the form is filled out the first time or edited there is some fields that have personal information and i dont want public to see this data.

Does any one have idea how i can hide the information but have the info available to be updated if needed.

I was thinking using password type but it hides all of it.

Or maybe hiding part of the text ?

I have no idea how to go about this. If any one that reads this has any idea please let me know.

Thanks in advance.

You can use the Field Permissions module to enable create/edit/view permissions per role.  So you can remove the view permission on those fields you want to hide for all roles but the admin role. That way authenticated users cannot view or edit the fields but the admin can.


2 views blocks on 1 page - no duplicate results I have 2 views blocks with the same filter criteria. Both are displayed in different regions on 1 page. But they should not display the same results.

Is there a solution for that?

Note: The views have the same data. But they are sorted randomly.

There are a few solutions:

You can use Panels module to build your page. Using this module you can insert a block in multiple times.
You can use this code into different regions to display the view

<?php print views_embed_view("VIEW_NAME","MACHINE_NAME","ARGUMENTS");

The views_embed_view displays the view.
You can also load the block itself despite of what entity has generated it's content by the following code

<?php
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  print render($block['content']);
?>

The How to insert a block into a node or template in Drupal 7? gives you more details about the arguments of above code.


Commerce: How to manage line item fields for custom product type? Drupal commerce works as follows:

When I add a product to the cart, system creates new line item (of type: product)

I have several product types. Could I achieve, that product line items would be specific for each product type?

What I would like to achieve is, that I can manage fields in line item type separately for each product type.
For now, I can manage fields (or manage displays) only generally for all product types (When I go to Store -> Configurations -> Line item types -> Product)

There's an open feature request for precisely what you want in the queue for Commerce Customizable Products. In the meantime, you need to create a new product display node type for each product type and use the settings for the Add to Cart form display formatter to use the pertinent line item type in its forms.


Change Omega4 Layout Based on Content Type via template.php I want to set Omega4 Layout defaults based on Content Type. I am trying to use the following code, but the hook_omega_layout_alter doesn't seem to use the $node variable. What am I missing?

I have already referenced Omega override simple-layout.tpl.php for content types but, once I try and and a switch statement based of $node->type it stops working.

What can I do to set the default Omega4 Layout based on Content Type using the hook_omega_layout_alter function?

function THEME_omega_layout_alter(&$vars, &$layout) {
  $node = $vars['node'];
  switch ($node->type) {
    case "article":
        $layout = 'article';
        break;
    case "blog":
        $layout = 'blog';
        break;
    case "market":
        $layout = 'market';
        break;
    case "merchant":
        $layout = 'merchant';
        break;
    case "product":
        $layout = 'product';
        break;
    case "update":
        $layout = 'update';
        break;
  }

}

As per referenced question I would go with something like the following:

function THEMENAME_omega_layout_alter(&$layout) {
  if (arg(0) == 'node' && is_numeric(arg(1))
      && $node = node_load(arg(1))) {
        switch ($node->type) {
          case 'article':
            $layout = 'article';
            break;
          case 'blog':
            $layout = 'blog';
            break;
          default:
            $layout = 'default';
        }
   }
}


Sync +- 70 000 records from CSV into drupal I have a CSV file with approx. 70.000 records that I want to import into Drupal 7. Once this is done the client will provide a new CSV file on a daily base that has to sync the updated rows to Drupal.

I wrote a import with Feeds and the Migrate module, but in both cases it takes like forever to import the 70.000 rows. Is there any other solution to import the data faster in Drupal 7?

If you need an update feature of your records i'm not sure how you'd get around scanning for Diffs to find changes -- this takes time.

I've used Migrate to upload simple CSV files and tables. Have you looked at Migrate 2.6 Hash() function to track data changes in stuff to perform only updates from your source data?
http://www.acquia.com/blog/migrate-26-framework-changes

  With Migrate 2.6, we have introduced the 'track_changes' option to
  MigrateSource. If you pass 'track_changes' => 1 in your options array
  on your source constructor, Migrate will hash the source data after
  prepareRow() is called and save the hash in the map table on initial
  import. On subsequent imports, it will again hash the incoming source
  data and compare it to the saved hash - if the hashes don't match, the
  object will be reimported and the new hash saved, otherwise it will be
  skipped. Of course, this is a slower method than highwater marks, but
  when you must pick up changed records and don't have a good highwater
  mark field in the source data, this is the way to go.

Is there any reason you cannot import your CSV file into MySQL tables and then import your data from there using Migrate or a Drush script? Once in tables you could partition the data/tables easily to run the inserts more concurrently for a speedup.

EDIT:

I hit a .NET webservice for 100,000s of records for campus data at an EDU. I found that parsing the data linearly took me on the order of an 1 hour from top of the XML file to the bottom. By requesting each department individually at-the-same-time (get ~60 XML files at once instead of 1 big xml file) and processing in parallel up to 8 threads (via Ultimate Cron) the same process now takes ~5 minutes.

At some point linear processing of data simply fails and you have to find other means.


Datetime retrieved from db is 7 hours off? I am having trouble displaying the correct date, well actually its only the time.

In the db the date is stored in this form: 2012-09-28 23:30:00

That is the value for a date of an event.

When I retrieve it using this script:

$ttdate = $obj->field_date_test_value;
$nttdate = strtotime($ttdate);
$okdate = format_date($nttdate, $type = 'medium');
print $okdate;

...it works fine but the time is off by 7 hours.
So instead of showing Fri, 9/28/2012 - 4:30pm it shows Fri, 9/28/2012 - 11:30pm.

Note that on the event's page, drupal retrieves the correct time...

I did some research and I figured it has to do with the timezone? But I have the timezone set to Los Angeles so I am not quite sure what is going on. Maybe its my script?

Date/times are generally stored in the database as UTC, so if your timezone is UTC -7 hours then all your times will be out by 7 hours (between the database and your expected output).

When you load a date from the database you then have to apply the desired timezone before displaying it or doing calculations on it or whatever.

For some examples you can see what the date module does with:
date_formatter_process() and
date_tokens()

It creates a new DateObject and then runs date_timezone_set($date, timezone_open($timezone)); on that date to set the timezone.

If you just want to use the site timezone (or user selected timezone) you can use date_default_timezone().

There is also the drupal core function format_date(), which takes a timestamp, a date format, and a timezone and gives you the output date.
That would be the easiest option.

For example, you might do this:

$okdate = format_date($nttdate, 'medium', '', date_default_timezone());


How to hide an image field from teaser view if video field has data? foreach($view->result as $value){
     if($value->_entity->field_videos->getValue()[0]['target_id']){
      kint($value->_entity->field_blogimage)
    }

I am getting following image by kint, I need to set exclude to 0 for image field of this view in views_pre_render hook in drupal 8.

function mymodule_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\
  EntityInterface $entity, $context) {
  // For nodes, change the view mode when it is teaser.
  $current_path = \Drupal::service('path.current')->getPath();
  if($current_path=='/dblog'){
    if ($entity->getEntityTypeId() == 'node') {
        // kint($entity->getFields()['field_videos']
        //  ->getValue()[0]['target_id']);
        if(!(empty($entity->getFields()['field_videos']
        ->getValue()[0]['target_id']))){
        $view_mode='single';
        }
    }

  }

}

well in my case, i solved my problem like this, i created new view mode with needed fields and switched view modes using above hooks.I think this one is a good alternative.Thanks Guys
@OPTASY Canada
@Chriss Happy


know if the last cron run automatically or manually? Is there a way to know if the last cron run automatically or manually from the form "run cron" button?

I'm not sure why you really want to check this. However, I can think of a few methods:

Alter the admin/reports/status/run-cron menu router item, and add some flagging to mechanism to detect the call. If the user runs cron through this page, that's definitely a manual "Run Cron" call. Implement hook_menu_alter, and change page callback (probably file and file_path aswell) to your own function. In this function, add some flagging mechanism, and run previous page callback. It's unlikely that another module will need overwrite the page callback so you are almost safe. A little performance hit during menu rebuilds.
Add your own cron handler, and check $_GET['q'], or better, $_SERVER['PHP_SELF'].
For $_SERVER['PHP_SELF'], if it's index.php, that's a manual run. Otherwise it will be  cron.php, which is likely an automatic call. However one could click the URL containing the token, which is not actually an automatic. I think this is the best method since it does not need to assume other modules does not need to override page callback. A little Performance hit in each cron run.
Hack the cron.php (better yet, copy it to a new file). For example, copy cron.php file to scron.php, and make your crontab request that file instead of the the regular cron.php with token. You can then edit the scron.php file, and right after the bootstrapping, add a custom code to flag the cron that the file is about to execute is an automated one. Requires some custom effort that you can't do with a regular hook_install implementation. Performance wise, this will work almost same since there are no any hooks involved.


How can I delete orphaned Product Displays? Using Commerce Kickstart 2.

We have a number of orphaned nodes we would like to delete, ie Product Displays which reference no Product Variation.

I created a View with VBO which shows me these nodes, but unfortunately, it throws an error when attempting to delete since each orphan is missing certain required fields.

Is there a way to -force- VBO to delete these nodes (bypass the form validation for each delete?)

Or... is there a SQL Query you can recommend which will do the same thing (hopefully safely)?

Perhaps a PHP script that mimics creation of that View list and then utilizes a node_delete_multiple().  Granted, you will want to test this out very carefully before actually using a method like this.

That said, an Entity Field Query coupled with a node_delete_multiple() may be what you're looking for.  Again, test very well, look at the DB after a test run, see that everything you want deleted is.


How to get the name of a field? I'm on hook_form_alter for the config edit form. The code runs for all fields, but it's critical that the code figures out the name of the field it is on.

When I load the formobject, I can see the field_name perfectly when I print_r the array. But I can't figure out how to pull it out. Something like $name=$field['field_name']

The field name is 'field_plan_purpose' I need to get that in a variable in the code.

My code minus all of things I've tried:

$field = $form_state->getFormObject()->getEntity();
print '<pre>';
print_r($field);
print '</pre>';

Here is the top part of the array that gets printed:

Drupal\field\Entity\FieldConfig Object
(
    [deleted:protected] =>
    [fieldStorage:protected] => Drupal\field\Entity\FieldStorageConfig Object
        (
            [id:protected] => node.field_plan_purpose
            [field_name:protected] => field_plan_purpose <--- HOW DO I GET THIS
            [entity_type:protected] => node
            [type:protected] => text_long
            [module:protected] => text
            [settings:protected] => Array
                (
                )

            [cardinality:protected] => 1
            [translatable:protected] => 1
            [locked:protected] =>
            [persist_with_no_fields:protected] =>
            [custom_storage] =>
            [indexes:protected] => Array
                (
                )

            [deleted:protected] =>
            [schema:protected] =>
            [propertyDefinitions:protected] => Array
                (...

As you can see, 'field_name' is in there. Does anyone know how I can pull that out and reference it directly?

A few things I've tried:

    // print_r($field->getEntityKey('#field_name'));
    // getEntityType()->getKey('field_name')
    // $field['field_name']  $field['field_name:protected']
    // $field['id']
    // $field->getKey('field_name')
    // $field->definition['field_name'];
    // print_r($field->definition);

EDITED ******* SOLUTION

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

   $field = $form_state->getFormObject()->getEntity();
   $field_name = $field->getName();
   print $field_name;

}

FieldConfigBase has a method named getName(). That will retrieve the field name:

public function getName() {
  return $this->field_name;
}


Fetch fields of a block defined via content type programmatically I've created a block type via the UI. This is a translatable block with 3 text-fields.

I am using hook_block_view_alter($build, $block) to massage the data. However, I can not seem to find the fields neither in $build or $block vars.
Any idea on the fetch the field's values programmatically?

You are in the wrong entity. block is a config entity to configure where and how the block is displayed and which plugin is used to build the block.

The plugin can be a core, contrib or custom block class. In your case a core plugin, which fetches content from the database. The content is stored in the content entity block_content.

So the entity type to modify the fields of a custom block is block_content and you have to use this hook:

hook_block_content_view_alter(&$build, $block_content)


How do I remove the itok token from the image URLs? How do I remove the itok token from the image URLs?

I found an article discussing it, but it only works for Drupal 7 (https://www.drupal.org/node/1934498).

Some articles explains why Drupal adds tokens to the image URLs.

http://www.unimitysolutions.com/blog/image-style-token-itok-drupal
Why is Drupal adding token on image url

While it's recommended to keep the itok parameter, it is configurable.

You can suppress it from output using the image.settings config setting suppress_itok_output

  // The token query is added even if the
  // 'image.settings:allow_insecure_derivatives' configuration is TRUE, so
  // that the emitted links remain valid if it is changed back to the default
  // FALSE. However, sites which need to prevent the token query from being
  // emitted at all can additionally set the
  // 'image.settings:suppress_itok_output' configuration to TRUE to achieve
  // that (if both are set, the security token will neither be emitted in the
  // image derivative URL nor checked for in
  // \Drupal\image\ImageStyleInterface::deliver()).

https://api.drupal.org/api/drupal/core!modules!image!src!Entity!ImageStyle.php/function/ImageStyle%3A%3AbuildUrl/8.2.x


List all nodes related to a term which is related to another one I searched many times how to list all nodes related to a term which is related to another one, but without success...

Can you help me ?

Actually I want to do something like this:

My page (where a term is defined) <- A term linked to the previous defined one <- The nodes related to this term.

Thank you for the help!

If you don't have Views installed, install the Views module.

Create a taxonomy view
Add filter to filter your taxonomy.
Add a relationship to other taxonomy you want.
Add the relationship to nodes.


Alter message status per content type After hours trying to figure it out, no way ! What am I doing wrong ?

function alter_appointment_message_form_node_form_alter(&$form,&$form_state,$form_id)
{
     if($form['#node']->type=="appointment_request")
     {
       drupal_get_messages('status'); // Flush default simplenews status message
       drupal_set_message(t('An appointment has been requested'), 'status');
     }
}

I suppose you want to show a message after submitting the form. (But as Pierre commented, please be clear in what you want and do not make us assume things.) hook_form_alter() works during the building of the form. Your code probably works, but there is no message generated yet.

Instead, use hook_form_alter to add a new submit callback and place your code in there. Somewhat like this:

function alter_appointment_message_form_node_form_alter(&$form,&$form_state,$form_id)
{
  $form['#submit'][] = 'alter_appointment_message_post_submit';
}

/**
 * Custom submit callback.
 */
function alter_appointment_message_post_submit($form, &$form_state) {
 if($form['#node']->type == "appointment_request") {
   drupal_get_messages('status'); // Flush default simplenews status message
   drupal_set_message(t('An appointment has been requested'), 'status');
 }
}


What is the easiest way to upload video and audio content? I am creating a website archive that will allow users to upload various different types of media content including video, audio, images, documents and text. I want to make it easy for users to upload the media content to the site.

Is it better to upload directly to the website hosting itself or to use a third party video and audio hosting like YouTube and SoundCloud?

Either way how can it be made as easy as possible for the user to upload the media content?

Get a media management suite that integrates with as many third party hosting providers as possible. It means less work for you, less complexity, and less bandwidth on your server for which you have to pay.

Good suite's include, but are not limited to:

Scald

  Scald is a popular and flexible way to handle media in Drupal.

  Scald can handle images, video, audio, tweets and even Flash files.
  Scald works with YouTube, Vimeo, Soundcloud and other many other
  providers.

and Media

  The Media module provides an extensible framework for managing files
  and multimedia assets, regardless of whether they are hosted on your
  own site or a 3rd party site - it is commonly referred to as a 'file
  browser to the internet'.

For a front end media solution you can look at MediaFront

  The MediaFront module is a front end media solution for Drupal. It
  employs an innovative and intuitive administration interface that
  allows the website administrator to completely customize the front end
  media experience for their users without writing any code.


Get taxonomy terms value in views I have two content types

Program
Registration

and one taxonomy

Program type

Program content type having term reference with program type taxonomy
and registration having node reference with a program.

I am using views to list out all registrations.

How can I get the program type terms value in registration content type list?

Considering entity reference fields in the following manner:

Program having an entity reference field pointing to the terms of program type vocabulary.
Registration having an entity reference field pointing to nodes of type Program.

To achieve what you want:

Create a view of content. Of type "Registration". Add required fields from registration content type
Add a relationship of type "Entity reference: referring entity" with field from #2 above.
This will enable you to add attributes/fields from the "Program" content type.
Add a relationship of "Entity reference: referring entity" with the field from #1 above (pointing to terms). Important: Use the earlier relationship in this new relationship (i.e. nested relationship).
This will let you add attributes/fields from the taxonomy terms.


custom form module not showing upload functionality <?php

function form_test_menu() {
  $items['formtest'] = array(
    'title' => 'Form Test',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('form_test_form'),
     'access callback' => TRUE,
    );
   return $items;
}

function form_test_form($form,&$form_submit) {
   $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
    $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

Hello all,

Can anyone explain to me why this will not work?  I am trying to test the form submission and I created a module folder with a .info file.  I am using mywebiste/formtest, but every time I try and load the page it says "page not found."  I have been looking at tutorials and they all seem to work fine but it seems that I must be doing something wrong.  Any thoughts?

Any and all help is greatly appreciated, thank you in advance.

Try to clear all cache of your Drupal website and try to access your url: http://wwww.your_domain.com/formtest


Replacement for _drush_file_private_path() I'm trying to get File Permissions working in Drupal 8.9 with Drush 9. The old code calls _drush_file_private_path(), which doesn't exist anymore, and _drush_file_public_path() is probably a no-go as well.
What is the proper way to do the following in Drush 9?
define('DS', DIRECTORY_SEPARATOR);

// Define default paths and variables.
$default = 'sites' . DS . 'default';
$private = $default . DS . 'private';
$files = $default . DS . 'files';
$directories = array();

// Check for Private Files subdirectory.
$private_directory = _drush_file_private_path();
if (empty($private_directory)) {
  $private_directory = $private;
}
$directories[] = $private_directory;

// Check for Public Files subdirectory.
$public_directory = _drush_file_public_path();
if (empty($public_directory)) {
  $public_directory = $files;
}
$directories[] = $public_directory;

As an additional note, it would be amazing if a resource existed to see all deprecated/removed functions and their equivalent replacements. I can't even get decent results when using a search engine and the function name.

_drush_file_private_path()
_drush_file_public_path()

in the end were just wrapper functions of

\Drupal\Core\StreamWrapper\PrivateStream::basePath()
\Drupal\Core\StreamWrapper\PublicStream::basePath()

And you probably get the same from

\Drupal::service('file_system')->realpath('private://')
\Drupal::service('file_system')->realpath('public://')


reorder fields on user profile page I can't find any solution to reorder some fields on user profil pages (like user/%/edit). At first I see User photo and language options. But in field options I have set another fields to be applied to the first position.

I have no possibility to move some fields to wished position.
Have you any advice, how to do it? Thank you very much. Peter.

You need to go to "Admin > Configuration > People > Account Settings > Manage display". You will be able to reorder the fields from there. If you want to remove some of them from the display, you can select "Hidden" from the menu in the "Format" column.

EDIT:
The profile picture, however, is managed separately by Drupal, not as a field. If you want to be able to manage it, a workaround might be to disable the default Drupal profile picture (Admin > Configuration > People > Accounts > Personalization) and to create a new Image field to display the picture, which you can treat as any other regular field. There are even some modules that create the field for you, like user picture field.


Group repeating dates in Views I have this scenario:
The contenttype "event" has a date-field (with repeat-options). All repeating events are repeated for a certain timespan once a week.

I want to achieve this views-block:

Show me all repeating events (got this to work with condition
eventdate:rrule not empty).
Group by Event-Id and don't show me every repeating event (because
the description text of the event contains the human-readable
repeat-logic ... e.g. every tuesday at 12.00)

My Problem is:
I activated "Use aggregation" in the view and wanted to group the events by node-id, but the date field (field_data_field_event_date_field_event_date_value) is automatically added to the "GROUP BY"-SQL part when i do this (and i can't remove it)

Am I using the wrong approach?

I ran into similar problems and managed to fix it by enabling Aggregation on the view plus enabling 'Distinct'.


How to send email when customer cancel payment? I am using Drupal Commerce 7x-1.10 and PayPal WPS 7.x-2.3 module. How can I send an email to customer (both anonymous and authenticate), if they cancel the order or cancel the payment method or cancel anytime within the checkout process?

I am using rules, also I have use "cancelled" in the Condition section. But for some reason it is not working. Please see below for the rules code -

{ "rules_completing_the_checkout" : {
    "LABEL" : "Completing the checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:status" ], "value" : "canceled" } }
    ],
    "DO" : [
      { "mimemail" : {
          "key" : [ "commerce-order:mail" ],
          "to" : [ "commerce-order:mail" ],
          "cc" : [ "" ],
          "subject" : "Cancel Order? Why",
          "body" : "Cancel Order? Why",
          "plaintext" : "Cancel Order? Why",
          "language" : [ "commerce-order:state" ]
        }
      }
    ]
  }
}

I think you can implement it via the module Rules

Just add the action "Send email" for a custom rule that has the "order state changes" event conditionally on order state "cancelled."


Display Count of associated nodes as "more" in Calendar View? I'm using the Drupal Calendar module to create a monthly calendar view. As is default behavior the monthly calendar shows a list of the days events on each day. I have the Format Settings set to only display one event and then a "more" link. I would like to have the total number of events for that day next to the "more" link.

I attempted to add a "nid:count" aggregated field but it only counted for each node (so it was always "1") not per day.

How can I show the total number of events per day?

In your calendar view you can select format>Settings: Too many items to "Hide all add link to day" and it will show the totals for that day.


Is there a Grouped Product listing type in Drupal Commerce I have a Magento site I would really like to migrate to Drupal Commerce.  The one must-have feature is Grouped Product.  A grouped product will have a base product from which the product listing will use the photos, description, etc.  The related products will provide their titles, prices, etc. to the product listing.  See the photo for an example.

Can this be done with Drupal Commerce?

Thanks for your time and help!

Drupal Commerce does differentiate between products and product variations same as other systems, but the feature you're looking for hasn't been ported to Drupal 8 yet. It's easy enough to create a table with individual Add to Cart buttons for the variations in Drupal 8, but to have a single Add to Cart button for all variations on a product page, you'd need this module upgraded for Drupal 8:

https://www.drupal.org/project/commerce_add_to_cart_extras


Guzzle httpClient Drupal Core throwing cURL error 28 Operation timed out I have been loading the httpClient Core Service in a drupal 8 site. The service class works just fine when the request doesn't take too long from the API. It seems that if the request takes any longer than about 20-30 seconds the site throws a cURL response error 28 saying

GuzzleHttp\Exception\ConnectException: cURL error 28: Operation timed out  after 30000 milliseconds with 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in GuzzleHttp\Handler\CurlFactory::createRejection() (line 186 of ../vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php).

After a bit of poking around online I saw some reference to the fact that the "CURLOPT_TIMEOUT_MS" error doesn't work with all versions of php and they suggest to replace the reference to "CURLOPT_TIMEOUT_MS" to "CURLOPT_TIMEOUT" same for "CURLOPT_CONNECTTIMEOUT_MS".

In the above file with the error I found that in lines 374-380 which read the following

if (isset($options['timeout'])) {
  $conf[CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
}
if (isset($options['connect_timeout'])) {
   $conf[CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
}

if it's changed to the following

if (isset($options['timeout'])) {
    $conf[CURLOPT_TIMEOUT] = $options['timeout'] * 1000;
}
if (isset($options['connect_timeout'])) {
   $conf[CURLOPT_CONNECTTIMEOUT] = $options['connect_timeout'] * 1000;
}

removing the "_MS" then the site doesn't throw any errors.

Is this an error in the core code? Is this issue possibly related and can it be fixed with the patches attached to this d.o issue? Also please see this comment on that issue with reference to what I mentioned above.

Any suggestions or direction on this would be greatly appreciated!

As @cilefen suggested in his comments my problem was related to the timeout value that was being set in the calling code rather then an error with an undefined constant. I had fixed the error in my particular situation by adjusting the timeout value in my custom code that was making the API call with the following (600 is an example).

$request = $client->post($url, [
  'timeout' => 600,
  'json' => [array(...)],
]);


Media module: how to generate a pdf link? I'm trying to use the media module to generate a link to a pdf that I uploaded using media module. The problem is that when I insert the pdf that is on my library and select the link format, it displays a missing image and does not generte my link. What should I do to make it generate the link to my pdf?

Check out your file-types display settings in admin/config/media/file-types in combination with the field display settings you are using.


How do I use views_pre_execute I am trying to run a subquery  through views and found this call. I cannot get it to work. Here is how I am using it

function module_name_custom_views_pre_execute(&$view) {
    if($view->name=="view_name") {
            if($view->build_info['query_args'][1]==0) {
            $view->build_info['query']="my subquery";

                //echo ($view->build_info['query'] );
                //var_dump($view);
            }
    }
}

Without to test it I tried replacing the $view->build_info['query'] with the query generated in the view. Instead of a view result I get a blank page. Any other query I put in there myself results in a blank page as well.

I am writing the queries like so:

$view->build_info['query']="SELECT nid FROM node WHERE node.status='1'";

So I am not assigning any array objects values but rather writing the query in as if I would in any other db call. Should I build the query through the means of creating an object?  So something like this to start:

["build_info"]=> array(3) {
    ["query"]=> object(SelectQuery)#752 (21) {
        ["fields":protected]=> array(4) {
            ["nid"]=> array(3) {
                ["field"]=> string(3) "nid"
                ["table"]=> string(4) "node"
                ["alias"]=> string(3) "nid" }
        ["node_created"]=> array(3) {
            ["field"]=> string(7) "created"
            ["table"]=> string(4) "node"
            ["alias"]=> string(12) "node_created" }
        ["og_og_membership_label"]=> array(3) {
            ["field"]=> string(5) "label"
            ["table"]=> string(16) "og_og_membership"
            ["alias"]=> string(22) "og_og_membership_label" }
        ["node_title"]=> array(3) {
            ["field"]=> string(5) "title"
            ["table"]=> string(4) "node"
            ["alias"]=> string(10) "node_title" } }

Is there is another way to implement a subquery in views?

Using Drupal 7 Views 3

Also checkout http://drupal.org/sandbox/Fabianx/1184598 as this is adding a subquery to a view; which is exactly what your trying to do.


add custom design to Views Row i need to add custom css id/class to views row after row first. example:

in default i see this :

Now, I need change this to:

Actually i need to print result like this:

views-row-first
 <-- example: 100% width

views-row-even
 <-- example: 50% width +
 views-row-last
 <-- example: 50% width

With this i combination of one and two columns. 100% width and one column for first row And at the bottom 2*50% and two column for other(even/odd/last). How to?

NOTE: i work with content-node / unforrmatted list.

Why dont you just add the 100% to views-row-1 and width: 50% to views-row?
I believe that you do it like this:

.views-row {
  width: 50%;
  //other css
}

.views-row-1 {
  width: 100%;
}


Display two vocabularies I have a content type LAW with fields Title, law Category( Taxonomy Vocabulary) and Tags( Another taxonomy vocabulary) and last field is Description.

When Adding law content, I select in which category it belongs (lets say Labor law). I also add tags (e.g. Condemnation, Judgement) which are autocompleted as the default tags.

In view, I have displayed a list of all the categories, for example:

Labor law
Banking law
Land law

When Labor law is clicked, I want a list of tags (Condemnation, Judgement) related to labor law; on clicking Condemnation or Judgement the nodes should be displayed.

I've made something similar using normal taxonomy view for "category list" and made an exposed filter for "tags", and to show just tags related to the exact category i've used the "Views Selective Exposed Filters".


Double Wide Views Table I have a table listing that shows the Item # and a View/Print/Download link to open a PDF datasheet in a new tab.  Right now I have like 3 or 4 in the system but in time I will have like 700-800 of them and the columns take up less than half the width of the page and although I have been looking I can't find a way to create two columns

I don't care whether the data goes

CH098 View     CH099 View
CH100 View     CH101 View
CH102 View     CH103 View

or

CH098 View     CH101 View
CH099 View     CH102 View
CH100 View     CH103 View

Does anyone know if there is a module for views that I missed that can do this?

Since you're using Views, you've got everything you need.  You just need to set the Display Format to Grid, and set it to Show Fields, as in the following example from editing a view.

And to display more than one field in each Grid "cell", you will need to add a Global: Custom Text field to combine the fields for display. (Change the Content: Title and Content: Link fields used in these example to your fields.)

See the Image of Custom Text Settings (below) for an example of how to combine the fields. The Replacement patterns shows the fields available to be combined.

In the settings for each field, set Content: Title and Content: Link fields to be excluded from display, and set the Global: Custom text to NOT be excluded.

Oh, yeah... these images are from Views 3.x.

View settings:

Click the Settings link next to 'Grid' to set the 'Number of columns'. You can also set the display Alignment to Horizontal or Vertical.

Grid settings:

Global Custom Text selection:

Custom Text Settings:


(File) File: Path outputs only first item I have a view that renders a node page as a view, that node has e.g. 100 images, so technically they are all on same node, so then we go to views fields settings and untick the option to show images in same row. So now each image has it's own row.

Now we add the relationship for file to enable extra fields. We add the File field and it also gets printed next to every image.

Except problem is that it prints the same and only path of the very first image under every other image. It should print the path of each image in the same row.

EDIT: tried the https://www.drupal.org/project/image_url_formatter module, same. It outputs the very same first image field only.

View:

This is expected behaviour following from your Views configuration, there is no way to instruct Views to maintain a 1-1 relation between the (File) File: Path (which gives you one file path for each image) and the Content: Image (which gives you one image formatted field with multiple images included). As a result, they are 'combined' (cartesian product) and you should actually be getting a very long list of all combinations of images and image paths.

By using the Image URL Formatter module you should be able to do what you need, here is a screenshot:

I added the "Content: Image" field twice, each time unticking the "show images in same row" option. The first one was formatted as an Image, the second one as an Image URL. And things worked as expected.

Good luck!


Why is my Query not returning a result Background

I have a large table with lots of values and want to check if any of the names are repeating and only display those results. I have built a view and cannot get the SQL query to return the result I want.

Code

Here is the code as it stands, I've done loads of variations of it but cant get the result and think that there must be a core problem with my logic.

So I have built a view and selected a couple of column and now I want a column that will print out the name of the title the number of times it appears in the database. Or just count the number and print that.

<?php
  $value = $row->title;
  $query= "SELECT node.title, node.type
           FROM {node} node
           WHERE  (node.type IN ('institution')
           AND node.title  =".$value.")";
  $result= db_query($query);
  $wat = $result->fetchAll(PDO::FETCH_COLUMN, 0);
  foreach($wat as $res){echo $res;}
?>

So as you can see I get the value of title at the row I'm on and compare it to every value for title in the database, then return only results that match. After that I loop through them and get the value printed.

I have managed to get all the titles out and print them but as soon as i bring $value into it it breaks. I have checked the value of $value and it returns the expected result. I just cant figure out what is wrong with my SQL query.

Question

What is wrong with my Query? is there something that stops me using the $row->title in drupal that I don't know about?

Without access to your error logs etc. I'm going to assume the problem is that you are not putting quotes around your title string, so it is trying to use the title as a database column and it fails.

It should be like this:

AND node.title  = '" . $value . "')";

That is not a great solution either though because it opens you up to possible SQL injection attacks so instead, use Drupal's built in sanitisation like this:

$query = "SELECT title, type
            FROM {node}
           WHERE type = 'institution'
             AND title = :title";
$result = db_query($query, array(':title' => $value));

When you do it like that Drupal will sanitize the $value and it will also know that it is a string and wrap it in quotes.
For more information see the documentation for Drupal's database API - Static queries.

In the above example I also changed the type "IN" operator to "=" because you only had one value, removed the redundant brackets around the where clause and removed the table alias to make the query as simple as possible.

On the topic of EntityFieldQuery, there are multiple different ways to run a query in Drupal and the best solution depends on the particular use case.
If you want optimal performance and don't need to restrict results based on node access then db_query() is likely the best method.
Without knowing your requirements I couldn't advise on the best approach for your current query.


Data returned from the controller is not showing in the template file I am sending data from a custom module controller to a template file using the following code.

module.info.yml

name: Module
description: Module description
package: Custom
type: module
version: 1.0
core: 8.x

module.module

function module_theme($existing, $type, $theme, $path) {
  return [
    'module_template' => [
      'variables' => [
        'var' => [],
        'title' => ''
      ]
    ]
  ];
}

module.routing.yml

module.event:
  path: '/path/{dynamic}'
  defaults:
    _controller: '\Drupal\module\controller::RunQuery'
    _title: 'Module'
  requirements:
    _permission: 'access content'

module-template.html.twig

 test {{ title }}

{% for user in var %}

 {{ user.title }}

{% endfor %}

test 2

controller.php

namespace Drupal\module;

class controller {

  public function RunQuery($dynamic) {

    // Some query here which work fine and return what I want
    $ok = 'Some value';

    return [
      '#theme' => 'module_template',
      '#var'   => $ok,
      '#title' => 'Title',
    ];
  }

}

This will return only test and test 2 in the template file, so the template file is called by the module controller, but it does not show {{ title }} and {{ user.title }}.

I don't know what exactly you are trying to do as var never seems to be passed an array or object but I'll give you a working example. Your controller should extend ControllerBase and use public function content() to output stuff. Also pay attention to reference the correct namespace and pay attention to upper and lower case writing as well.

module.info.yml

name: Module
description: Module description
package: Custom
type: module
version: 1.0
core: 8.x

module.module

function module_theme($existing, $type, $theme, $path) {
  return [
    'module_template' => [
      'variables' => [
        'var'   => NULL,
        'title' => NULL,
      ],
    ],
  ];
}

module.routing.yml

module.event:
  path: '/path/{user}'
  defaults:
    _controller: '\Drupal\module\Controller\Controller::content'
    _title: 'Module'
  requirements:
    _permission: 'access content'

templates/module-template.html.twig

 test {{ title }}

{{ var.getUsername }}

test 2

src/Controller/Controller.php

namespace Drupal\module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;

class Controller extends ControllerBase {

  public function content(AccountInterface $user) {

    return [
      '#theme' => 'module_template',
      '#var'   => $user,
      '#title' => 'Title',
    ];
  }

}

Now you can access /path/1 or whatever user ID you want to get this user's name printed.

With the Devel sub-module Kint installed you can use {{ kint() }} or {{ kint(var) }} inside the template to check out what else you can get and print.


How do I update multiple rows in one single function call? I want to update multiple rows in one query, for example as with the following code.

db_query("update bestsellers set count = 4 where product_id = 30; update bestsellers set count = 5 where product_id = 32; update bestsellers set count = 1 where product_id = 34;")->execute();

The server returns a 500 error. Is there any way to achieve this?

While you can probably update multiple rows using one call to db_query(...)->execute() (if you use a single SQL query that will updates multiple rows), that's not what the OP code shows. The code try to execute multiple SQL queries with a single call to db_query(...)->execute(), which is not supported by the API. Also, as stated in its documentation for Drupal 7, db_query() should not be used for update queries. Instead, use db_update().

The following would be the clean and safe way to do it with multiple db_update() queries

$counts = [
  30 => 4,
  32 => 5,
  34 => 1
];
foreach ($counts as $product_id => $count) {
  db_update('bestsellers')
    ->condition('product_id' => $product_id)
    ->fields(['count' => $count])
    ->execute();
}

It may also works with a query using a CASE in in the SET clause

db_query("
    UPDATE bestsellers
    SET count = CASE product_id
        WHEN 30 THEN 4
        WHEN 32 THEN 5
        WHEN 34 THEN 1
    END
    WHERE product_id IN (30,32,34)
")->execute();


How can I export only one paragraph type, the fields, the form settings and the display settings? Some days ago I've exported and imported a full configuration with drush cex and drush cim.
What are the steps to export 1 paragraph type including the fields, form settings, display settings etc ...
I'm using a multisite, so it would be great to copy them from one site to the other sites within the multisite.
Can I:

drush cex site 1
copy exported .yml files to other site in folder (sites/site1.multisite.com/files/config_HASH/sync)
Delete all .yml files except those needed for the import of my paragraph type?

I guess there are better methods to establish this?

That's exactly what the Features module is for. Syncing partial config across multi-site instances.

The features module enables the capture and management of features in
Drupal. A feature is a collection of Drupal entities which taken
together satisfy a certain use-case.
Features provides a UI and API for taking different site building
components from modules with exportables and bundling them together in
a single feature module. A feature module is like any other Drupal
module except that it contains additional information in its info file
so that configuration can be checked, updated, or reverted
programmatically.

That means you would create a feature on your main multi-site instance which contains the paragraph type. Have it placed inside the modules/features/ folder. Related config will be added automatically. You then enable the feature (which basically is just another module) in another multi-site instance. The config will be imported into the database. On both multi-site instances you then export config as usual. Because every multi-site instance still is managed from its own config. Which then also contains the synced paragraphs config.
As soon as you add another field to the paragraph type on either multi-site instance Features will recognise the changes. You then can recreate your paragraph feature and import the changes on another multi-site instance (into the database). Finally, on both sites again export config as usual (which then also contains the paragraph types you've synced via Features). Features enables you to keep track of changes to a feature via built-in diffing, which after you recreated the feature (partial config gets exported) can be synced into the database on other multi-site instances again.
Of course Features also comes with a set of Drush commands to make your live easier.


Add placeholder in registration form and removing labels I wanna customize my registration form on drupal 7. I wanna add placeholders and remove the labels. How can I do that? Thank you

This could be easily done my hook_form_alter in your custom module. See example below:

Suppose you have a form with id as 'your_form_id' and are looking at overwriting title and placeholder text for a field named 'yourfield', you can create a custom module and add this code to your custom module.
You will need to replace 'yourmodule' with the name of your module. Same with 'your_form_id' and 'yourfield'.

     /**
     * Implements hook_form_alter().
     */
     function yourmodule_form_alter(&$form, $form_state, $form_id) {
       switch($form_id) {
         case 'your_form_id':
           $form['yourfield']['#title'] = t(''); // Remove title from yourfield.
           $form['yourfield']['#attributes']['placeholder']= t('Your placeholder text'); // Set placeholder text for yourfield.
           break;
       }
     }

The t() method is used for internationalisation.

Let me know how you go...


Adding a Serial (cck field) to the Page Title I don't really know PHP or how to modify the Drupal API so it would probably have to be a solution in the Drupal interface or rather simple programming.

Is it possible to have a Serial cck field automatically combine with the page/node title? Example, Title: Update Example Task. Serial (job number): 225 -- Automatically combine to make the page/node title: 225 Update Example Task  -- So it can be referenced as a autocomplete term with either the Serial field or the Title

Thanks for any input!

Checkout auto_nodetitle, you could add the serial field as a token to the node title automatically.

The rest should then just fall into place.


User module functions undefined in custom module I am attempting to use the user_password() and user_save() functions from user.module in my custom module file, but I only receive the following:

  Fatal error: Call to undefined function user_save() C:\xampp\htdocs\drupal-7.38\sites\all\modules\(modulename)\(modulename).module on line 1037

I get a similar error if I comment out all of my code, leaving the module file as

<?php
user_save();

As far as I know, if the only problem was the lack of parameters, it chould be an entirely different error, not 'Call to undefined function'.

The function in which I'm trying to use user_password() and user_save() is as follows:

function create_user_by_id($id){
    $password = user_password(8);
    $info = soap_info($id);
    $fields = array(
        'name' => $id,
        'mail' => $info['mail'],
        'pass' => $password,
        'status' => 1,
        'init' => 'email address',
        'roles' => array(
            DRUPAL_AUTHENTICATED_ROLE => 'cas authenticated user'
        )
    );
    $account = user_save('', $fields);
    drupal_mail(
        'user',
        'register_no_approval_required',
        $info['mail'],
        NULL,
        array('account' => $account),
        variable_get('site_mail', 'noreply@example.com'));
}

So you are just calling a function without telling drupal how to access that function , you can tell drupal about where to find this function using this code :

 module_load_include('module', 'user', 'user.module');


White screen of death in hook form alter I have enabled simplenews module in drupal 8 and I am trying to reduce the width of input field from 60 to 30. I am trying to implement form alter hook and have devel module installed. I used  dsm($form_id); to identify form and then in order to identify the form attribute to change, I tried to use dsm($form), dpm($form) and print_r($form) and all these are giving white screen of death.

function custom_newsletter_form_alter(&$form,  $form_state, $form_id) {
  if ($form_id == 'simplenews_subscriptions_block_2138c21c-6453-4b7d-92d6-9407e427a78a') {
    dsm($form);
    dpm($form);
    print_r($form);
  }
}

I have tried different drupal 8 installations both localhosted and web hosted, tried with different themes but I am not able to print form. Is there any other way to identify/target correct form attribute to change like DOM inspecter of firebug?

It seems that dsm() and dpm() are not supported in Drupal 8. They are replaced by kint(). I have enabled the devel kint sub-module and used kint($form) to print my form array. You can also use ksm($form).


What function does Drupal provide to save an array in a file? I am writing a module that handles a large associative array which has string keys and floats values.

$array = array('hello' => 122.23, 'name' => 334.3, /* etc... */);

I was thinking of storing it in the database by serializing it, but the array size is dynamic, so I thought of storing it in a file to reduce access time.

What functions should I use to create the file, write the content, and read the array from the file?

Apart from PHP functions for reading/saving data in files, Drupal 7 has file interface functions too; one of those is file_unmanaged_save_data() which saves data in a file. The difference between those Drupal functions, and the equivalent PHP functions is that the Drupal functions can handle the case the module is trying to save the content in a file that already exists. See FILE_EXISTS_ERROR, FILE_EXISTS_RENAME, and FILE_EXISTS_REPLACE.

There are file interface functions that save a reference to the file created in a table. This can be useful in the cases the files needs to be automatically deleted because they are temporary, or programmatically deleted. See for example file_copy(), and file_move().

About using a database to save serialized data, that is what Drupal already does with the table containing the value of Drupal variables defined from modules. Its database table is defined as follow. (I show the definition used from Drupal 7, but Drupal 6 uses a similar definition.)

  $schema['variable'] = array(
    'description' => 'Named variable/value pairs created by Drupal core or any other module or theme. All variables are cached in memory at the start of every Drupal request so developers should not be careless about what is stored here.',
    'fields' => array(
      'name' => array(
        'description' => 'The name of the variable.',
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
      ),
      'value' => array(
        'description' => 'The value of the variable.',
        'type' => 'blob',
        'not null' => TRUE,
        'size' => 'big',
        'translatable' => TRUE,
      ),
    ),
    'primary key' => array('name'),
  );

During bootstrap, Drupal loads all the variables from the database, and saves their values in a global variable. This is the code used by Drupal for this purpose. (The function is variable_initialize(); the Drupal 6 function is variable_init(), called in the same circumstances.)

  // NOTE: caching the variables improves performance by 20% when serving
  // cached pages.
  if ($cached = cache_get('variables', 'cache_bootstrap')) {
    $variables = $cached->data;
  }
  else {
    // Cache miss. Avoid a stampede.
    $name = 'variable_init';
    if (!lock_acquire($name, 1)) {
      // Another request is building the variable cache.
      // Wait, then re-run this function.
      lock_wait($name);
      return variable_initialize($conf);
    }
    else {
      // Proceed with variable rebuild.
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
      cache_set('variables', $variables, 'cache_bootstrap');
      lock_release($name);
    }
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

  return $variables;

Drupal doesn't have performance issues, even if that function is called for every rendered page. As you can see, it caches the value of the variables in a cache. If your data is requested frequently enough, you could consider using a cache table too.

As for using persistent variables to store data, keep in mind they are loaded in memory every time Drupal bootstrap; if you are going to store data that could not be used for the currently loaded page, then persistent variables are not what you should use for storing your data. Also, since variable_set() clears the cache used for the persistent variables, it is generally preferable to reduce the number of calls to variable_set() done for a single page.


List of content types posted/commented by users I follow I'm running a D7 system Where users can follow each other using 'Follow' flag on user's profile.

Now I've been assigned a task to come up with a view where I can have a list of content posted/commented by people I follow.

I tried so many ways but no luck.

Humm, I couldn't find a way to easily put them all together (comments and nodes authored by the users followed) but could create separate views.

For nodes created is easier:
Create a new View, change from Show Content to Show Users and in the Relationship add a Flags: User flag, choose your flag and Current user.

For comments created:
Create a new View, select Show Comments. In the Relationship add Comment: author to expose the Authors ID, select require this relationship. Add new Relationship, this time look for Flag: User flag, select the author's relationship created before and your flag.

As stated before, you might get all the content together but I couldn't get it in any easy way.


Get term value from referenced node Drupal 8 Twig
I have a content, which have entity reference field field_field_data_provider_ref, referencing another content, which itself contains a field field buisness_property_type (single taxonomy term)

 {{ node.field_field_data_provider_ref.entity.buisness_property_type.value }}

 {{ node.field_field_data_provider_ref.entity.buisness_property_type|views }}

doesn't work for me

If the referenced field is a taxonomy term, you need to specify what property to show (usually the name). So your solution should be like

{{ node.field_field_data_provider_ref.entity.buisness_property_type.name.value }}

or, as NoSssweat said, with correct spelling (check your fieldnames)

{{ node.field_field_data_provider_ref.entity.business_property_type.name.value }}

also, I assume your machine name is field_business_property_type, so its

{{ node.field_field_data_provider_ref.entity.field_business_property_type.name.value }}

also, your field field_field_data_provider_ref is named field_data_provider_ref, then it's

{{ node.field_data_provider_ref.entity.field_business_property_type.name.value }}

Check your field names!


The vendor class doesn't autoload I am trying to port the Infusionsoft module to Drupal 8 and I need to load the infusionsoft/php-sdk library.  I have been racking my brain all day trying to figure this out, but I cannot get the class to autoload.  I do not know if this is because it is a custom module and not hosted on drupal.org yet or what.

I have added the requirement to a composer.json file in the module:

{
  "require": {
    "infusionsoft/php-sdk": "dev-master",
  },
}

And told the root composer.json file to include the module's composer.json file:

{
  "extra": {
    "merge-plugin": {
      "include": [
        "core/composer.json",
        "modules/infusionsoft/composer.json"
      ],
      "recurse": true,
      "replace": false,
      "merge-extra": false
    },
  },
}

Ran

composer update

and also tried

composer install

Both give me the vendor files.  I have uploaded those files to the remote server's vendor directory, yet they are still not being loaded.

I have read several other posts on here and many other sites, but none of the answers are up-to-date with Drupal 8.5.2.  And the composer manager module method is depreciated.

I don't know if this is an issue with their sdk's structure or if I need to upload a another/different file(s) to the server, but instantiating the class breaks.

use Infusionsoft\Infusionsoft;
$infusionsoft = new Infusionsoft([
  'clientId'     => $id,
  'clientSecret' => $secret,
  'redirectUri'  => $redirect,
]);

Any help is greatly appreciated! Thanks!

Both give me the vendor files. I have uploaded those files to the remote server's vendor directory, yet they are still not being loaded.

What files did you upload exactly? It's not enough to upload just the new files from your package, installing packages with composer also updates its own autoloading files to make sure it knows where to load that and you probably forgot to upload those, that's the only explanation I have at least.

Try uploading all the files in vendor/composer as well or to be sure, all the files in vendor.


Validating a node body hello i am trying to validate the content of the node body for certain text having some trouble with it. it outputs an message "array".

function test_form_alter(&$form, FormStateInterface $form_state) {
  // Custom validate function.
  $form['#validate'][] = 'submitForm';
}

function submitForm(array &$form, FormStateInterface $form_state) {
  $author = $form_state->getValue('author');
  $body = $form_state->getValue('body');
  $title = $form_state->getValue('title');
  drupal_set_message('Thanks for submitting the form! you typed in the following as author:' . $author . ' . body:' . $body . '. title:' . $title);
}

You get the outputs message as an array, because you supplied $body and $title as arrays, and $form_state->getValue('author'); doesn't give you author of node test with the following code:

function test_form_alter(&$form, FormStateInterface $form_state) {
  // Custom validate function.
  $form['#validate'][] = 'validateForm';
}

function validateForm(array &$form, FormStateInterface $form_state) {
  //- Get the author id.
  $author_uid = $form_state->getValue('uid')[0]['target_id'];
  // Load the author account.
  $author = User::load($author_uid);
  //- Get the body value, if you want just the summary change value by summary.
  $body = $form_state->getValue('body')[0]['value'];
  //- Get the title value .
  $title = $form_state->getValue('title')[0]['value'];
  //- Use addMessage instead of drupal_set_message its deprecated.
  \Drupal::messenger()->addMessage('Thanks for submitting the form! you typed in the following as author:' . $author->getAccountName() . ' . body:' . $body . '. title:' . $title);
}

Don't forget to add the following use:

use Drupal\Core\Form\FormStateInterface;
use Drupal\user\Entity\User;


Select Entity with condition on node id I am trying to select an Entity with a condition on the node id.
Here's the query I use:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'event')
    ->propertyCondition('status', NODE_PUBLISHED)
    ->fieldCondition('nid', 'value', $id, '=')
    ->range($page, 1);
$result = $query->execute();

I get the following error:

  EntityFieldQueryException: Unknown field: nid in EntityFieldQuery->addFieldCondition()

How can I resolve this issue?

For EFQ, you need to filter on the entity condition column entity_id which is the node id.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->entityCondition('entity_id', $id)
    ->entityCondition('bundle', 'event')
    ->propertyCondition('status', NODE_PUBLISHED)
    ->range($page, 1);
$result = $query->execute();


What is the node:id cache tag equivalent for blocks? I am wondering why the last two entries do not work:

public function getCacheTags() {
  $tags = [
    'node:270',
    'node:271',
    'node:273',
    'node:282',
    'block:customblockname',
    'block:7',
  ];
  $cacheTags = Cache::mergeTags(parent::getCacheTags(), $tags);

  return $cacheTags;
}

When I edit my custom block the URL is:

  /block/7?destination=/admin/structure/block/block-content

The actual id of the block (for instance when embedding it) is customblockname.

What are the correct cache tags to include that block in my caching?

I just figured myself. The cache tag for custom blocks is simply:

block_content:7