Creating a custom field view using theme_field template Folks - I'm trying to create a custom field view with custom content that utilises the standard theme_field template, to display in a node template.

I've tried to call the function programmatically e.g:

  $field_vars = array(
    'title_attributes' => 'test123',
    'label' => t('custom field label'),
    'items' => array('
This is a test
'),
    'classes' => 'test',
    'attributes' => FALSE
  );
  $my_field = theme('field', $field_vars);
  print $my_field;

It returns the template, but none of the $field_vars are being used.  Has anyone done something similar?

I'm not really sure what you are trying to do, but if you only like to render a custom array with the field template this should work:

$field = array(
  '#theme' => 'field',
  '#field_type' => 'text',
  '#field_name' => 'temp_field',
  '#entity_type' => 'node',
  '#bundle' => null,
  '#items' => array(
     array(
       'value' => '',
     )
   ),
   0 => array(
     '#markup' => '
This is a test
'
   )
);
print theme_field(array(
  'label_hidden' => false,
  'label' => t('custom field label'),
  'items' => array($field),
  'classes' => 'test',
  'content_attributes' => '',
  'attributes' => '',
  'item_attributes' => ''
));

You can load one of your existing field using field_view_field() to check what data the renderable array contains. For example to load the body field from a node with an id equal to 1000 you could do like this:

$node = node_load(1000);
$field = field_view_field('node', $node, 'body');
print_r($field);


How to make a node appear across *all* Taxonomy terms? I am creating and classifying nodes by:

A main taxonomy
A secondary geographic location taxonomy

I created a View for the display of these nodes. It accepts a term ID from the main taxonomy via URL, and provides a Hierarchical Select "exposed filter" for further filtering by geography within the displayed nodes.

I notice that if a user does not select any location from the exposed filter, all nodes from across the world are displayed. But when I select USA, only USA nodes are displayed.

That is the desired behavior, however, I need to create some nodes that have "Worldwide" scope, and appear in the view even when the geographical filter is activated. It would be a great hassle to create nodes for each and every location.

I could hardcode this in some way: I even considered a separate taxonomy of worldwide nodes, and creating a block which is always displayed on top of the filtered results. But the problem with this is that the order of node-creation is also important, and my solution would appear disjointed.

Any ideas to nudge me in the right direction would be greatly appreciated.

Assuming I understand you correctly... why don't you create a custom checkbox field "Worldwide?" for the node type? Then in any views you could insert an OR checking if the node has it set. Still, you would be able to group the results by another field, such as geographical region name.

This is where you get the dialog in Views3


How to debug Batch API more efficiently? I've some issues with Feeds importing (I don't want to focus on particular case) and I'd like to find the way of able to debug Batch API processing more efficiently. Given the fact of complexity of Feeds module (a plethora of classes), I can't easily implement one-time processing in a short time.

Here are the methods which I'm aware so far:

using dd() from Devel and tail -f drupal_debug.txt (minus: not time efficient)
using watchdog() like watchdog('foo', '<pre>'. print_r($foo, TRUE). '</pre>'); then drush watchdog-show --tail --full to monitor in real-time
using XDebug and its xdebug.auto_trace (minus: non-interactive excess of trace logs)

but they're not helpful in particular case and at the same time I'd like to learn something new.

Ideally I'm looking for some easy way to convert Batch API into standard non-AJAX processing, so I can do old-school var_dump($var); exit; and refreshing the page by sending the same POST requests over and over again, unless there are some more efficient ways. I'm also considering temporary core hacks to achieve that.

Any ideas?

Here are some workarounds which I've found so far which makes life easier.

Using curl

You need: drush and curl.

Add var_export($name); exit; into the batch code place of interest, so batch won't be set to finish state.
In the web browser open Network console (e.g. DevTools in Chrome).
Start batch process as usual (in Feeds it's at: /import).
Stop the batch processing just before the redirect by pressing Escape. Then note the URI.

Alternative way is to fetch id directly from the batch table:

$ drush sqlq "SELECT bid FROM batch"

Click on the previous 302 request and take a note of your session cookie from Request Headers, you need only SESS0X=Y cookie, e.g.

Cookie: SESS0F00=B4R

Run curl as below (you need to replace id, session cookie and your host):

$ curl -X POST -d "id=124&op=do" --cookie "SESS0F00=B4R" "http://myhost.local/batch"
your_debug_data_here

Previous step is repeatable after each code change which makes it easy to debug variables in no time.

For ever more efficiently, you can map it (e.g. in vim), so the output can be executed each time when you need it.

Using repeatable XHR requests

Add var_export($name); exit; into the batch code place of interest, so batch won't be set to finish state.
In the web browser open Network console (e.g. DevTools in Chrome).
Start batch process as usual (in Feeds it's at: /import) and it should fail, because of exit; added in step 1.
Note the batch?id=x&op=do request and do Replay XHR (at least in Chrome).
Now on each code change you should be able to repeat the last step over and over again.

There are probably more ways of doing similar thing (including use of some plugins such as Postman, etc).


Is MySQL 5.7 compatible? My server has been on MySQL 5.6 for quite awhile and now I need to upgrade to MySQL 5.7. Is it safe to upgrade to 5.7 for all of my Drupal 7.x sites? Just doing a quick google for drupal 7 mysql 5.7, I get a few people reporting issues when updating with Drupal 7.x.

Yes. MySQL 5.7 is compatible with D7.x. Per the docs:

  Drupal 7 supports MySQL 5.0.15/MySQL 5.1.30/MariaDB 5.1.44/Percona
  Server 5.1.70 or higher, and requires the PDO database extension for
  PHP (see What is PDO?).

Is it safe? Maybe. It depends on your code/infrastructure setup.

Just because a web application is compatible with a version of a DB server, doesn't mean an upgrade will happen flawlessly. There can be many things that could go wrong (e.g. hidden dependencies).

It will probably be fine with a minor version upgrade, but always have a test/backup plan in place when rolling out infrastructure changes.


Disable cache a custom block for anonymous user I have a custom block, it displays in every pages with dynamic data calculates in every refresh, How can I disable cache for this block for anonymous users?

I try with:

public function build() {
  return [
    '#markup' => time(),
    '#cache' => [
      'max-age' => 0,
    ],
  ];
}

It won't work.

Edit:
I don't want to disable the cache for the entire page, I just need a specific block not to be cache.

If you want to completely disable caching for the block, use this function in your block class:

  public function getCacheMaxAge() {
    return 0;
  }

I've never found in the documentation why

'#cache' => [
      'max-age' => 0,
    ],

doesn't work with blocks but, like you discovered, it doesn't seem to.


How to debug a configuration object, when testing? I write tests for a custom module using Drupal\simpletest\WebTestBase. I can not find a method, how to debug the configuration object.

I tried e.g. the following commands:

$config = \Drupal::config('mymodule.settings');

debug($config); // AJAX-HTTP-Error
debug(get_object_vars($config)); // Empty array
debug($config->getRawData()); // Empty array
debug($config->getOriginal()); // Empty array
dump($config); // AJAX-HTTP-Error
var_dump($config); // Needs extremely long time
ksm($config); // Nothing is shown
kint($config); // Nothing is shown
dpm($config); // ServiceNotFoundException
dpm($config->toArray()); // AJAX-HTTP-Error
dsm(get_object_vars($config)); // ServiceNotFoundException
print_r($config); // Needs extremely long time

The debug() command works fine for arrays and strings (and is nice integrated in the test report).

 debug($var, 'Label');

You can use Config::get(), for which:

  If no key is specified, then the entire data array is returned.

e.g.

debug(\Drupal::config('mymodule.settings')->get());


added files to module: use drush to upgrade to a new version of this module will added files be deleted? A co-worker has added a couple of .css files to the quicktabs 3rd party module.  What will happen if you use drush to upgrade to a new version of this module.
Will these added files be deleted or kept as-is?

If the css files are stored in the quicktabs module directory, yes they will be lost upon upgrade.


How do I use Bootstrap scrollspy? I would like to use Bootstrap's scrollspy plugin in Drupal 8.
So I edited the html.html.twig file replacing

<body{{ attributes.addClass(body_classes) }}>

With

<body{{ attributes.addClass(body_classes) }} data-spy="scroll" data-target=".nav-scrollspy" data-offset="50" >

Where .nav-scrollspy is the class of my navigation block. Additionally I added the following JavaScript to my theme:

$('body').scrollspy({ target: '.nav-scrollspy' });

But as this does not work I were wandering whether or not this plugin is already integrated in Drupals Bootstrap theme. Apparently not, as I could not locate such a file in themes/bootstrap/js/.

Unfortunately I did not find such a file in the web neither, so I am asking my self, where to get it and how to add it to Drupal?

AFAIK your bootstrap theme will be having bootstrap.js or bootstrap.min.js included. Generally, scrollspy plugin related code will be inside these files.

So try to recheck whether you have added nav-scrollspy to your div element. I think you might need to have 'id' for your div element and a proper link to it.

Section 1

Section 1

Try to scroll this page and look at the navigation bar while scrolling!

Also in Drupal 8, caching is a bit aggressive so try to rebuild your cache and check again. For better understanding refer http://www.sitepoint.com/understanding-bootstraps-affix-scrollspy-plugins/


Color code field in View? Use case:  When the Status is Overdue, the word overdue should display in red, and if it's Accepted, it should display as green.

I was hoping to use Rules to set this up, but don't see options to get this logic in.

You can use Style Settings in the field setting and and use replacement tokens as a css class.


How to prevent article titles to become links I am making a website in Drupal 8. I made a new content type 'Slide' and a view called 'Presentation' that shows all slides as a blog page. I enabled the pager and set it to 1 item per page. This results in a nice slide show. See screenshot ('presentatie' is Dutch for 'presentation'):

The slides are small articles, containing text content and an image. They are shown by the Presentation view as full content, but their titles are still shown as links to the full article (slide) content. I don't want this linking, because by going to the full article, you leave the presentation page with pager for navigating through the slides. See screenshot of result on site below:

I am pretty new to Drupal and I can not find where or how to switch this off. Could anyone tell me?

To remove link from Title, what you have to do is click on the title field in views, and there is a checkbox Link to the Content. To unlink this, you have to uncheck this field. I am attaching a screenshot to it :


meta tags not appearing I am using Drupal 7, and I have strange problem with meta tags. For some content type even if I enter meta title, meta keywords and description, they don't get effective on page.

Where in for some content type it does reflect the meta information.

How can I narrow down the problem? I have no idea how I can make use of meta tag quick module for my problem because meta information is not getting generated.

How can I debug where the problem exists?

I searched for this a while and found some solutions.

The thing is make sure you have rendered the <?php print render($page['content']['metatags']); ?> in page--front.tpl.php


Redirect based on query string I'm migrating a legacy blog from a home-grown CMS to Drupal 7 and I need to wrap my head around how I'm going to redirect URLS to a new aliased pattern.

The legacy site's URLs use query strings /?t=40&an=49187&anc=570&format=xml which then redirect to an aliased url like /blog/i-know-this-is-not-ideal. Most of the listing pages on the site use the query parameters to link to pages, though others use the aliased urls. The an parameter appears to refer to their version of a Node ID, which I'm able to parse and store in my migration.

The company who owns this platform was kind enough to sent me an Excel spreadsheet with aliases in one column and query strings in another — so I have something at least.

Maintaining SEO juice is critical for this client — and Google has parsed these query parameters in many cases.

Should I look towards writing a custom module for this, as the Redirect module appears not to provide support for query parameters? Or should I look into htaccess rewrite rules?

I think a small custom module will probably be the method with the least overhead. You could store the legacy ID in a field during the migration and access it from there if the appropriate query string is set.

Very rough examples...

Drupal 7:

mymodule.module

function mymodule_init() {
    if (!empty($_GET['an'])) {
        $query = new \EntityFieldQuery();
        $result = $query->entityCondition('entity_type', 'node')
            ->fieldCondition('field_old_id', 'value', $_GET['an'])
            ->execute();

        if (!empty($result['node'])) {
            $nids = array_keys($result['node']);
            $nid = reset($nids);
            drupal_goto(url("node/$nid"), [], 301);
        }

    }
}

Drupal 8:

mymodule.services.yml:

services:
  mymodule.redirect_subscriber:
    class: Drupal\mymodule\RedirectSubscriber
    arguments: ['@entity_type.manager', '@path.alias_manager']
    tags:
      - { name: 'event_subscriber' }

src/RedirectSubscriber.php:

namespace Drupal\mymodule;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Path\AliasManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class RedirectSubscriber implements EventSubscriberInterface
{

    protected $nodeStorage;

    protected $aliasManager;

    public function __construct(EntityTypeManagerInterface $entity_type_manager, AliasManagerInterface $alias_manager)
    {
        $this->nodeStorage = $entity_type_manager->getStorage('node');
        $this->aliasManager = $alias_manager;
    }

    public function Redirect(GetResponseEvent $event)
    {
        $old_id = $event->getRequest()->get('an');

        if (!empty($old_id)) {
            $ids = $this->nodeStorage->getQuery()
                ->condition('field_old_id', intval($old_id))
                ->execute();

            if (!empty($ids)) {
                $nid = reset($ids);
                $url = $this->aliasManager->getAliasByPath("/node/$nid");
                $event->setResponse(new RedirectResponse($url, 301));
            }
        }
    }

    static function getSubscribedEvents()
    {
        $events[KernelEvents::REQUEST][] = array('Redirect', 20);
        return $events;
    }
}


View displays nodes that should be excluded by filter I'm working on the website for my bicycle shop. I've created a series of views that display the different types of bicycles we have: touring bikes, city bikes, etc. There is also a view that displays all the bikes.

In order to hide display of bikes that have been sold already (i.e. have 0 stock), I have the following filter criteria:

Stock: Level (>0) OR
Stock: Active (No)

(There is the provision that if the stock level is not set to active it's ok for the stock to be zero, because there are some products that we don't track the stock of).

When someone buys a bike, the stock is decreased by 1 (to 0, most often), and the bike should then disappear from the view.

Except that it doesn't.

Eg. The first bike on this page - if you click on it, it says it's sold, and the stock is set to active, and the stock number is zero.

My question is: why does it still appear in the view? I have cleared the caches, re-created the view... If I create a new view that has no filters except the criteria "Stock level > 0", the aforementioned bicycle with stock=0 still appears!

Please tell me what I'm doing wrong.

Cheers,
Chris

Your filter says, "if the stock level is greater than 0 (1,2,3,4...) OR stock is not active, don't show the product". You want it to say, "if the stock is equal to 0 ( or <=0 ) OR stock is not active, don't show the product“. In other words: Stock: Level (=0) OR Stock: Active (No)

On second thought, if you're not filtering out, you would want Stock: Level (>0) OR Stock: Active (Yes) to show all bikes that are active, and have more than 0 in stock.


Do not map (update) some fields with migrate in update action I have a custom migrate import that imports some fields like:

...
$this->addFieldMapping('title', 'title');
$this->addFieldMapping('body', 'description');
$this->addFieldMapping('created', 'created');
...

If I run an update of some items (the source data is a live site) I don't want to update the title or body fields because editors are changing this content in the drupal site.

I'm using this workarround but I'm not sure this is the best way to do this:

/**
 * Migrate prepare method.
 */
public function prepare($entity, $row) {
  if (isset($entity->is_new) && $entity->is_new === FALSE) {
    unset($entity->body);
    unset($entity->title);
  }
}

Thanks!

Good news! You are doing this exactly right. By "unsetting" the fields in the source data you are taking the proper approach. This practice is common and the relative snippet of documentation is buried a bit in the Migrate Handbook:

  To use default values for NULL or '' or array() values, be sure to remove the item with unset() in your prepareRow() [or prepare()] function.

From https://www.drupal.org/node/1133448

Good luck with the migration!


Authcache Caching Cancelled due to php error I have authcache installed on my Drupal site that runs on commerce(not Kickstart)

On all the page I am getting

Cache Status: "Caching CANCELED"
Message 1: "Canceled: PHP Error: "

I enabled database logging but I don't see any additional information there.

My pages are rendered properly and there is no errors being displayed on the page. So I am curious about the source of PHP Error that Authcache keeps referring to.

Ironically there is an error in the error-reporting code of Authcache 7.x-2.0-beta2. Apply the patch from issue #2161095, after that the PHP error message will be displayed correctly by the debug widget.


Define Access Control based on URL Path Is there a contrib module that can define access control based on the url path of content? So if an anonymous user goes to www.mysite.com/pages/test they can reach it, but if they go to www.mysite.com/hidden/stuff they can't get to it since it is in the /hidden/ path and they don't have an authenticated role.

I've already looked into controlling it based on content types, workbench groups, etc. Don't want to go with Workspaces since it is experimental and requires a whole other suite of modules to function.

Ideally, I'd like to be able to allow and block users with certain roles access to content that follows a specific path. Hoping there's something that already exists to handle this.

What we ended up using was an existing module that we have already installed (Context) along with a custom block.

We created a new context for hidden sections of our site using the condition of the request path and the user role anonymous. From there our two reactions were to hide all sections within our theme except ones for help messages to our users, and to add a custom block to that help section.

Works like a charm and is fairly straightforward to change and keep track of in config.


Special type of nginx redirect: redirect only if $request_uri is empty I need a special type of redirect for a Drupal 6 website. I'm thinking that the best place to do this is in an nginx config file, but please correct me if I'm wrong. I know I can do it in a template file/module by checking $_GET['q'] and then using drupal_goto(), but I don't want to load the full bootstrap only to do a redirect.

Basically, I need to redirect www.domain.com and domain.com to subdomain.domain.com ONLY if I don't have anything after the domain part. This means that domain.com/node/3 should NOT be redirected.

I hope it makes sense and thank you in advance for your help :)

Ok, I've found the solution. I'm adding this to my existing nginx config:

location = / {
  rewrite ^ http://subdomain.domain.com permanent;
  break;
}

This redirects the top level domain but leaves all the existing "deep" links intact. If anybody wants to know why I'm doing this, it's good for SEO. I'm keeping the old URLs intact (as an archive) but redirect the domain to my new website.


How to make one field's appearance on form depend on another field Please I need to create a field whose appearance on my form depends on the field immediately preceding it.

For example in field A the user is asked a true or false/yes or no question. E.g Do you like the English premiership?

If he answers true, a previously hidden field B (which is a taxonomy term)is presented to the user e.g Choose your preferred English Premiership club.

If he answers no, nothing happens.

P.S. Both field will be created via Profile 2 module.

Thank you.

You are looking for Conditional Fields module.

Description on module page says -

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition.


"You cannot send more than 5 messages in 1 hour" I have several contact forms, but I don't want to limit the users to submit the form. I've tried form unblock with smart IP; it doesn't work for me.

Do you have any idea to release the IP and unset the limit?

Change it using drush config-set.

To get the default settings use:

drush config-get contact.settings

To change the limit to 100 instead of 5, use:

drush config-set contact.settings flood.limit 100


How to register Field Handler class with Migrate module I'm trying to use the migrate module to import some video fields. I'm assuming that I'll need to write an extension to the MigrateFileFieldHandler. I set up a shell class based on what I saw in the MigrateImageFieldHandler (which is a subclass of MigrateFileFieldHandler), however my class doesn't seem to get loaded.

My guess is that I need to register my Field Handler somewhere, somehow, but I can't find any instructions or examples anywhere. I know that I register Migrations in the hook_migrate_api but I can't find how or where I need to register Field Handlers.

From this blog post it looks like you register the field type from within your custom class:
http://openconcept.ca/blog/mmallett/migrating-data-using-drupals-migrate-module

as such:

class MigrateCUSTOMFIELDNAMEFieldHandler extends MigrateFieldHandler {
  public function __construct() {
    $this->registerTypes(array('email'));
  }
// more stuff in your class ...

Without such information migrate usually just silently ignores the field, or try to work with it in any way. The same rule for an improperly named/implemented Migration class -- you just don't see it in drush ms.

EDIT:

From the blog post, actually from MigrateExtras README:

  The Migrate Extras module provides extensions to Migrate
  (http://drupal.org/project/migrate) to support various contributed
  modules. The ideal place to implement migration support for a
  contributed module is in that module. That way, the migration support
  is always self-consistent with the current module implementation -
  it's not practical for the migrate_extras module to keep up with
  changes to all other contrib modules. Support for contributed modules
  may be added to migrate_extras for two reasons - if the module's
  maintainer does not accept a patch providing migration support, or as
  an intermediate step before submitting such a patch to the other
  module.

  In cases where modules supported by migrate_extras end up implementing
  the support themselves, you could at least temporarily end up with
  redundant implementations. The extra implementation may be disabled at
  admin/content/migrate/configure.

Anyway, if you then look at:
http://drupalcode.org/project/migrate_extras.git/blob/9843c3b2c003e8bd19bb370e6eb6b2264f13eca1:/migrate_extras.migrate.inc

They declare their migrate API integration thus:

/*
 * Implementation of hook_migrate_api().
 */
function migrate_extras_migrate_api() {
  $api = array(
    'api' => 2,
    'destination handlers' => array(
      'MigratePathautoHandler',
      'MigrateExtrasNodeFlagHandler',
      'MigrateExtrasUserFlagHandler',
    ),
    'field handlers' => array(
      'MigrateAddressFieldHandler',
      'MigrateCckPhoneHandler',
      'MigrateGeoFieldHandler',
      'MigrateIntervalFieldHandler',
      'MigrateNameHandler',
      'MigrateMediaFieldHandler',
    )
  );
  return $api;
}

You probably want to list your FieldHanlder in a similar fashion (but with your class name). You probably also want to add it to the files[] array of your module so it is autoloaded and Migrate sees it.

Your new FieldHanlder should be listed at admin/content/migrate/configure

... if you read the blog post provided, it explains this oddity of FieldHandlers ...


Facebook style url fetching Does anybody have an idea, how to do a facebook url or link fetcher just link the one on facebook.

I have tried and have got a script but how to convert that into a drupal module for it to work.

Let me try to be more clear.

If you type a link on facebook it will go and get the image, meta description and other info from that link.

This is what i want to achieve.

If a user enters a link, what or how can i pull the data like image, meta description, etc etc from the link provided by the user.

Facebook-style link module is the perfect example of what i need but it is only for drupal 6 and i need it for drupal 7.

You can do this by using any of these below modules :

Facebook Connect
Simple FB Connect
Drupal For Facebook


Views PDF Change Table Layout Setting I am using Views PDF Module in my project.

This module provide only limited settings for table layout i want to generate pdf according to custom design as given below:

The pdf file generated through views PDf module currently as below:

so, please tell me how to design my pdf table in Views PDF Module.

I done this before using global text field and html. Add all needed fields into view and exclude them from display. Then create an html layout using field replacement patterns according to your requirement using a Global:Text field. Then generate PDF.

Hope this helps you.


How to insert ® value in database I am inserting users from drupal6 to drupal7 using a custom script. I am using db_insert function.
In one of the D6 entry I am getting ® mark in a field and because  of this that particular value become blank in D7 database.
D6:  imatter®    ->   D7:

Anyone has any idea about how to insert this value in database?

Collation is same in both database: utf8_general_ci
And in phpmyadmin its look like same as above, means no html code for ®

In the case that your insertion script is not capable of handling UTF-8 encoding (it sounds like this is the case), you can get around this by inserting this character as 7-bit HTML entities (i.e. &#174; or &reg;) provided the field where it appears is going to be rendered as HTML (and not as plain text).  Just do a search and replace and replace all occurences of ® with &#174; in the source text file.

If this workaround doesn't work (because the field is supposed to be plain text, or for some other reason), you must do two things:

Make sure your file containing these characters is UTF-8 (not ISO-8859-1 or some other encoding incompatible with UTF-8).
Make sure your insertion script is capable of handling UTF-8 (db_insert is, but I don't know what other components you use).


Alter user's entity label method By default the label() method of the user entity returns the username. So everywhere on the website where user references are used, the username is displayed.

I need to alter this method so everywhere the user name is displayed it will use my custom function. So instead of "custom_user_name" will display "Firstname Lastname" for example.

Any idea on how to achieve this? Thanks.

I'm not sure if there's a shortcut for that, but if not the steps are still quite minimal:

Sub-class the \Drupal\user\Entity\User class in a custom module, and override its label() method:

mymodule/src/Entity/User.php

namespace Drupal\mymodule\Entity;

use Drupal\user\Entity\User as CoreUser;

class User extends CoreUser {

  public function label() {
    return 'something new';
  }

}

Implement hook_entity_type_alter() to set the class for the User entity type:

function MYMODULE_entity_type_alter(&$entity_types) {
  $entity_types['user']->setClass(\Drupal\mymodule\Entity\User::class);
}

Rebuild the cache


How to patch core via drush-make when using a stub make file? When using a stub make file based profile workflow as suggested in Drush Make theory for happy profile development I notice that patches to core are no longer applied.

I've tested this by reverting to a single make file workflow - core patches get applied just fine that way.

Has anyone else found a fix/workaround for this?

UPDATE with details...

Here's what my stub make file looks like:

api = 2
core = 7.x

projects[] = drupal

projects[example_profile][download][type] = "git"
projects[example_profile][download][url] = "git@github.com:danohea/example-profile.git"
projects[example_profile][type] = "profile"

Which as you can see is designed to go grab a custom profile. I should mention that that is not the real path to the profile (which is a private repo anyway).

The profile contains a further make file that looks a bit like this (shortened for convenience):

api = 2
core = 7.x

; Contrib modules (not in dev)

; Specify common subdir of "contrib"
defaults[projects][subdir] = "contrib"

projects[admin_menu][version] = 3
projects[ctools][version] = 1
projects[diff][version] = 3
projects[eck][version] = 2
projects[entity][version] = 1
projects[jquery_update][version] = 3
projects[libraries][version] = 2
projects[link][version] = 1
projects[module_filter][version] = 2
projects[pathauto][version] = 1
projects[token][version] = 1
projects[transliteration][version] = 3
projects[views][version] = 3

; Contrib modules (in dev)

projects[wysiwyg][version] = 2.x-dev
; Keep in dev until this issue makes it to stable:
; https://drupal.org/node/1956778

; Themes

projects[omega][version] = 4
projects[omega][subdir] = "contrib"

; Libraries

; ckeditor
libraries[ckeditor][download][type] = file
libraries[ckeditor][download][url] = http://ckeditor.com/builder/download/a63002d0b001ab7841c8e29bb8081e57

; Patches

; drupal
; Ignore front end vendor folders to improve directory search performance
projects[drupal][patch][2329453] = https://www.drupal.org/files/issues/optimize_scan-2329453-84-do-not-test.patch

; pathauto
; Merge in pathauto_persist module functionality to prevent losing manual aliases with node_save() calls
projects[pathauto][patch][936222] = https://www.drupal.org/files/issues/merge_in-936222-299.patch

The stub make file is run with a command that looks a bit like this:

drush make --prepare-install path/to/stub.make -y

I'm running Drush version 7.0.0.

Note that there are 2 patches, one for drupal core and one for pathauto. The pathauto one is applied as expected, the drupal one doesn't seem to even run.

If I download & run the profile's make file directly (i.e. not via the stub) then the core patch is applied as expected.

If I move the drupal core patch to the stub make file, it still doesn't run.

Include the core patch in the core stub makefile. Here is mine straight out of buildkit.

api = 2
core = 7.x

projects[drupal][type] = core
projects[drupal][version] = "7.39"

; Use vocabulary machine name for permissions
; http://drupal.org/node/995156
projects[drupal][patch][995156] = http://drupal.org/files/issues/995156-5_portable_taxonomy_permissions.patch

projects[example][type] = profile
projects[example][download][type] = git
projects[example][download][url] = git@github.com:Laudanum/example.git


Limit amount of adding a certain Paragraph per Content type I use Drupal 8 Paragraphs module.

I created a Content type Landingpage.

I create some Paragraph types like Hero Image, Intro text etc.

In the Content type Landingpage I created a Paragraph Entity reference revisions field. In the REFERENCE TYPE, the Paragraph types Hero Image, Intro text are selected.

How do I manage the site editor is able to only insert one time (one value), the Hero Image Paragraph type? Because it doesn't make sense to have more then one Hero image section on the website...

Things which only should be unique to a node, should better be attached directly to that node.

There's already a feature request on DO. But I'd recommend you to solve this by attaching these things directly to the node, with standard image or text fields.

-- node type
  |__ hero image field
  |__ intro text field
  |__ paragraphs field

The only other alternative I see is to add multiple Paragraphs fields to your content type and then limit them to only one type and one item.


Any risks associated with habitually updating/reverting ALL features in drush? I want to start using drush commands to simply update all or revert all features (depending on which environment I'm in) instead of doing them one by one. What are the risks involved or questions I should ask myself before habitually just updating all or reverting all features?

drush fra (to revert all on production and test servers)

drush fua (to update all on dev environment)

Thanks!

In my opinion, first and foremost thing which should be taken into consideration is that your feature should not have any changes different from your development environment.

secondly, make sure that all of the fields of a content type have same type and widget as that are in your production environment.

You can also take backup of the db before reverting the features in case you are making any major changes.


CDN Module and Image Styles Yesterday I installed the CDN Module using Amazon Cloudfront and magically everything worked as expected. I was quite happy.

This morning I was showing off my new improved CDN enabled website to a colleague and most (not all) of the image style generated images were broken! And to confuse things even further, when I opened a broken image in a browser window the file was actually Drupal's Access Denied Page.

Digging into this further, I found that the /sites/default/files/styles/STYLE folder was empty. This seems strange to me since it was not empty yesterday when all of these files were uploaded to Amazon. What could be deleting the styles/STYLE folder?

So, I installed the Image Style Flush Module and flushed the style in question. Still nothing, but it makes sense since the CDN module is re-writting all of the links to static content and Drupal doesn't actually get hit to re-create the missing image. How the Access Denied page was uploaded is a mystery as well.

Next, I disabled the CDN module and cleared the cache. Reloading the page recreated all of the images and everything works as expected. But, I need to use the CDN as it's a requirement of the project.

Drupal 7.27, CDN module latest version.

I could blacklist the /sites/default/files/styles/STYLE folder, but that represents almost 30 images that are loaded on every page.

Any advice would be greatly appreciated.

AD MPD noted in the comments, the issue is how Amazon Cloudfront handles the image style URL, specifically the ?itok query string.

So, when creating your distribution in Cloudfront, make sure you set "Forward Query Strings" to "Yes". See screenshot:


updating webform submission display by using form So, this is what I'm trying to do.
I've got a webform submission filled in and saved to the database. When viewing the submission (node/nid/submission/sid). I want to show a form, which ask the user for a key. When the key is filled in I want to change the display of the submission (not the data in the database) using the webform_submission_load() hook. This is the code right now:

// webform hook
function mymodule_webform_submission_load($submissions) {
   $key_status = mymodule_get_key_status();
   if($key_status) {
      //change the submission display values
   }
}

// return TRUE or FALSE, depending on form submit
function mymodule_get_key_status($setkey = FALSE) {
   $status = &drupal_static(__FUNCTION__);
   if(!isset($status)) {
      $status = $setkey;
      // display form when key is not provided
      if(!$status) {
         $getform = drupal_get_form('mymodule_form');
         $output = drupal_render($getform);
         drupal_set_message($output, 'form', FALSE);
      }
      // key provided in form, so don't display the form
      else {
         $errors = drupal_get_messages('form');
      }
   }
   return $status;
}

// form submit callback
   function mymodule_form_custom_submit($form, &$form_state) {
       if (isset($form_state['values']['form_value'])) {
          $key = $form_state['values']['form_value']);
          drupal_static_reset('mymodule_get_key_status');
          mymodule_get_key_status(TRUE);
       }
    }

When viewing a submission I see the submission and the form. When I submit the form nothing changes and the form is displayed again. When I debug the return value of the mymodule_get_key_status function the following happens. First the function return FALSE, then the form calls the function and the function returns true. After that the function is called again by the webform hook. The function returns false again... Not what I expected. When I call mymodule_get_key_status(); in the form submit callback it returns true. So the drupal_static is set properly.

Why isn't the code working as I expected?

Well, i figured it out myself. After the form submit callback drupal fires a redirect to the same page. So the values set in mymodule_get_key_status are flushed after the redirect.
I add $form_state['redirect'] = false; to my submit callback and now everything works as expected.


Custom Drupal view filter I need to add a custom filter to the drupal views.i created the view to list some user fields. Drupal view path is like this /user/1/cj. Then i want the details of user with id=1.
How can i give the filter like this

It depends what kind of content the view is displaying, but in general

Set the view path to be user/%/cj
Add a new argument (or contextual filter D7) > User Uid
This will work for any user id you insert, eg user/1/cj, user/20/cj, etc...

You can also set the filter to filter on user > Current user, but that would make the path user/1/cj ambigious.


Content Type Display different per theme I'm using ThemeKey to switch my theme for mobile users. The problem i'm having is that i'm using image zoom for my products and on iphones it blocks the dropdown due to a hidden element. My question is, is it possible to change the way a content type is displayed per theme without disturbing the regular 'desktop' version of the site?

Clarification: What I'm referring to is when you go to Manage Display, how can you reposition content entities differently per theme.

Those settings are one per content type and will be applied for all themes you enabled.

I suggest to do that within the themes themselves - start by adding the node--[content type machine name].tpl.php and then exclude/move around the fields you need.

Example for hiding a specific field:

hide($content['field_name_goes_here']);

Other useful things:

hide($content['links']);
hide($content['comments']);

To see a full list of fields and exact names, install devel and do a dpm($content); in tpl file.

Also check the template_preprocess_node() function for more and better control of the fields values.


Getting error while joining two tables Here is query which is, I am using

$query = db_select('users','u');
$query->join('users_roles', 'u.uid = users_roles.uid'); // JOIN users_roles with users
$query->fields('users', array('name','uid')) // SELECT the field name from users
    ->condition('users_roles.rid', 5);

  $results = $query->execute();

Actually i want the user name and id for that those user who are under role id = 5

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1066
  Not unique table/alias: 'u': SELECT users.name AS name, users.uid AS
  uid FROM {users} u INNER JOIN {users_roles} u.uidusers_roles.uid WHERE
  (users_roles.rid = :db_condition_placeholder_0) ; Array (
  [:db_condition_placeholder_0] => 5 ) in user_assign_list() (line 80 of
  C:\xampp\htdocs\nic\sites\all\modules\user_assign\user_assign.module).

This error shown on the browser. Actually i am creating the custom module file for this requirement. Is there any need to include sql connection for those custom module?
here is .module file

<?php
function user_assign_permission() {
  return array(
    'submit user_assign' => array(
      'title' => t('Submit user_assign'),
      'description' => t('Submit the user_assign form'),
    ),
    'access user_assign list' => array(
      'title' => t('Access user_assign list'),
      'description' => t('Access the user_assign submissions'),
    ),

  );
}
function user_assign_menu() {
  $items = array();

   $items['users-list'] = array(
    'title' => t('User Assign'),
    'page callback' => 'user_assign_list',
    'access callback' => TRUE,
    'access arguments' => array('access user_assign list'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function user_assign_theme($existing, $type, $theme, $path) {
  return array(
    'user_assign_function' => array(
      'variables' => array('rows' => NULL),
    ),
    'user_assign_template' => array(
      'variables' => array('rows' => NULL),
      'template' => 'user_assign_template',
    ),

  );
}

function theme_user_assign_function($variables)
{
    $output = '';

//   print_r($variables);
    foreach($variables['items'] as $row) {

     $output .= '

'.$row[1].'&nbsp'.$row[2].'

';

    }

    return $output;
}

function user_assign_list() {
 // $query = db_select('users', 'n');

//  $query->condition('n.empname', '%' . db_like($_GET['empname']). '%','LIKE');

 // $query->fields('n', array('fe_id', 'empcode','empname','empphoto','empemail','empdesignation'))
  //    ->limit(4)
  //    ->addTag('node_access')
  //    ->groupBy('n.fe_id');
$query = db_select('users','u');
$query->join('users_roles', 'u.uid = users_roles.uid'); // JOIN users_roles with users
$query->fields('users', array('name','uid')) // SELLECT the field name from users
    ->condition('users_roles.rid', 5);

  $results = $query->execute();
     $rows = array();
  foreach($results as $result)
  {
    $rows[] = array(
        $result->uid,
        $result->name,
        );

  }
  $output = theme('user_assign_function', array('items' => $rows));
  return $output;
}

?>

Hi Sumit check the below query and it not showing any error.

Use Query coder module to create any query in drupal format

Query coder Convert SQL query to Drupal Database abstraction layer code.

$query = db_select('users','u');

$query->join('users_roles', 'r', 'u.uid = r.uid'); // JOIN users_roles with users

$query->fields('u', array('name','uid')) // SELECT the field name from users
    ->condition('r.rid', 5);

$results = $query->execute();
     $rows = array();

foreach($results as $result)
  {

$rows[] = array(
    $result->uid,
    $result->name,
    );

}


Adapting a superfish menu to what I want I am getting acquainted with Drupal 7 right now. One of the things that I have consumed a lot of time doing is understanding theming and getting the kind of Menu I want for my website.

I am using a subtheme of Bartik and have a Superfish menu (parent menu : main menu) rendering itself in the Highlighted region.

My grouch is that the menu does not render itself for the full width of the screen. The next is, I need to trigger some design changes to my menu itself which I am not sure how to.

Any leads people?

If you need the menu to render to the full width of the screen make sure the containers the menu is in doesn't have any set widths, and then set the main ul to a 100% width. Superfish comes with a lot of default styles that can be hard to override. If you use the Drupal Superfish module, configure your Superfish block and set the 'Style' to none, and make sure drop-shadow is ticked off. If you don't use the module you can do this when you call Superfish with drupal_add_js (or in your init.js).


How to find the path of the feed for content type in drupal 7? I wanted to add the path to the feed view display, but I'm not able to know what the path is?

You can use the Views module to create feeds. Simply add a new display of type "Feed" and customize the view to contain only the content you want. You have to set the path in Feed Settings(enter your own path for example: type feed or any path you want).

To add a "Feed" display:

Go to your views administration and select the view you want to edit. Towards the top of the page you will see the "Displays" heading with an "+ Add" button. Click that and select "Feed" . You will then have a Feed display that is using the Default Display's settings.


How do I reference another field properly? In Drupal 7, how can I properly reference another field with the Computed field module?

It's best to turn on the devel module and do a dsm() on the $entity object to see what fields are available to you. Even if you think field_name would work, there are other arrays inside that field variable.

In the case below i am parsing a URL link from another field and exploding it via the dashes. Since my field_sell_link is a "link field" i had to add the ['url'] at the end of the field reference instead of the usual ['value']. I didn't find this out until I did a dsm on $entity. You can also do a set_message(print_r($entity)); too.

let me know if this helped anyone.

Example code for the PHP code section:

$ebay_url = isset($entity->field_sell_link['und'][0]['url']) ?
  $entity->field_sell_link['und'][0]['url'] :
  'zero/one/two/three/nothing-here-asdf/last';

if (isset($ebay_url)) {
  $url = explode('/', $ebay_url);
  $pattern = '/-/';
  $replace = ' ';
  $entity_field[0]['value'] = 'testxxx' . $url[3];
}
else {
  $entity_field[0]['value'] = "";
}


How to assign uid in "users" table with imported users? I am using Drupal 7.

I am using the Migrate module to migrate a list of users from an external user database table into the Drupal "users" table. The problem is that the Drupal "users" table has a numerical "uid" field, which does not exist in my external database users table.

Could someone please tell me of a way to assign a unique uid to the users table everytime I map a row using Migrate?

For example, right now I have, in the "users" database:

0
1 root ...
//external users start here
2 user1 ...
3 user2 ...
4 user3 ...

Essentially I have would like to start at 2 and continue for each user I migrate over to the "users" table.

More specifically, how I would modify/add a line to the following so that the code can auto generate unique ID's starting from 2? Would the following code be a viable option? If so, where would be the appropriate place to update $counter?

$counter = 2;
$this->addFieldMapping('uid', '$counter');

Thanks.

EDIT:

If I were to use the following SQL statement to do the user migration, would it be a good idea? If it is also a viable option, how might be able to create unique "uid" for insertion into the "users" table?

INSERT INTO users (uid, name, mail,pass,...) SELECT uid, oldusername, email, md5(clear_password),... FROM old_users_table;

Thanks.

Inserting data directly into Drupal tables is generally a bad idea (until you are familiar enough with the database schema to know what you're doing). For programmatically inserting users there are functions like user_save() and drupal_form_submit() that you can use.

As for generating the unique uid: if you can't just provide incremental values in the data insertion loop then you might be able to use the following code instead (copied from user_save() function):

$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());

I'm not familiar with the Migrate module so I don't have more specific advice to offer currently, but the above info and links should be helpful.


What are costs/benefits of integrating Phing, Jenkins together with Drupal? I would like to improve my testing environment automation in order to reduce effort needed for quality assurance tasks.

I heard about Phing and Jenkins and read overview information but still I am not convinced it is worth investing the set up effort currently.

Can you explain the costs and benefits of installing Phing, Jenkins based continous integration environment while I am using Drupal, Drush, Git, Simpletest and bash scripts already in dev, staging, production set up ?

Ok, as for being a fan myself of continuous integration, I can assure you virtualisation is very handy to control the testing environment. I have built myself a CI setup, forking off from a wonderful package called quickstart. This package depends on Virtual-Box or other VM software, it is basically a Ubuntu made for Drupal with a pre-set up lamp architecture, pre-configured debugging and editors, profilers, etc.

I have installed Jenkins and phing  on top of quickstart, and can assure you it is quite low cost($0), quite low hassle. Any one can co-opt in with me on most any project quite easily, the whole dev environnement is reproduced and it comes with quite a few tools by default, and quite a few I have myself upgraded.

Now, the way we use jenkins is most certainly not pure CI, it just run the tests when we commit, then we shut down the thing and forget about it.  It could be used for notifications and documentation generation, and on some projects I do generate some code metrics but the main thing I also cared about in my setup was testing. One clear advantage when using a vm software for testing  is it can easily be reproduced used  to run the tests elsewhere or even on different systems and configurations, you always have control over the environnement (memory, processor usage, peripheral ressources, etc..)

In most projects I contributed on, testing is done before staging I guess this may be different depending on the project managers.

PS: Another thing to consider, in a true testing environnment you would tend to try and reproduce your server setup and load as much as possible. Our projects are hosted on Cent-OS and obviously we don`t quite follow up to the rules on this aspect either, quickastart is Ubuntu based. So far have not had any problems,  and  as a bonus has many other features pre-configured for rapid Drupal application prototyping and developpment.

Happy CI'ing!


How to create a Notification system in D7? I am new to Drupal and was wondering if there is a module that can serve as a Notification system for logged-in users on my site?

Since my nodes consist mainly of images generated by users, I would like for logged in users to be able to see how many members liked their images, made a comment, followed them, etc.

P.S. I read almost all similar posts here and none of them provided any clear explanation. Pointing to active sites that already use "these module(s)" would be of great help.

Thanks in advance,
Milos

In the Drupal community, "notifications" are usually referring to email notifications sent to users.

Messages sent to users to indicate "likes", etc. are usually called "messages". So you should probably search for "messages" and "messaging" (instead of "notifications") to locate stuff about this type of user interaction.

One of the most popular Drupal modules for messages is HeartBeat:

  Heartbeat displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.

However, the maintainer of Heatbeat has recently announced:

  This project will be deprecated. The future would be in the module Message. It's much smaller and it cannot be compared to heartbeat when it comes to features. However the possibilities as API would be the same.

At the time of writing, Message is an API that you can use to build the required flagging and messaging by combining it with other modules in the message stack. As for social messaging functions, you need to  add those. The Heartbeat API already has all the necessary functionality built-in.  Today, it will take much less effort to get something working with Heartbeat than with Message, but maybe Message is still a better option than putting efforts into working with a module about to be depreciated,


Using AJAX in Drupal 7 to change a form action I would like to update the Drupal save_edit module to add an auto-save feature. This would look similar to the Stack Exchange auto-save (draft saved). So far I've gotten the save portion working (saving the new node) but when I save again, it creates another node (this is not a surprise since I've not told it to do anything else).

I'm looking for how to tell the form that the node has already been saved and what the node id is.

I think I need to update the form action to point to /node/$nid/edit this way when the user clicks on the normal submit button, the node will be published (if set to).

Obviously I'm not wanting to refresh the page after these saves, that would be too easy ;-)

For more examples, here is the link to Lullabot's jQuery and JavaScript in Drupal video tutorial source files. I would pay attention to the Drupal 7 quickview.module example.

Here they use a page callback that passes either 'nojs' or 'ajax' as the second argument. The Drupal ajax framework will change the links on the page from 'node/[id]/nojs' to 'node/[id]/ajax' if the client has ajax enabled. The page callback function tests for the presence of ajax. If not, it will use drupal_goto() to gracefully degrade and reload the page. Or, if the ajax framework changed the link to ajax it will construct the HTML can send it back to the page with json headers and all using the new command() to manipulate markup, javascript Drupal setting, or CSS on the page.

I image with a tweaking this same technique can be used for Form API.


Drupal add class to body if page is unpublished I would like to be able to add an unpublished class to the body tag of a node (for both its main view and edit view) if the node has been unpublished.

How can I do this?

Steps I have taken:

1) Node Object
The node object contains if a node has been published or unpublished (with $node -> Status), but I am not sure how to test this for each node and then add it to the body class.

This question is similar, but the provided answer doesn't work.

2) Drupal 6
This page explains how to do it for Drupal 6, but the code doesn't work for Drupal 7.

in your theme's template.php:

function mytemplate_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && isset($node->nid)) {
    if ($node->status) {
      $vars['classes_array'][] = 'published';
    } else {
      $vars['classes_array'][] = 'unpublished';
    }
  }
}


Drush command to run cron won't work in Crontab I am attempting to run two Drush commands from my crontab:

# m h  dom mon dow   command
*/2 * * * * drush -r /path -l https://www.domain.com/ cron
*/2 * * * * drush -r /path -l https://www.domain.com/ -u civicron civicrm-api job.execute

Both of these commands work when I run them manually on the server, however they do not appear to work through crontab, even though the log shows them running:

Apr 17 20:16:01 ip-000000000000 CRON[3736]: (ubuntu) CMD (drush -r /path -l https://www.domain.com/ -u civicron civicrm-api job.execute)
Apr 17 20:16:01 ip-000000000000 CRON[3737]: (ubuntu) CMD (drush -r /path -l https://www.domain.com/ cron)

Any suggestion as I cannot see why these would not be running?

I ran into a similar issue multiple times. I think in all cases cron was running a different version of php.  To fix I ended up having to define my php path in my drush call:

*/5 * * * * /usr/local/bin/php /home/myuser/bin/drush elysia-cron run --root=/home/mysite/public_html --uri=www.mysite.com

Also, another thing that helped me debug the issue is by adding a log path > path/to/file.log like this and then looking at the exact error:

*/5 * * * * /usr/local/bin/php /home/myuser/bin/drush elysia-cron run --root=/home/mysite/public_html --uri=www.mysite.com > /home/mysite/cron.log 2>&1


How to retrieve data from custom table in database? I created a custom table in my modules .install file and I am asking for some form input in a custom made configuration file. I am unable to retrieve that data and print it out in a custom callback page that i created for testing. I'm not quite sure what i am doing wrong.

<?php
/* mymodule.install */
function mymodule_schema(){
  $schema['mymodule'] = array(
    'description' => 'Table for testing',
    'fields' => array(
      'pmid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'field_one' => array(
        'description' => 'Field 1',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => ''
      ),
      'primary key' => array('pmid'),
      'unique keys' => array(
        'pmid' => array('pmid'),
      ),
     ),
   );

/* mymodule.module */
function mymodule_form_submit($form, &$form_state){
  db_insert('mymodule')
  ->fields(array(
    'field_one' => $form_state['values']['field_one'],
    'pmid' => 1,
  ))->execute();
}

function mymodule_print_table(){
$result = db_select('mymodule', 'mm')
       ->fields('field_one')
       ->execute()
       ->fetchAll();
var_dump($result);
}

This prints an empty array for me.

EDIT:

I incorrectly assumed form_submit was a hook and didn't add it to my form.

function mymodule_form($form, &$form_state){
$form['field_one'] = array(
    '#type' => 'textfield',
    '#title' => t('Field One'),
    '#default_value' => '',
    '#description' => t('Field One Test'),
    '#required' => true,
  );
//This was missing
$form['#submit'][] = 'mymodule_form_submit';

return system_settings_form($form);
}

The fields method takes a table name/alias as its first arg, and an array of field names as its second:

$result = db_select('mymodule', 'mm')
   ->fields('mm', ['field_one'])
   ->execute()
   ->fetchAll();


Custom blocks created as a plugin in a module not showing for Block::load() I have a couple of blocks that have been created using the ... extends BlockBase syntax in my module. They work perfectly fine, and I can add them on the blocks layout page, can add them into DS as a field, etc. They definitely exist fine.

However, when I try and render them using Block::load(), they won't show up, unlike other blocks that work fine.

For example, if I have the following docblock:

/**
 * Provides a 'Cute Cats' Block.
 *
 * @Block(
 *   id = "cute_cats",
 *   admin_label = @Translation("Cute cats yo"),
 * )
 */
 class CuteCats extends BlockBase { ... }

... and then try and call it like this:

$block = \Drupal\block\Entity\Block::load('cute_cats');
return render(\Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block));

Any idea why? Thanks in advance.

Block::load() loads a configured block, that means a block that is placed in the block layout. It does not load plugins.

The name of the configured block is displayed in the block layout as Machine name.

You can place the block in the Disabled section, if you only want to configure the block, but don't want to show the block in a region.


Why does Rules event 'After updating existing content' not result in 'Create a new comment'? I've used Create a new entity for the Rules event After updating existing content, but nothing happens.

Is it a bug?

Update:

Here is an export of my rule:

{ "rules_update_order" : {
    "LABEL" : "Update Order",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : "Something",
            "param_node" : [ "node" ],
            "param_author" : [ "node:author" ],
            "param_comment_body" : { "value" : { "value" : "Something", "format" : "filtered_html" } }
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      }
    ]
  }
}

It is a very simple rule. And I have a lot of rules which are easily fired apart from this one.

Some more Debugging information (contained in my Rules Logging):

0 ms Rule Update Order fires.
0.873 ms Evaluating the action entity_create.
33.717 ms Unable to create entity comment": Invalid data value given.
          Be sure it matches the required data type and format.
36.05 ms Unable to evaluate action entity_create.
36.099 ms Rule Update Order has fired.

Part 1: Understanding the problem

It takes a little time/effort to get used (and become experienced) in using the Rules module.

My experience is that it is rare to find a bug in the Rules module. Most of the cases where I experience something in Rules that deviates from what I expected, I can find out what "my" problem is by using debug-facilities available for the Rules module.

So within the Rules settings, experiment a bit with the debugging facilities that come with the Rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

For more suggestions about Rules debugging, refer to  "How can I display the value of a variable inside a condition?"

Part 2: Examples of creating comments after updating existing content

Sorry to say, but I disagree with this comment that was posted below this answer:

  It seems that it cannot work in this way and it is not possible to create a comment with this event.

Have a look at these answers, which are about questions that are variations of the question here:

How to create a Rule to create a new entity of type Comment and a body with tokens?
How to add a comment form in VBO to add the same comment to mutiple nodes?

Part 3: Experiment with other text formats

Even though your question doesn't provide any details about the text formats you are using, IMO it could well be that your actual issue is caused by the Text format that you're using for the comment body: your rule shows you're using filtered_html, but you should definitely give it a try to experiment with other text formats, such as plain_text.

PS: this answer is about D7 ...


Rewrite results (like trimming titles) won't work at all I created a view with articles. All I need is to trim titles.
The reason I cannot do this from content types (teaser view) is because the title field is a node module element. (It cannot be deleted, and is too late for that.)

There is an option in views output in the preview mode/contextual menus/rewrite results, but it seems it won't work.

None of the rewrite results options will work. It looks like a bug in the Views module.

Clear your Drupal cache by visiting /admin/config/development/performance or if you use the Drush module, simply run drush cc all

Also make sure you're editing and viewing the correct view.  If you're modify the master display but viewing an overwritten display, your master view settings will have no effect.


Alter add to cart message How to alter the message shown - "xyz" added to your cart, when we add an item to cart in Drupal 8 Commerce 2x.

I saw Drupal\commerce_cart\EventSubscriber where the function displayAddToCartMessage(CartEntityAddEvent $event) is written which is responsible for showing the message, is there any method to override it.

Install the Commerce Extended Quantity module and then implement a HOOK_xquantity_add_to_cart_qty_prices_msg_alter():
https://github.com/drugan/commerce_xquantity#an-item-added-to-your-cart-message-alter


Custom form from user registration form not showing new fields in D7 I am trying to build a new form from the user registration form and while the user reg parts are appearing the new fields are not. Any ideas? The code is below. I tried having the fields in the primary array level AND under the account parameter.

When the array prints out it shows the parameters are there. So I am having trouble figuring out why it is not working. I am used to doing this in Drupal 6. But in Drupal 7 it is not cooperating.

function custom_reg_company_registration() {
  return drupal_get_form('custom_reg_company_form');
}

function custom_reg_company_form($form, &$form_state) {
  $form = user_register_form($form, $form_state);

  $form['company_name'] = array(
    '#type' => 'textfield',
    '#title' => 'Company Name',
    '#maxlength' => 60,
    '#description' => 'The name of your company.',
    '#required' => 1,
    '#attributes' => array(
      'class' => array(0 => 'company_name'),
    ),
    '#default_value' => '',
    '#access' => 1,
    '#weight' => -10,
  );

  $form['primary_phone'] = array(
    '#type' => 'textfield',
    '#title' => 'Primary Phone',
    '#maxlength' => 30,
    '#description' => 'The primary phone number for your company.',
    '#required' => 1,
    '#attributes' => array(
      'class' => array(0 => 'primary_phone'),
    ),
    '#default_value' => '',
    '#access' => 1,
    '#weight' => -10,
  );

  $form['secondary_phone'] = array(
    '#type' => 'textfield',
    '#title' => 'Secondary Phone',
    '#maxlength' => 30,
    '#description' => 'The secondary phone number for your company.',
    '#required' => 0,
    '#attributes' => array(
      'class' => array(0 => 'secondary_phone'),
    ),
    '#default_value' => '',
    '#access' => 1,
    '#weight' => -10,
  );

  $form['company_type'] = array(
    '#type' => 'radios',
    '#title' => 'Company Type',
    '#maxlength' => 30,
    '#description' => 'The type of company you are setting up.',
    '#required' => 1,
    '#default_value' => 0,
    '#weight' => -10,
    '#options' => array(
      0 => 'Carrier',
      1 => 'Broker & FF',
      2 => 'Shipper',
    ),
  );

  $form['#action'] = url('register/company');

  echo "<pre>" . print_r($form, true) . "</pre>";

  return $form;
}

Is there a reason you need to use code? You could just add the fields to the user profile and check "required on registration" to make them show up during registration.