How to remove status messages from admin theme? I am working with Drupal 8. I have enabled "Seven" as admin theme. When I have added an image with high resolution I am getting 2 error messages at a time(screenshot). I want to hide "green" colored status message from this particular page. I have tried with hook_page_attachments(array &$attachments) in my custom module to include the css for admin theme.

But it is not working. How to solve this issue?

.

hook_page_attachments is not the correct hook. You want to implement hook_preprocess_HOOK, like the example below.

There are some caveats with this fix, especially if your site will be localized to other languages, see the comments within the code:

/**
 * Implements hook_preprocess_HOOK().
 * Implements hook_preprocess_status_messages().
 *
 * @param $variables
 */
function mymodule_preprocess_status_messages(&$variables) {
  if (isset($variables['message_list']['status'])) {
    $status_messages = $variables['message_list']['status'];
    $dummy_message_parameter_1 = '_parameter_1_';
    $dummy_message_parameters =       [
      '%dimensions' => $dummy_message_parameter_1,
      '%new_width' => 0,
      '%new_height' => 0,
    ];
    // The message could change eventually, but it is unlikely.
    // This logic *could brake* in a some language translations, if the %dimensions string is not the first parameter.
    $file_resize_message = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.', $dummy_message_parameters);
    // $file_resize_message_start is the part of the message that won't vary.
    $file_resize_message_start =strtok((string)$file_resize_message, $dummy_message_parameter_1); ;
    foreach ($status_messages as $delta => $message) {
      if (strpos((string)$message, $file_resize_message_start) !== FALSE) {
        // The next commented line still leaves a green area
        // unset($variables['message_list']['status'][$delta]);
        // Removing all messages, the side effect is that you could be
        // missing on some relevant messages
        unset($variables['message_list']['status']);
      }
    }
  }
}

The message is set in the function file_validate_image_resolution at core/modules/file/file.module:447 (as of version 8.6.0-dev)

There is a good explanation about the hook implementation at Stack Overflow


How can you identify all nodes that use a certain paragraph type or template? In Drupal 7, given a custom paragraph bundle and an associated template file, is there a way to list all the nodes using that bundle? Or, if it's any easier, a way to do the same for a specific module instead of a paragraph type?

A Drupal core module update (https://www.drupal.org/project/link/issues/3095484) broke a bunch of our links across our site, and while a workaround is available, I wanted to test it against all the existing nodes first.

As @runwithscissors stated in the comments, you can use views to to this.

I’m not super experienced with views in Drupal 7, but It should be as easy as:

Create a view that lists the nodes .
Add a relationship to the referenced paragraphs.
Add a filter on the paragraphs bundle.

That should be all. Once you have added the relationship, the bundle field will be made available as a filter.

I hope this is as easy in Drupal 7 as it is in Drupal 8.

You can read more about views here.


Create send user private message link in a node template content type How do you print the private message link in a node template please?

This what I've tried

hide($content['field_privatemsg']);

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

Many thanks for your help

Assuming you want to create a link to the author, you should be able to create a simple link in the template
 - Field that links to a path/url defined with Tokens, is it possible?

It would follow something like: http://www.example.com/messages/new/[node:author]

You can see a list of tokens here: https://drupal.org/node/390482#token-node


how to do mapping user to user in drupal I created 4 user in my site.

1)contributor1
2)contributor2
3)validator1
4)validator2

Contributor can able to create a node  and validator can able to review the node

I am using workbench module for content moderation.

My question is?

When contributor1 create a node, then he send the node to validator1 for review
and  contributor2 create a node , then he send the node to validator2 for review

So please let me know, how can I do the user wise mapping

contributor1 create node1 through content type 1  , then only node1 access only validator1 user and he can publish the content   same as
contributor2 create node2 through content type 2 , then only node2 access only validator2 user and he can publish the content..

you have any idea please let me know

So you have 4 user roles and 2 different content types. The first 2 user roles work with content type 1 and the other 2 user roles with content type 2.

I believe you'll find the answer to your question on this page as it explains:

How to configure Workbench Moderation states
How to configure and check Workbench Moderation transitions for each role

So you can set additional States according to your needs but the three default States of "Draft", "Needs Review" & "Published" seem to do the job for your case. You can also set what transitions between which states should generally be available and then configure the transition permissions for every role according to your needs.

Applying those guidelines, a Contributor1 user would create a node of content type 1 (in "Draft" state), given that they have the proper content creation permission. After that, Contributor1 would not be able to do the transition to other states for that content type. On the other hand, Validator1 should be given permissions to do the transition from "Needs Review" to "Published" for content type 1.


I can't to expose the option sort Post Date in a view in Drupal 7 I have created a view type content, with the follow features:

Format

Format: Unformatted list | Settings

Show: Content | Teaser

Fields

The selected style or row format does not utilize fields.

Filter criteria

Content: Type (= article)

Content: Published (Yes)

Sort criteria

Content: Post date (desc)

When I checked the option "Expose this sort to visitors, to allow them to change it " in Sort Criteria>Post Date and press Apply, the sort Expose doesn't show and when I am going again to Post Date I can see that the change was not stored, the "Expose this sort to visitors, to allow them to change it" appears unabled.

What's my error?

Thanks for your help.

It seems to be an issue with having the devel module enabled.  If you are using it try disabling it and it should work.


How do I set, and return, a value in Views PHP? I'm not going to use the real scenario here, just a very simple one that I think should be working.

I have a View.  This view does access some Solr stuff.

I've added a new field to the view.  It's a Global PHP field.  My end goal of this is that I'd like to make this field sortable when you click the table heading.

In the "Value code":

return "asdfasdf";

In the "Output code"

<?php
  print $value;
?>

This returns... nothing. No errors, no output. This is the simplest example I could think of. Am I missing something here?

"Output code" does display other things, even complex things if I ask it to.  It just seems like "Value code" is being completely ignored.

It works for me. I put the information you said in a PHP field and it printed out as expected. I imagine it's a caching issue or something else about your site that is causing the issue.


How to Migrate files having path in it? I have a custom table in drupal 6 in which file path is stored in the field like sites/default/files/file_name.jpg. I dont have fid for this field.

How can I map this with my image field?

I saved the file in prepareRow() and map the fid with my field.

$this->addFieldMapping('field_image', 'fid');
$this->addFieldMapping('field_image:file_class')
  ->defaultValue('MigrateFileFid');

In my prepareRow method :

  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    $files_dir = '/mnt/files';
    $file_name = str_replace('sites/default/files/', '', $row->image);
    $file_path = $files_dir . $file_name;
    $row->fid = _my_migration_upload_file($file_path);
    return TRUE;
  }


Can't update via composer because of lock file I am trying to install Lightning 8.1.0. I am currently at 8.1.00-rc5. When I run composer require drupal/lightning:8.1.0 I get the following response:

± |master ✓| → composer require drupal/lightning:8.1.0
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
    1/1:  http://packagist.org/p/provider-latest$aa4f1da6acef0b15640bc1cace21327f5342dbb88c61b4605f0b1b0ff21d7399.json
    Finished: success: 1, skipped: 0, failure: 0, total: 1
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: drupal/entity_browser[8.1.x-dev, 8.1.0-alpha3].
    - Can only install one of: drupal/entity_browser[8.1.0-alpha3, 8.1.x-dev].
    - drupal/lightning 8.1.00 requires drupal/entity_browser 8.1.0-alpha3 -> satisfiable by drupal/entity_browser[8.1.0-alpha3].
    - Installation request for drupal/lightning 8.1.0 -> satisfiable by drupal/lightning[8.1.00].
    - Installation request for drupal/entity_browser (locked at 8.1.x-dev) -> satisfiable by drupal/entity_browser[8.1.x-dev].

Installation failed, reverting ./composer.json to its original content.

The only way I get around this is that I have to remove the composer.lock file before I run composer require drupal/lightning:8.1.0. Does this sound like the right way to do it?

composer.json: http://pasted.co/f2561b5d
composer.lock: http://pasted.co/573a945e

The way I updated is I manually updated composer and set Lightning to 8.1.0 and then ran composer update drupal/lightning.


Is there an efficient way to dermine whether a node can be viewed by all users? I am trying to use the Drupal node access API to determine whether a node is subject to an access restriction. That is: I want to make sure that the node can be viewed by any authenticated user (provided the authenticated user is granted the right to view published content).

The function node_access('view, $node, $account); returns TRUE if the user object $account can access $node, and FALSE otherwise, so I can get the correct result stored in $view_for_all with the following snippet of code:

$accounts = entity_load('user');
$view_for_all = TRUE;
foreach ($accounts as $account) {
  if (!node_access('view', $node, $account)) {
    $view_for_all = FALSE;
    break;
  }
}

However, looping through all accounts will be very slow if there are, say, 50000 users. I am looking for a more efficient way to do this.

If you are needing to check node_access records, then you may be able to examine them similarly to how devel_node_access does.  In the end, all nodes have grants added to the node_access table, so if there are grants that deny or restrictively add access, then you can probably see it there.

Another option would be to have a dummy account that is an authenticated user, and used as the test case.  This will fail, of course, if you need to detect grant rules that deny access to authenticated users who would otherwise be entitled.  It's a sticky situation.

The hardest part about this question is that it seems as though you are looking for a general solution to a specific problem, and I'm not quite sure that a general solution exists.


Drupal patch files - Why do Drupal patches have complicated file names? I know almost nothing on Drupal patches but it is important for me to ask this for others and myself: Why almost every Drupal patch I've seen in discussions in Drupal.org has a long complicated file name? For example, I've seen this one yesterday:

  [Add_rtl_support]-[2635832]-[1].patch

Why is the []-[]-[] structure, why 3 words in the first structure(?), what is the medium-number, and what is the 1 (first patch release from the same committer)?

Two more examples, which are different from the above and one from another:

  metatag_by_path_consequences_fix-2184979-12.patch
  metatag-n2564483-190.interdiff.txt

And there could be more I guess...

I would thank any experienced dev who could shed some light in this context...

And also a subtle question: If I download a file with a long name and than changed the name to something like "fix1.patch" just for navigation comfortability, Will it still work as normal as it should have been?

It just provide good information about the patch.

Here is the proper way to name a patch

[project_name]-[short-description]-[issue-number]-[comment-number].patch

Why? Here is a list of why these name are useful...

[project_name] - We use the project name to distinct the patch from other projects. Sometimes some project have multiples sub-modules and it just nice to have a name in front of the patch.
[short-description] - This is just a well practice from git, which is adding a small description about the patch.
[issue-number] - With unique issue number we can make sure what this patch is trying to solve because we can visit drupal.org/node/[issue-number] and see what is trying to solve.
[comment-number] Usually, there are multiple patch in the same issue queue and we need way to distinct different patch for this reason we add the comment-number so we do not get confuse when we are reviewing patches.

For more information about patches naming visit - Making a Drupal patch with Git

  And also a subtle question: If I download a file with a long name and
  than changed the name to something like "fix1.patch" just for
  navigation comfortability, Will it still work as normal as it should
  have been?

Patches names does not have any affect to the patch content. This been said, it will work, it just that developer was very lazy and did not want to name it the proper way (or he/she did not know how to in Drupal we name patches).


Cannot configure the site as SAML SP with simplesamlphp_auth I have a functioning SAML IdP, implemented with LemonLDAP::NG. I know it functions because it works with Nextcloud as an SP. I've also successfully configured a DokuWiki SP in the past.

The IdP, the Nextcloud SP and the Drupal 8 SP are all behind an Nginx reverse proxy. All of them are directly reachable from my IP, but I have restricted access from other IPs.

I have been trying on and off for a year to make SAML login work with Drupal 8, using simplesamlphp_auth, but without success. I have lost count of how many articles I have read on the net, which all suggest that configuring SAML is trivial. Sadly, not for me.

Currently, when I select the Drupal 8 SP under 'Test authentication sources' in the 'Authentication' tab, I get the following error:

  Too many redirects occurred trying to open “https://www.xxxx.tld/simplesaml/module.php/core/authenticate.php?as=wmh-www-sp&%5CSimpleSAML%5CAuth%5CState.exceptionId=_568428306a7ad7ad7bf8f8f47a94940de364239c67%3Ahttps%3A%2F%2Fwww.xxx.tld%2Fsimplesaml%2Fmodule.php%2Fcore%2Fas_login.php%3FAuthId%3Dwmh-www-sp%26ReturnTo%3Dhttps%253A%252F%252Fwww.xxx.tld%252Fsimplesaml%252Fmodule.php%252Fcore%252Fauthenticate.php%253Fas%253Dwmh-www-sp”. This might occur if you open a page that is redirected to open another page, which then is redirected to open the original page.

The log file contains repeated occurrences of the following error messages:

  2019/04/03 22:31:48 [error] 21251#21251: *982 FastCGI sent in stderr: "PHP message: simplesamlphp DEBUG [e54b9408f4] Session: 'wmh-www-sp' not valid because we are not authenticated.

  PHP message: simplesamlphp DEBUG [e54b9408f4] getIdpMetadata: METADATANOTFOUND('%' => '\'https://cloud.xxx.tld/saml/metadata\'')

  PHP message: simplesamlphp DEBUG [e54b9408f4] getIdpMetadata: METADATANOTFOUND('%' => '\'https://cloud.xxx.tld/saml/metadata\'')

  PHP message: simplesamlphp DEBUG [e54b9408f4] Saved state: '_f37c552249cf34b640de1dac7ad22b1481c763fc0f:https://www.xxx.tld/simplesaml/module.php/core/as_login.php?AuthId=wmh-www-sp&ReturnTo=https.xxx.tld.php.php-www-sp'

  PHP message: simplesamlphp DEBUG [e54b9408f4] saving key SimpleSAMLphp.session.161a8f86a89cf6e93f36117cc21a26af to memcache" while reading response header from upstream, client: NN.NNN.NNN.NNN, server: www.xxx.tld, request: "GET /simplesaml/module.php/core/authenticate.php?as=wmh-www-sp HTTP/2.0", upstream: "fastcgi://unix:/var/run/php-fpm-www.sock:", host: "www.xxx.tld", referrer: "https://www.xxx.tld/simplesaml/module.php/core/authenticate.php"

  2019/04/03 22:31:48 [error] 21251#21251: *982 FastCGI sent in stderr: "PHP message: simplesamlphp DEBUG [e54b9408f4] loading key SimpleSAMLphp.session.161a8f86a89cf6e93f36117cc21a26af from memcache" while reading upstream, client: NN.NNN.NNN.NNN, server: www.xxx.tld, request: "GET /simplesaml/module.php/core/authenticate.php?as=wmh-www-sp HTTP/2.0", upstream: "fastcgi://unix:/var/run/php-fpm-www.sock:", host: "www.xxx.tld", referrer: "https://www.xxx.tld/simplesaml/module.php/core/authenticate.php"

(www.xxx.tld is the SP, cloud.xxx.tldis the IdP, wmh-www-sp is the entityID of the SP.)

Specific things I do not understand:

we are not authenticated - I have logged into the simplesamlphp_auth interface
METADATANOTFOUND('%' => '\'https://cloud.xxx.tld/saml/metadata\'') - this is the address of the IdP's metadata and is correct as such

I created file metadata/saml20-idp-remote.php from the IdP's metadata URL, https://cloud.xxx.tld/saml/metadata using simplesamlphp_auth's metadata converter under the "Federation" tab.

Can anyone help me to make sense of all the above?

Steve

The problem was - as so often - between the keyboard and the chair. I had some subtle mistakes in a couple of file paths in config/config.php. Apparently simplesamlphp_auth doesn't do any validation of file names, so mistakes blow up without any apparent context at runtime.


Internal URL or menu callback to use node/entity content without html/page wrapping Does anyone know, if there is any work-around or regular setup for panels or custom code known, to be able to use a url/node/%id or node menu-callback to render node/entity content delivered without the rendered page wrapping (<html> <header>,etc)?

I am not asking for Panels_everywhere behavior nor for Drupal modules like Colorbox, Lightbox, and all the others, nor Colorbox_node popup and such. I only try to have the node/entity callback url at hand to render entity or node content without any page.tpl.php or html.tpl.php involved, to use it somewhere else like for bootstrap modal, node_panels rendered into modals, or for custom scenarios to get most flexibility.

I took a look into Ctools module suite's modal callback and Entity_popup but the lack of documentation (no offense) and the confusion in my mind lead me to here asking for some breadcrumbs and ideas.

Thanks for any help on this.

After some research I maybe found an answer by myself for this question, not sure yet. Maybe temporary or at first glance only.

While I embrace user5482's (Thanks for your fast reply!) approach using hook_menu() in a custom module, what I have considered already, I still have 2 worries. First: there is missing experience on my side and missing documentation on the functions side for its underrated delivery argument (take a look here). Second: Custom modules should only be considered for very rare individual situations, otherwise you fastly run into 10 custom modules on a project which need to be maintained on core updates. If the scenario what you are looking for is more common, the chance is 99%, that there is a module for that.

So, at first, I will try to achieve this with the JQuery_Ajax_Load module, which actually builds on the mentioned hook_menu() and I will report back when I have any news on this.


Autocalculated price field depending on language I need field for my own content type that will show price in currency depending on chosen language (from i18n module) calculated by currency exchange rate from currency module.

I've installed money field, but how to connect this to currency exchange?

I need some advice. I'm newbie.

Thanks for any hints, maybe I try to go wrong way?

Ok, I managed that with computed field. Money field was not needed.

In computed field I've posted code:

 $exchange_rate = CurrencyExchanger::load('PLN', 'EUR');
 $netto_price = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_name')));
 $entity_field[0]['value'] = bcmul($exchange_rate, $netto_price, 2);

It calculates currency in fly from currency module.


Anonymous user cache issue We're having a problem with caching that is affecting anonymous users.

We have a form in a block that when the user fills out the form, they are able to download a PDF. We hide the block on pages where we don't want this PDF download form to appear. Ideally the block is hidden, if no PDF is available for a particular page, but the block is being cached and displayed regardless the of the actual page. This only is a problem for anonymous users. Logged in users do not have the problem of the seemingly cached PDF download blocks appearing on the wrong pages.

For example after clearing the cache, somebody first visits page A with a PDF available, then that PDF download form block is being cached and the cached version is also displayed for page B which does not have a PDF download.

Same vice versa, if you visit Page B first, than the block is being cached with it's attribute display:none, and it will not be displayed for Page A either
Basically, we need the visibility to be re-evaluated on each page load.

We're fairly certain it's a cache issue as when we inspect the live rendered code we can see the block IDs being mixed up on the page.
For example: we'll see a body-tag includes a class "node-164", it's node 164 and the Download the PDF includes a class "PDF-node-205", so it's the cached version for node 205, it also includes the filename as a CSS classname, it's clearly the block for a different page node.

We've tried disabling the page cache, dynamic cache, and the twig cache and we're still having the same problem. And again it is only happens for anonymous users, logged in users do not see these cached blocks appearing on the wrong pages.

Has anyone run into this or know of another caching method that Drupal may be using that we're not aware of?

If I understand correctly, it is okay for the block to be cached, but each path/URL can have its own "version" of the form, right? In that case, you need to inform Drupal that this block changes depending on the current path/URL. Drupal 8 introduced the concept of "cache contexts" to do that. The cache context defines the external factors by which the return value can vary.

Now that you know this, you'll notice that this question is pretty similar to yours.

As documented in the change record, blocks can define their cache context by overriding the getCacheContexts() method from the BlockCase class. Overriding that method would probably look like this in your block class:

/**
 * {@inheritdoc}
 */
public function getCacheContexts() {
  return Cache::mergeContexts(parent::getCacheContexts(), ['url.path']);
}

As you  can see I'm using the url.path context here. A list of contexts provided by Drupal core can be found in the documentation.


Remove forum comment title I'm having problems with removing the title of comments on my forum.
I'm using the advanced forum module and the 'comment title' option is disabled. Anyone knows how to remove it? Thanks!

First install the devel module and then check the theme registry to see if the forum form is in the theme registry or not. for more information about registering a form visit this page. as an example to register the comment form you must use this code:

function YOUR-THEME-NAME_theme($existing, $type, $theme, $path) {
    return array(
           'comment_form' => array(
               'render element' => 'form',
            ),
       );
};

When checking the existence the form theme in theme registry make sure that you use the YOUR-THEME-NAME as administrator theme.

Now use the hook_form_id_alter to customize the form.to see the form elements write:

kpr($form);

now you can hide or change the order of form elements.

Here is the video tutorial


form Class, add a check function before the buildForm method I generate a sample Class form (and routing) with the drupal console.

Then, I have my class with some defaults generated methods ; getFormId, buildForm...

When the user go to the url path defined in the routing file, the buildForm method is called for build the the form.
I want call another function for check some datas before the buildForm method :

I function like :

function a_check_function_or_method_before_buildForm(...){
    // - Check some datas
    // - If all is ok, the buildForm can be called
    // - Else, if the custom function detect an error, the buildForm isn't called and the user is redirected to an error page
}

Is it possible to do that ? how can I do that ?

Thank you =)

You can do all that inside of buildForm():

use Symfony\Component\HttpKernel\Exception\HttpException;

public function buildForm(array $form, FormStateInterface $form_state) {

  $data = a_check_function_or_method_before_buildForm();

  // throw an exception
  if (empty($data)) {
    throw new HttpException(500, 'No data connection.');
  }

  // or return an empty form with an error message
  if (empty($data)) {
    return $form['#markup'] = '
No data could be collected!
';
  }

  // build the form with $data

}

Another possibility would be to call first a controller, which then decides what to do, return a form or something else.


How do I add an additional “Cancel account” operation link? On Drupal 8, I'm trying to modify /admin/people to have the cancel button appears under Edit link in operations.

What's the easiest way to do this?

It can be achieved by rewriting operation links field in views:

edit
cancel


Would hook_access() hide content from Views/Solr if returning FALSE? If I were to setup my own hook_access() and return FALSE based on a few different criteria, would this then hide the content from a view in modules like Views and Apache Solr?

hook_access() is only called when viewing/editing a single node. For all listings, both in core and views, you need to use the node access system. You also need to use that for node types which are not owned by your module.


How do I pre / post process aggregated css or js files? I want to declare the character encoding of our aggregated css files - how would I be able to pre or post process the aggregated css files in Drupal 8?

E.g. injecting @charset "UTF-8"; on top of all css files.

Using dependency injection we are able to inject a modified Asset Dumper, which can contain custom code.

Add to a custom module / or create a new module:

mymodule/mymodule.services.yml

services:
  asset.css.dumper:
    class: Drupal\mymodule\Asset\Utf8CssAssetDumper
  asset.css.collection_optimizer:
      class: Drupal\Core\Asset\CssCollectionOptimizer
      arguments: [ '@asset.css.collection_grouper', '@asset.css.optimizer', '@asset.css.dumper', '@state' ]

mymodule/src/Asset/Utf8CssAssetDumper.php

<?php
namespace Drupal\mymodule\Asset;

/**
 * Dumps a CSS asset and injects a utf-8 encoding string at beginning.
 */
class Utf8CssAssetDumper extends \Drupal\Core\Asset\AssetDumper {

  /**
   * {@inheritdoc}
   *
   * Injects utf-8 encoding statement at start of data string.
   */
  public function dump($data, $file_extension) {
    if ($file_extension == 'css') {
      // Don't override existing charsets.
      if (FALSE === strpos($data,'@charset ')) {
        // Charset string not found prepend.
        $data = "@charset \"UTF-8\";\n" . $data;
      }
    }
    return parent::dump($data, $file_extension);
  }
}

A short note on this: since this kicks in for all aggregated css files you might want to add additional checks to existing encodings etc.. If you have everything encoded the same way (which is very much suggestible) then this shouldn't cause weird side effects.

This approach also works for javascript (js) files:

services:
  asset.js.dumper
  asset.js.collection_optimizer


Find Menu Link Title given URL alias, to replace node Title in breadcrumbs In Drupal 8, how can one determine the Menu Link Title of a node, given its URL and other information like its route & parameters?

This is to modify the core path-based breadcrumbs (PathBasedBreadcrumbBuilder.php) to use the Menu Link Title of a node, as breadcrumb link text, rather than the node's Title field.  This would have to be a common requirement, since the default D8 breadcrumbs would be very long in deep menus with wordy titles.  For example, we would need:

  Home > Design > Drupal

instead of the D8 default:

  Home > Introduction to Our Design Services > Drupal 8: The Best CMS for Everything

for all nodes in the "Drupal" sub-menu.

The default breadcrumb service method PathBasedBreadcrumbBuilder::build uses a bunch of injected services to look up & check routes to each ancestor pathname of the node URL, then ultimately TitleResolver::getTitle to get the titles for those routes.  We would just need a way of looking up the corresponding MenuLinkContent instead so we could then get the menu title via MenuLinkContent::getTitle.

I have tried to outline the problem for the Drupal Module Development forum (change Breadcrumbs from Node Title to Menu Link Title) but got no response when asking how to simply bridge the gap between the space of URLs/routes and the space of menu link content.  Maybe this means it's not possible without a traversal of the menu: if so I would deeply appreciate some idea of where to start with that approach.

The sandbox module "wb_breadcrumbs' did the trick for me: https://www.drupal.org/sandbox/oles89/2367919


How to add mulitple legends in chart created with the Forena reports module? I have created a report using the module Forena reports. It's a compound graph of 3 items.

I need to mention these 3 items in legend. But I am not able to add more than 1 legend.
I am trying to create this graph from the front end itself. I don't want to use the frx file.

Any attribute supported as PHP SVGGraph options may be included as frx attributes also. Checkout the PHP SVGGraph library documentation to fully understand the available options, and identify the actual SVG Graph option you should be using (there are plenty of them).

In your case, I think you're looking for SVG Graph legends. In your Forena FRX file, you should be able to specify the desired legends (say 1st Legend, 2nd Legend and 3rd Legend) within the SVG tag of your chart with something similar to this example:

  <svg frx:renderer="FrxSVGGraph"
    frx:legend_entries_1="1st Legend"
    frx:legend_entries_2="2nd Legend"
    frx:legend_entries_3="3rd Legend"
    ...
  />

For many more details about how to create charts with Forena, refer to the reports/help.renderers#frxsvggraph in your own site (which is part of what comes with Forena), or refer to the online equivalent of it.

Note: if you only have 1 legend (say MyLegend), the SVG tag of your chart should be similar to this example (no need for the suffixes like _1, etc):

  <svg frx:renderer="FrxSVGGraph"
    frx:legend_entries="MyLegend"
    ...
  />


where to find the variables that can be changed through drush vset There are several variables which we can change through drush vset command like changing the file_temporary_path, maintenance_mode, user_register

I just need to know, how can I know the relevant variable names for which I need to make any changes through drush vset

Variables are saved in the variables table in the database. Every module can define its own variables. It is mostly common that the core and contributed modules save their configuration/settings as variables.

It is also mostly common that the modules add a prefix to their variables, so that you can look at the variables table in your database and search for the related module if they defined any variables.

Another approach would be looking in the source code of the configuration form for the related field. For example for file_temporary_path, you would see:

<input type="text" class="form-text" maxlength="255" size="60" value="/tmp"
name="file_temporary_path" id="edit-file-temporary-path">

Here is the name attribute hints that this configuration field will be saved in file_temporary_path variable.

Moreover, if you have Devel module installed, there is a Variable Editor under the path devel/variable, which lists all the variables defined in your site and gives you the possibility to edit or delete them.


Where do twig files find variables? for example for the file node.html.twig has a giant comment saying

* Available variables:
* - node: Full node entity.
 *   - id: The node ID.
 *   - bundle: The type of the node, for example, "page" or "article".
 *   - authorid: The user ID of the node author.
 *   - createdtime: Formatted creation date. Preprocess functions can
 *     reformat it by calling format_date() with the desired parameters on
 *     $variables['node']->getCreatedTime().
 * - label: The title of the node.
 * - content: All node items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.
 * - author_picture: The node author user entity, rendered using the "compact"
 *   view mode.
 * - metadata: Metadata for this node.
 * - date: Themed creation date field.
 * - author_name: Themed author name field.
 * - url: Direct URL of the current node.
 * - display_submitted: Whether submission information should be displayed.
 * - attributes: HTML attributes for the containing element.
 *   The attributes.class element may contain one or more of the following
 *   classes:
 *   - node: The current template type (also known as a "theming hook").
 *   - node--type-[type]: The current node type. For example, if the node is an
 *     "Article" it would result in "node--type-article". Note that the machine
 *     name will often be in a short form of the human readable label.
 *   - node--view-mode-[view_mode]: The View Mode of the node; for example, a
 *     teaser would result in: "node--view-mode-teaser", and
 *     full: "node--view-mode-full".
 *   The following are controlled through the node publishing options.
 *   - node--promoted: Appears on nodes promoted to the front page.
 *   - node--sticky: Appears on nodes ordered above other non-sticky nodes in
 *     teaser listings.
 *   - node--unpublished: Appears on unpublished nodes visible only to site
 *     admins.
 * - title_attributes: Same as attributes, except applied to the main title
 *   tag that appears in the template.
 * - content_attributes: Same as attributes, except applied to the main
 *   content tag that appears in the template.
 * - author_attributes: Same as attributes, except applied to the author of
 *   the node tag that appears in the template.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 * - view_mode: View mode; for example, "teaser" or "full".
 * - teaser: Flag for the teaser state. Will be true if view_mode is 'teaser'.
 * - page: Flag for the full page state. Will be true if view_mode is 'full'.
 * - readmore: Flag for more state. Will be true if the teaser content of the
 *   node cannot hold the main body content.
 * - logged_in: Flag for authenticated user status. Will be true when the
 *   current user is a logged-in member.
 * - is_admin: Flag for admin user status. Will be true when the current user
 *   is an administrator.

Where would these come from?

When I write my own template file how do I know what variables are available in my new template file?

Variables can be added and manipulated in preprocess functions just as with .tpl.php files.

Twig has a dump() command that can allow you to see the available variables.


Execute pending queues using batch? Possible? I have implemented the Queue API inside hook_cron, to do certain update operations on a site:

function HOOK_cron() {
  $interval = variable_get('variable_val', 60 * 60 * 24);
  if (time() >= variable_get('cron_next_execution', 0)) {
    variable_set('cron_next_execution', time() + $interval);
    $queue = 'MODULE_queue';
    $queue = DrupalQueue::get($queue);
    $query = db_query('SELECT nid FROM {node} WHERE type=:type', array(':type' => 'profile'))->fetchAll();
    foreach ($query as $node_obj) {
      $node = node_load($node_obj->nid);
      $queue->createItem($node);
    }
  }
}

where MODULE_queue is name of the queue, who's worker callback does some task on the nodes.

At any moment of time I would like the administrators to be able to run the updates manually using batch.
I would like something like this

Check if there is anything pending in a queue at the moment Admin chooses to manually update, and execute them in batch.
If not just run a manual batch update.

So, I'm stuck at the part where I need to run the queue inside batch. I am not sure if this even is possible. Any pointers would be highly appreciated.

Check: https://drupal.org/project/queue_ui

  Process queue with Batch API


Views Contextual Filters: Using node's URL alias as a conditional filter I have Drupal content whose nodes have URL aliases;

/node/1 routes to /bar

I also have a View which passes a NID as a contextual filter:

WHEN THE FILTER VALUE IS NOT AVAILABLE:

[selected radio] Provide default value

TYPE

[selected dropdown] Raw value from URL

PATH COMPONENT:

[selected dropdown] 1

[checked] Use path alias

View's Path is set for /foo/%

So:

/node/1 returns node

/bar returns node

/foo/1 returns view

/foo/bar returns a white screen

How do I allow the View to access the node's URL alias as a conditional filter?

Thank you

Maybe the View Url Path Arguments module. I am seeing it recommended in this thread, but I'm really not sure if that's your issue or not.

Alternatively, you can implement hook_views_pre_view and alter the argument passed to the view based on the value in the url, i.e. do the conversion from alias to id manually. If you have an issue when your alias contains a /, an alternative may be to use a query string for the contextual argument.


How do I apply a custom set of blocks to a custom content type I have a custom content type I call a Listing. It contains a few hundred fields, and it has a custom template, which renders the node indie the main content area.

How do I configure the sidebar and other blocks to appear/not appear for only this content type and not all content?

This depends on the information you would like to show in the sidebar. If you want to show some static information like for example a help text, then you can create a block in admin / structure / blocks. After you added a new block, you can modify the visibility settings of this Block (and many other settings). For example set the block to to show only on a specific path, content type or whatever.

The other way or case you might have, is to show dynamic data which has a relation to the content you're currently looking at. These dynamic blocks can be built for example with Views or you can create them programmatically in an own module.

The placement of the blocks works like on the first case. But there are other ways to place a block (e.g with Context).


exception 'TwitterException' with message 'Bad Request' I am trying to setup twitter module for Drupal 7 on my localhost. I followed the installation instructions as given in Twitter 7.x installation guide. I followed steps until "Add Twitter accounts" when i start getting this error.

Could not obtain a valid token from the Twitter API. Please review the configuration.

The dblog has the following information:

  exception 'TwitterException' with message 'Bad Request' in
  C:\wamp\www\test_twitter\sites\all\modules\twitter\twitter.lib.php:142
  Stack trace: #0
  C:\wamp\www\test_twitter\sites\all\modules\twitter\twitter.lib.php(101):
  Twitter->request('https://api.twi...') #1
  C:\wamp\www\test_twitter\sites\all\modules\twitter\twitter.lib.php(51):
  Twitter->auth_request('https://api.twi...', Array) #2
  C:\wamp\www\test_twitter\sites\all\modules\twitter\twitter.pages.inc(336):
  Twitter->get_request_token() #3
  C:\wamp\www\test_twitter\includes\form.inc(1464):
  twitter_auth_account_form_submit(Array, Array) #4
  C:\wamp\www\test_twitter\includes\form.inc(860):
  form_execute_handlers('submit', Array, Array) #5
  C:\wamp\www\test_twitter\includes\form.inc(374):
  drupal_process_form('twitter_auth_ac...', Array, Array) #6
  C:\wamp\www\test_twitter\includes\form.inc(131):
  drupal_build_form('twitter_auth_ac...', Array) #7
  C:\wamp\www\test_twitter\sites\all\modules\twitter\twitter.pages.inc(130):
  drupal_get_form('twitter_auth_ac...') #8 [internal function]:
  twitter_user_settings() #9
  C:\wamp\www\test_twitter\includes\menu.inc(517):
  call_user_func_array('twitter_user_se...', Array) #10
  C:\wamp\www\test_twitter\index.php(21): menu_execute_active_handler()

  11 {main}

I also have oauth module installed as given in the requirements.

Additional info:

My machine accesses internet via a proxy server and i do have proxy settings given in settings.php file. Not sure why it should cause problems.
I was able to run twitter API commands using twitteroauth library in a standalone application. It was throwing errors before i gave it the proxy settings for curl.

Can anyone help?

I actually had a lot of trouble setting the Twitter module up on my localhost for testing, so I just created a blog post about how to set that up, that includes some tips on doing this with localhost: http://drupalwoo.wordpress.com/2013/04/22/how-to-show-tweets-from-your-twitter-account-on-your-drupal-website/

Here are the couple of things that I think my be relevant for you to check:

If you’re testing on localhost, use the following urls for your website and callback URLs (don’t worry, these are just placeholders, and your drupal site will send the correct callback URL when it connects):

Website URL: http://127.0.0.1:8000/twitter/oauth
Callback URL: http://127.0.0.1:8000/twitter/oauth

If you’re still getting errors when testing with localhost, make sure the version of the module you’re using has the patch #5 on this issue queue: http://drupal.org/node/1924478#comment-7260928 (if you have an older version of the module, prior to the incorporation of the patch, get the latest stable/dev release that includes it and uninstall and install the module)


How to alter a form base on the users' request info? I would like to customize a form base on the users' request info in a page callback. I use drupal_get_form (or node_add for node create form) to get the renderable array, but most changes to the array here have no effect.

I know that we usually use hook_form_alter, but it seems not suit here.

I would like to hide/set a field, change a field's title/options etc. based on the query parameters or page arguments.

Do we have any methods to get the "raw describing form" and then modify and render it?

You should definitely use hook_form_alter() for that - no need to go a different route, it'll just make things harder for no benefit. Doing things the standard way your code could be as simple as:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo_form' && isset($_GET['bar'])) {
    $form['baz']['#access'] = FALSE;
  }
}


Send Commit message on Acquia Hook by Slack Based on Automating with Cloud Hooks I've implemented  Slack notification based on Simple Slack Notification Bash Script

site="$1"
target_env="$2"
source_branch="$3"
deployed_tag="$4"
repo_url="$5"
repo_type="$6"

FILE=$HOME/slack_settings

if [ -f $FILE ]; then
  # Load the Slack webhook URL (which is not stored in this repo).
  . $HOME/slack_settings

  # Post deployment notice to Slack

  if [ "$source_branch" != "$deployed_tag" ]; then
    curl -X POST --data-urlencode "payload={\"username\": \"Acquia Cloud\", \"text\": \"An updated deployment has been made to *$site.$target_env* using branch *$source_branch* as *$deployed_tag*.\", \"icon_emoji\": \":acquiacloud:\"}" $SLACK_WEBHOOK_URL
  else
    curl -X POST --data-urlencode "payload={\"username\": \"Acquia Cloud\", \"text\": \"An updated deployment has been made to *$site.$target_env* using tag *$deployed_tag*.\", \"icon_emoji\": \":acquiacloud:\"}" $SLACK_WEBHOOK_URL
  fi
else
  echo "File $FILE does not exist."
fi

It works correctly, it sends the message,

  An updated deployment has been made to mysitexxxx.dev using tag dev.

But What I need is the commit's message,How can I get commit message on Acquia post-code-update?

The commit message isn't passed in to the script, so you have to get it from somewhere else. I'm not sure if there is a git repository available to the cloud hook scripts on Acquia's cloud servers in general (it seems like there must be, but...I can't find an answer about where it is in their docs). You do have the repository url and the branch/tag, so you could try a shallow clone of the tag to get the data:

git clone --depth 1 --branch $deployed_tag $repo_url clonedirectory
cd clonedirectory
commit_message=`git show -s --format=%B`
...
echo $commit_message

You can use the $commit_message variable in the slack commands.

Of course...you have to figure out how to authenticate to the git repo and I'm not sure what's a great solution there.

Really I hope someone will reply with the location of a git clone that's available on cloud servers.


How do I insert the image into article? I am using field image to insert image into article.
The image can't show in article body.

How do I insert the image into article?

If you have a wysiwyg option you can insert images into the body field.  There is a wysiwyg module that provides good integration and management and lets you use one of several engines.  If it is okay to have the image at the start or end of the body text, and not in the middle, then go to the Display Fields tab at the top of your screenshot and drag your image field into the appropriate order.  Also you can set image display size and other options from that area.


Keep custom theme when using AJAX submit I am using the following code to switch to a custom theme based on the URL

function job_agent_custom_theme() {
  if (arg(0) == 'vista') {
    return 'vista';
  }
}

This works great and will switch to my "vista" theme when "vista" is in the URL. The problem is that one of my pages has a form that is submitted via AJAX. I created the form using the standard Drupal form API and creating my submit button like so

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array('class' => array('submit')),
  '#ajax' => array(
    'callback' => '_display_form',
    'wrapper' => 'ajax_wrapper',
    'effect' => 'fade',
    'event' => 'click',
  ),
);

So the problem is that when I submit the AJAX form, the page switches to this weird hybrid of the default theme and my custom theme. It's like they are both loaded. Am I missing something? How do I preserve the custom theme when submitting an AJAX form. It also seems really weird to me that the entire page would refresh and switch to a different theme anyway. I would think that defeats the whole purpose of AJAX. I can understand the contents of my ajax_wrapper changing, but not the entire page. Anyway, does anyone know of a way to preserve my theme when submitting via AJAX?

EDIT: Oh and I forgot a big piece to this puzzle. This ONLY happens with anonymous users. If I am logged in, it works as expected and when submitting the form, the custom theme is preserved, but if I am NOT logged in I get the mish mash theme.

THANKS

The form AJAX callback uses /system/ajax as the default. The menu router item for /system/ajax implements a theme callback to try and render the ajax contents in the same theme. For example, perhaps this is a node edit form and you have set node forms to use the same theme as the admin theme. The callback will find that. In your case, it is likely rendering in what it thinks is the default theme. Fortunately, you can specify your own ajax path like so:

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array('class' => array('submit')),
  '#ajax' => array(
    'callback' => '_display_form',
    'wrapper' => 'ajax_wrapper',
    'effect' => 'fade',
    'event' => 'click',
    'path' => 'vista/system/ajax'
  ),
);

You'll then have to create a menu item for 'vista/system/ajax', which I guess would be a duplicate of 'system/ajax' without theme callback. Perhaps something like this:

/**
 * implements hook_menu
 */
function mymodule_menu() {
  $items['vista/system/ajax'] = array(
    'title' => 'AHAH callback',
    'page callback' => 'ajax_form_callback',
    'delivery callback' => 'ajax_deliver',
    'access callback' => TRUE,
    // 'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
    'file path' => 'includes',
    'file' => 'form.inc',
  );
  return $items;
}

Don't forget to clear cache so the new menu item takes affect.

Also, I wanted to bring your attention to the ThemeKey module which is great way to change themes based on path.


List Nodes/Content Type Items with same tags as current On the node page I'd like to add a linked list of other nodes tagged with the same tag/taxonomy term. How can this be achieved? Via Views?

Any help will be highly appreciated

There's a module that does that for you: Similar by Terms. But you can also do this with Views using Contextual Filters & Relationships. This comment on Drupal.org explains it quite well:

  Its really easy in D7. Coding is not at all required.

  Taxonomy is a field in D7. I will explain how to create a Related
  Content block using Views.

  Create an argument by adding the taxonomy field on which you want to
  find the related nodes. Select "Provide default argument". Argument
  type = "Taxonomy Term ID from URL" Remove tick from "Load default
  argument from term page" Tick the "Load default argument from node
  page, thats good for related taxonomy blocks." To remove duplicates
  you have to follow the following points.

  Open "Query settings" in the "Advanced Settings". Tick "Distinct".
  This gives you a perfect "Related Articles" or "Related Nodes" using
  Views.


Drush Scripting? Or Batch API? We have an Ubercart website that handles large volumes of orders daily, processes them and runs other tasks like billing, delivery routing, and future order creation.

Some of these tasks are heavy and sometimes cause PHP to timeout. Is there a better way to run these tasks like through Drush or Batch API?

Speed is not necessarily a priority (although nice), but we want to avoid timeouts, which can sometimes cause issues with billing correctly and scheduling daily orders.

Is Drush script the better option, or Batch API? Are there any tutorials to make better use of both?

I would not suggest to use the batch API, simply for the fact that batch operations depend from the browser; if for any reason the browser crashes, or it loses the connection with the server, the batch operations will not terminate, or (worse) they will be hanging.
In fact, to avoid PHP timeouts, the batch operations cause the browser to ping the batch page at intervals; that is what happens, whenever JavaScript code is involved, or not (in the later case, Drupal uses the refresh meta tag).

In these cases, Drush is probably a better choice; you can create a custom module that implements specific Drush commands, or simply add a command file in the directory Drush uses for its commands.


Unable to show the Uploaded Image by the user in user submitted form for node On my site, we have a form which directly adds data into one content type. When user submits the form, all the field data is inserted. It's working fine except the Image field.

What I want is that the image field is automatically uploaded and is shown as automatically uploaded in the node admin. In the code below, I am providing a static image just to make it work and it still doesn't :(.

I have been banging my head on it for hours and hours and I'll be very thankful if you can provide me with any hope or solution ....

So with the following code, I've been able to upload the Image in the public://tmpprofiles folder. The problem is that file_copy is not working and throws an exception in error log that that

File http://yoursite.com/sites/default/files/tmpprofiles/anewimage.png could not be copied because it does not exist.

But it does exist!!!!

I don't why it is saying that. I guess it means that all the code is working except the last two lines. Those are the lines which will attach the image to the node and therefore would show this image as an uploaded image in the node admin.

Please discard my meh code if you've a better way of doing this.

Code

  $path = './sites/default/files/animage.png';
  $filetitle = 'newimage';
  $filename = 'anewimage.png';

  $file_temp = file_get_contents($path);

  $file_temp = file_save_data($file_temp, 'public://tmpprofiles/' . $filename, FILE_EXISTS_RENAME);

  $tmp_file_path = 'public://tmpprofiles/' . $filename;

  $file_path = file_create_url($tmp_file_path);

  $file = (object) array(
    'uid' => 1,
    'uri' => $file_path,
    'filemime' => file_get_mimetype($file_path),
    'status' => 1,
  );

  //These two lines don't work.

  $file = file_copy($file, 'public://another');
  $new_moment_node->field_profile_photo[$new_moment_node->language][0] = (array) $file;

In Drupal 7 you can use system_retrieve_file()

  As system_retrieve_file function will download a file from a remote
  source, copy it from temp to a specified destination and optionally
  save it to the file_managed table if you want it to be managed.

Can you try this Save image from URL to a field from a custom module


Where are Commerce 2 hooks (or Events) in Commerce 2 I am working on replacing our payment system from D7/DC1 to D8/DC2 and the original code makes use of hooks. I have replaced some of them with events but I cannot find any information on the DC2 versions of:
mymodule_form_commerce_checkout_form_checkout_alter()
mymodule_form_commerce_checkout_form_review_alter()
mymodule_form_commerce_checkout_complete()
mymodule_form_commerce_cart_add_to_cart_form_alter()

Are they still the same or much like the former cart (add, update, remove) hooks, these are also events but I can't locate documentation on them. Anyone know the equivalent events or where to find the docs on these (or their replacements)
/* Small Update */
I found OrderEvents and I think I need ORDER_PAID to replace mymodule_form_commerce_checkout_complete()
Does this look correct?
I added OrderEvents::ORDER_PAID => 'orderPaid' to my getSubscribedEvents(){} array and have:
public function orderPaid(OrderEvent $event){
    $order = $event->getEntity();
    //Some internal logic here
    $order->save();
  }

//Updated
Tried a hook form alter and ran through my checkout process and nothing is showing in the logs
function srs_hook_form_alter(&$form, $form_state, $form_id){
  \Drupal::logger('hook_form_alter fires')->info('
' . print_r($form_id, TRUE) . '
');

}

as you've discovered, you can look in any module's src/Event/*Events.php file to find a list of their events. Using the order paid event is one way to react once you know that payment has been collected, but note that in scenarios where an order is placed with only a payment authorization (and not a capture), that event would not have been fired yet.
That may be fine in your case - if not, I'd recommend the commerce_order.place.pre_transition or commerce_order.place.post_transition events that are triggered when the order is placed. That event is coming from the state machine module and correlates to order workflow transitions. You can read more about it in the module's readme.
As for form alters, those exist in D8 as they did in D7.


AJAX doesn't work in custom form element I want to create a custom form element for email that have a textfield and button and when click button send an email but ajax not working inside form elemen class. I test it in form api and it's ok but when move in form element on button click nothing happend
this is my code

<?php
/**
 * Created by IntelliJ IDEA.
 * User: peter
 * Date: 24/12/18
 * Time: 13:59
 */

namespace Drupal\aqr_basic\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\FormElement;

/**
 * Provides a form element to display a email.
 *
 *
 * @FormElement("aqr_email")
 */
class EmailElement extends FormElement {

  public function getInfo() {
    $class = get_class($this);
    return [
      '#pre_render' => [
        [$class, 'preRenderSelect'],
      ],
    ];
  }

  public static function preRenderSelect($element) {
    dump($element);
    $email = [
      '#type' => 'email',
      '#title' => $element['#emailTitle'],
    ];
    $email = array_merge($email,$element['email']);
    $btnSendCode = [
      '#type' => 'ajax_button',
      '#value' => $element['#btnSendCodeTitle'],
      '#ajax' => [                  //////this ajax not work
        'callback' => '::email',
        'event' => 'click',
      ],
    ];

    $btnSendCode = array_merge($btnSendCode,$element['btnSendCode']);
    $verifyGroup = [
      '#type' => 'fieldgroup',
      '#attributes' => ['class' => ['hidden']],

    ];
    $verifyGroup['emailCode'] = [
      '#type' => 'textfield',
      '#title' => $element['#emailCodeTitle'],
    ];
    $verifyGroup['emailCode'] = array_merge($verifyGroup['emailCode'],$element['verifyGroup']['emailCode']);
    $verifyGroup['btnVerifyCode'] = [
      '#type' => 'ajax_button',
      '#value' => $element['#btnVerifyCodeTitle'],
      '#suffix' => '
' . $element['#description'] . '
',
    ];
    $verifyGroup['btnVerifyCode'] = array_merge($verifyGroup['btnVerifyCode'],$element['verifyGroup']['btnVerifyCode']);

    $element = [
//      '#attached'=>[
//        'library' => ['aqr_basic/state'],
//        'drupalSettings' => [
//          'id' => $element['#id'],
//          'cities' => json_encode($cities),
//        ],
//      ],
      'email' => $email,
      'btnSendCode' => $btnSendCode,
      'verifyGroup' => $verifyGroup,
      '#attributes' => ['id' => ['email-wrapper-id'], 'class' => ['email_verify']],
    ];
    dump($element);
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    return $input;
  }

  public static function email(array &$form, FormStateInterface $form_state) {

    dump($form);

    return $form;
  }
}

I believe you may need this syntax as your callback, I think because everything went to being 'static' when you moved your demo code from a form to a Element.

 $btnSendCode = [
  '#type' => 'ajax_button',
  '#value' => $element['#btnSendCodeTitle'],
  '#ajax' => [
    'callback' => ['\Drupal\aqr_basic\Element\EmailElement', 'email'],
    'event' => 'click',
  ],
];


How to add block-like visibility settings to nodes? I have created a custom content type 'campaign' in my module using hook_node_info() and added fields using hook_field_group_info(). This campaign content type will be shown to users site wide in modals/pop-ups using CTool modal on page load (hook_init()).

What I'm looking for is, to give an option to admins to restrict this pop-up/modal for different roles or paths. Same like block section is doing. For example whether to show a block on node/104 or not, or wether to show a block for (anonymous) users only or not. Like shown in the screenshot below.

My aim is that, while creating 'campaign' nodes, admins should be able to select pages or roles to show that particular campaign or not.

Can you please guide me how can I use Drupal block logic here? Or do you maybe can make some code suggestions I can start with in my custom module?

Block visibility rules are kind of fundamentally different from nodes in that nodes are intended to always show up using the "full" or "default" display mode in the main content block/region of the specific node's unique URL. On the other hand, blocks go hand-in-hand with the ability to be placed in any region on any page.  Block visibility can group permissions (ie role based rules)  along with path-or-url-based rules, but nodes cannot natively do this.

I can think of three possible alternatives (there might be more):

1) Embed Nodes in a block using one of these modules, and then use block visibility rules to place it.  This has the drawback that you have to tie things together quite manually in two places.

2) If you're showing campaign nodes on other nodes, then you can use an entity_reference field to reference the campaign node from another node (or vice versa)  and then just set the entity reference field's display settings to render the entity as if it were a field on the node.

3) Write a completely custom solution to mimic block visibility rules for nodes.  I'd start with a Text (long) field (call it field_campaign_urls),  then in a node_form_alter() hook alter the display to show up in a vertical tab (or you could use Field Group module to do this in the UI).  Then you'd need to implement a hook that gets called on all pages, e.g. hook_page_alter test the internal Drupal URL (and optionally also the pathauto alias) for a match against all values in the field_campaign_urls database table. The challenge here will be writing the wildcard functionality, you'll need to figure out how to convert  some/url/* into a database condition LIKE 'some/url/%'  This is also where you might want to start digging into the block.module code to find out more about the internal structure of how block visibility query logic works.   Finally, you'll need to combine this logic with your custom node access logic as well.  And indeed figure out which block region you want to add your node to.  You may leverage drupal_add_region_content to add your rendered node to a specific region.


Webform in block allowing clicking on send button and redirecting to page view, without validation the fields even when they are empty Webform in block is allowing to click on send button and redirecting to page view, without validation the fields even when they are empty.

so if I come to the website and click on submit (on my form in block) instead of validationd and showing the little popup it redirects me to the form page view url.

But when I start typing something in my email fieled, then after clicking on submit I get a popup that email is in wrong format etc.

How to correct the behavior so that the popup shows the message like "the field is empty" etc.

Is it a bug of webform or am I missing something?

This is because you somehow missed making the E-mail field mandatory.
You can do so by following the steps given below:

Edit the existing webform content at : yourhost.com/admin/content and selecting edit for your webform.
Click the "Webform" tab, and check the "MANDATORY" option for the required field.
Click "Save". Thats it!


Using built in jQuery UI in my theme Every page of my theme will need to use jquery UI. I know it's included with Drupal 7, but I can't really decipher Drupal's way-too-technical documentation.  It looks like the only way to do it is with the template.php file.  But since I don't understand that file, I'm trying to avoid doing it that way.

Is there another way, or should I just try the template.php file?

Adding JS to a page is really not that hard, even though you need to use php.

For normal JS files, you could do something like this

drupal_add_js($path_to_js)

Drupal has however registered jQuery UI into libraries making it easier to add both JS and CSS files for certain jQuery UI plugins. This can be done using

drupal_add_library($module, $library);

All the jQuery UI plugins exist in the system module, so you could do

drupal_add_library('system', 'ui');

or

drupal_add_library('system', 'ui.accordion');

Some of these plugins have dependencies because they use other plugins. Drupal handles this very cleverly and will included the components needed.

You can see the full list of jQuery plugins here. This is formatted as a PHP array, but generally the naming convention is ui.PLUGIN-NAME.

If you need to add the JS on every page you could simply add a preprocess page hook and add them there. This would look something like this in the template.php file.

function NAME_OF_THEME_preprocess_page(&$variables) {
  drupal_add_library('system', 'ui');
  drupal_add_library('system', 'ui.accordion');
  drupal_add_library('system', 'effects.highlight');
}


Using Drupal as client of a web service I need to use Drupal as client for a web service, for extracting data and showing it in a view or as content. (The format use is JSON or REST.)

I use a Web Service Client module in Drupal 7, and the Services module in Drupal 6, but I don't know how to use them. I read the documentation but I don't get any result.

Can anyone help on this issue, or tell me how to use these modules? Is there any other module for this purpose?

A possible solution: I find a module called XML VIEWS but this module convert only XML files.

Now, I programing in this module for convert the JSON to XML.

In this files: xml_views_plugin_query_xml.inc

In this function: Execute

Anyone have another solution?

Drupal has specific functions that can help with communicating with a web service, and handling JSON input.
Drupal 7 has the following functions:

drupal_http_request() is the function to make a HTTP request to a remote site, and it handles GET, POST, PUT or any other HTTP requests; it also handles redirects.
drupal_http_build_query() transform an array in an rawurlencode()-d string.
drupal_json_decode() decodes a JSON string in PHP code.
drupal_json_encode() encode a PHP variable into a string that is handled by JSON.

With those functions you can write your own custom module to make requests to a site implementing a web service.

If there are some restrictions about the number of requests that can be done to the web server, you can use the Drupal functions to cache the result obtained from the web server:

cache_get(), to get the data saved in the cache
cache_set(), to save the data in the cache

To notice that Drupal supports more than one cache bin, and modules can use their own cache bins, when necessary.
Drupal supports also cache items that are automatically removed at the successive cache swipe (see the description for the CACHE_TEMPORARY constant). Implementing hook_flush_caches(), the modules allow to the administrator users to clean the cache used by the module when the "Clear" button on the "Performance" page is clicked, or any times a module calls drupal_flush_all_caches().

In Drupal 7, cache data for frequently used data are associated with a static variable handled with drupal_static(). When the data is really frequently used when outputting the same page, code similar to the following one is used:

  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['implementations'] = &drupal_static(__FUNCTION__);
  }
  $implementations = &$drupal_static_fast['implementations'];

  // …

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }

The code is part of module_implements().


Views RSS channel properties added with hook_views_query_alter() disappear I have applied this patch to the Views module so that it will add the channel properties of pubDate and lastBuildDate.

Then I ran Drupal "Clear all caches" within /admin/config/development/performance.

The added channel properties are only available for the first page requested each time after running another Drupal "Clear all caches".

For Drupal 7 how can I ensure that views RSS channel properties that are added with hook_views_query_alter() remain?

=================================================================================

I have already tried the “Views RSS” module and after downloading and enabling this module along with its associated “views_rss_core” the “RSS Feed – Fields” radio button does not display and only the “RSS Feed” option is present which comes from the “Views” module.

You can do this with Views RSS 2 and hook_views_rss_item_elements().

As we can see in the documentation for Views RSS API views_rss_get it can :

  Fetch item elements provided by other modules.

So to create your own item element do the following :

First thing, revert your hack, it won't be needed.
Download and install the module Views RSS (and Core Elements, DC Elements)
Create a default view for content and fields
Add a feed to it
Style it as RSS Feed - Fields
In the settings pubDate is avaible alerady so we don't have to worry about that.

Create a tiny module and enter the following

/**
 * Implements hook_views_rss_namespaces().
 */
function MY_MODULE_views_rss_item_elements() {
  $elements['dc:lastBuildDate'] = array(
    'description' => t('My custom lastBuildDate field.'),
    'help' => '',
  );
  return $elements;
}

Then install it and clear your cache.

Now, in the Views RSS field settings there should be a new field for your custom field (see image)

And when you view your feed it should be included (see image - last line)

Note: if you look at the snippet, it adds the field to the dc namespace. If you want to use another or provide your own namespaces have a look at the API and hooks.


how to hide text format tips for text field in a module, not theme? I need to hide the text format tips for body field, depending on user role, in a module. After some research, I found this kind of code:

function mymodule_form_node_form_alter(&$form, &$form_state) {
  if (isset($form['body'][LANGUAGE_NONE][0]['#after_build'])) {
    $form['body'][LANGUAGE_NONE][0]['#after_build'][] = 'mymodule_node_after_build';
  } else {
     $form['body'][LANGUAGE_NONE][0]['#after_build'] = array('mymodule_node_after_build');
  }
}
function mymodule_node_after_build(&$form, &$form_state) {
  /*if (!user_access('administer filters')) {
    $form['LANGUAGE_NONE']['0']['format']['#attributes']['class'][] = 'invisible';
  }*/
}

*I know the mymodule_node_after_build function is all commented, so
it's doing nothing, but it's here only for illustration. Just adding
#after_build to the form or field makes it all invisible - and this is the issue here.*

The above code results in field body not displayed at all, instead of just hiding text format info. More precisely, the html contains this code in place of the body field (just an empty div):

I tried setting this also for:

$form['body'][LANGUAGE_NONE]['#after_build']
$form['body']['#after_build']
$form['#after_build']

(the last one displays white space instead of the whole form)

Unless there is another much simpler solution to this problem, I'd like to use the above approach or something similar in a module, but it's not working!! So what's wrong with it?

Here is the simple code you can write your role base logic in hidetips_test_node_form_after_build() fuction.

function hidetips_form_node_form_alter(&$form, &$form_state) {
  $form['#after_build'][] = 'hidetips_test_node_form_after_build';
}

function hidetips_test_node_form_after_build($form) {
  // Here you can write your logic for role based hide and display.
  $form['body']['und']['0']['format']['#access'] = FALSE;
    return $form;
}


what does hook_field_is_empty actually mean? I feel like I'm retarded but when I read the page at api.drupal.org I'm still wondering what the point is of the function. It says 'Define what constitutes an empty item for a field type'. I'd expect that this function would put NULL there if a value wouldn't be present, but it doesn't look like this is happening.
Also: is it required to write this function in my .module file to get a fieldname in my drop-down list of the Manage Fields page (you know, as a babystep)

I think it's used for fields that can accept multiple values, to determine whether or not the last item in the list has been filled out, or is in the 'new' state without having been filled out.

If this function didn't exist the field API wouldn't be able to make a distinction between what is classed as a filled-in row, and what is a 'New' row that hasn't been filled out, and for which the values should not be saved.

It can also be used to ensure that a minimum of columns in a field are filled out before it's classed as a save-able value.

If I remember rightly the hook is 'required' for modules that provide a field, so I'm not sure if you'll get away with leaving it out.

You could easily just implement it and return a TRUE or FALSE though for testing purposes.


How do I set the HTML element of a text field? My request couldn't be simpler - I have a custom text field on a node (field type text), and I want this field to be placed in a Panels layout in a <h3> element.

For Node title, I can choose the HTML element. For text fields, there seems to be no such option. The available formatters are Default, Trimmed and Plain text, none of which have any settings. Views fields have all sorts of easy field rewriting features, but I can't find anything equivalent in Panels.

How can I get the drop down of HTML elements like you get for Node Title for a custom field? Or change the output another way?

I'd prefer not to have to rewrite my entire Panels layout and create a whole new region for this one field in its .tpl file simply to put some text in a <h3>.

Have you tried Panels Extra Styles ? As per module page :

  Panels Wrapper

  Wrap your panes and regions with unlimited possibilities.
  Go HTML5! Wrap your content in the newly defined tags. Add custom
  containers and HTM

  Wrapper: Element

  Wrap any region or pane with one of several dozen tags, including
  HTML5 elements.

  Wrapper: Raw

  Wrap any region or pane with a custom raw prefix and suffix.

  Sample output after applying the wrapper elements on 1 region and 2
  content panes: the powered by block and a main menu.


Programmatically creating a content type with file field in a custom module I'm writing a custom module, which I've done before, but this is the first time I've tried to create a content type with fields. I implemented hook_node_info and the Content Type is showing up in the list of Content types in the dropdown from admin_menu, however, when I browse to admin/structure/types it is not listed.

I implemented hook_install and grabbed some code I found on another SO question. I have the code print out some debug info to my error log and it LOOKS like it all works, but when I browse to the Structure Content Type it doesn't show the field I added.

Here are hooks:

function mymod_node_info() {
  return array(
    'mymod_content' => array(
      'name' => t('My Mod'),
      'base' => 'mymod_content',
      'description' => t('A Description'),
    )
  );
}

function mymod_install() {
    error_log('mymod_install');
    $types = node_type_get_types();

    if ( ! field_info_field('field_mymod_myfile') ) {
        $field = array(
            'field_name' => 'field_mymod_myfile',
            'type' => 'file',
        );
        $created_field = field_create_field($field);
        error_log('---- field_create_field -----');
        error_log(var_export($created_field, true));
    }

    $instance = array(
        'field_name' => 'field_mymod_myfile',
        'entity_type' => 'mymod_content',
        'bundle' => 'mymod_content',
        'required' => TRUE,
    );
    $created_instance = field_create_instance($instance);
    error_log('---- field_create_instance -----');
    error_log(var_export($created_instance, true));
}

I can see a table called field_data_field_mymod_myfile in the database, so I know the first part worked. However, the table is empty.

The error log shows the field_create_instance() method returned this:

array (
  'field_name' => 'field_mymod_myfile',
  'entity_type' => 'mymod_content',
  'bundle' => 'mymod_content',
  'required' => true,
  'field_id' => '5',
)

Why doesn't my field show up on this content type?

This isn't so much an answer as it is an expansion on the previous answer.

I found these two links very helpful in figuring out what the system needs for custom fields to be added to your custom module node type.

Best: http://www.sitepoint.com/creating-a-new-drupal-node-type/

Good additional info: http://public-action.org/content/drupal-7-field-api-drupal-7-adding-custom-content-type-custom-fields-field-api

The problem I had was that these (and every other example I can find online) are very specific examples without enough documentation to help me figure out a solution to my own usage case.

What helped was tenken's comment to the OP about using the Features module to get the arrays for the custom fields.

So I downloaded the Features module and enabled it: https://drupal.org/project/features

Then I created the fields on my content type, using the admin interface in Drupal like you normally would, that I wanted the module to create. Then I browsed to Structure > Features > Create feature and put in a bogus name (I used "test") for the feature and then over in the components area click on "Field Instances" and check the boxes for the custom fields. The fields are all named something like node-[your node type machine name]-[field name], so in my case since I wanted an image field it was node-novel_section-field_image.

After selecting the custom fields for my node type I then just clicked on "Download feature" and saved the .tar file to my desktop, opened it, opened the "test" folder then viewed the test.features.field_base.inc and test.features.field_instance.inc to get the arrays I needed for my fields.

Then I just used the structure outlined by that first link I posted and after that it worked perfectly. For me.

I could not find any documentation on the array structures needed for things like image fields and taxonomy reference fields and it seemed all other tutorials and help requests online are focused on specific things like text fields.

Hopefully anyone having the same trouble I was having will see this and be able to make their setup work using these examples and the Features module like I did.

Thanks to tenken for pointing out this functionality of the Features module, I'd never used it and didn't know it would do that.


I'm assuming you're using an HTML5 DOCTYPE, The CDATA tags are required for XML-based documents (including XHTML).

The characters look to be hard-coded into common.inc, line 4287:

$embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
$embed_suffix = "\n//--><!]]>\n";

Examining that code I think the only way to intercept it would be to override theme_html_tag() in your theme, e.g.

function MYTHEME_html_tag($vars) {
  if ($vars['element']['#tag'] == 'script') {
    unset($vars['element']['#value_prefix'];
    unset($vars['element']['#value_suffix'];
  }

  return theme_html_tag($vars);
}


How can I throw a form error if a submission field has a certain value in webform? I am using mymodule_webform_submission_presave() to alter some of the data before it gets saved.
I want to check if a certain select field has a certain option selected, dont save the form to the db and give the user an error like "you may not pick this" and dont save the form.

I would remove the option itself from the form but this wont be possible.

I've also tried to do it via the webform gui but there is no rule which says "this select may not have this option selected", is there?

Thanks!

Create your own validation function of your webform and do it there:

function modulename_form_webform_client_form_FORMID_alter(&$form, &$form_state, $form_id) {
     //FORMID - your webform id
    $form['actions']['submit']['#validate'][] = 'modulename_form_webform_client_form_FORMID_validate';

}

function modulename_form_webform_client_form_FORMID_validate($form, &$form_state) {
    //validate it here
    if ($form_state['values']['yourvalue'] == 'somevalue') {
        form_set_error('you can\t do that');
    }
}

also you can use hook_form_alter to provide your own validate function.
Further reading form_set_error, hook_form_alter,


Menu link that uses title from router item's title callback? In the user menu, I would like the menu link for the "user" path to use the dynamic link title from the title callback, instead of a custom link title.

I know I could alter this on the theme layer, e.g. with hook_preprocess_menu_link(). But somehow I have the feeling there must be something simpler, that works out of the box..

Any ideas?

Menu links that are registered through hook_menu() do this already, so if you are using the system-provided menu link, it should pick up whatever you have altered "title callback" to be instead.

The system-provided 'user' menu link is being altered by user.module to prevent it from showing up to anonymous users (see user_menu_link_alter(), user_translated_menu_link_alter()). That might be getting in the way of what you want, in which case you could bypass/unset the user module implementation in a hook_module_implements_alter() function.

If you're using a custom menu link created through the UI, I don't believe you will be able to make that link title dynamic short of implementing hook_menu_link_alter() and hook_translated_menu_link_alter(). That's probably more work than intercepting it at the theme layer, though.


Drupal 7 views join two profile2 profiles together I would like to join two profile2 profiles so they appear as one row in the view module and not two rows like the example below. Can this be done?

Fields

User: Name
Content: image_profile_image

Relationships

User: Profile
User: Content authored

Have you tried Display Suit.

Also panels is a good solution for this.

Oskar


Views Block origin link in breadcrumb I've created a views block, which contains a list of same node types. The block is placed within another node on my page "home >> blockpage". When you now follow some link in the block view you will get a breadcrumb like "home >> pageFromBlock".
How to achieve a breadcrumb like "home >> blockpage >> pageFromBlock".

I am using drupal 7 with breadcrumb module and views.

You can do by using these modules:

Custom Breadcrumbs

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

Path Breadcrumbs

  This module is a solution for all problems with the breadcrumbs on
  your site!

  Path Breadcrumbs module helps you to create breadcrumbs for any
  page with any selection rules and load any entity from the
  URL!


Billing and shipping mismatch on some orders I just recently getting billing and shipping mismatch on some orders which in turn  affects shipping rates. On below transaction shipping rates get billed for Afghanistan, but address details are for USA. Payments go through to Paypal which then need to be refunded due to the mismatch in Countries.

Having a look in the database I get 4 entries for this order, 2 shipping and two billing.

At Home » Administration » Store » Orders >> order number I see this:

Billing information:
A. Customer
Afghanistan

Shipping information:
A. Customer
1234 Wild Trail
Chocolate, OH 44233
United States

Any advise on how to trouble shoot this? Thanks for your input.

Afghanistan is the default country in country select lists since it's first alphabetically. It appears to me that perhaps some part of your checkout form is causing a previously saved address to be overwritten. This is an infrequent but common issue when combining a variety of Ajax related features on a single checkout form. I'd begin debugging there to see if you can isolate the point at which stale address data is saved to the active billing profile accidentally.


Create nodes in a installation profile How can I create nodes in a installation profile? Can this be done in the .info file, or does it have to be done in the .install file?

When a profile needs to create something to make it accessible once the profile is installed (e.g. blocks, content types, fields), it does it in its hook_install() implementation. For example, the standard profile creates content types, fields, and input formats in its standard_install(); it also enables some of the standard blocks, and it set the Seven theme as administrative theme.

Drupal doesn't use any directives in the .info file to automatically create nodes, but a profile could implement code to parse extra directives in a .info file, for example in hook_modules_installed().

I would rather go with implementing hook_install(). I may consider using directives in the .info file if there is a module handling them and I am writing more than three profiles for which being able to change the nodes added from the profile is much important. I understand that avoiding to keep changing the code make less probable to introduce errors; since I know the code to use to create nodes, and the task is relatively simple, using directives in the .info file doesn't simplify much the code I would write for a profile.
I would take more in consideration a module that would back-port to Drupal 7 the code that in Drupal 8 handles the configuration files used to create content types, and fields for those content types, using YAML files. For example, this is the core/modules/forum/config/optional/node.type.forum.yml file that in Drupal 8.3 allows the Forum module to create its content type.

langcode: en
status: true
dependencies:
  enforced:
    module:
      - forum
name: 'Forum topic'
type: forum
description: 'A forum topic starts a new discussion thread within a forum.'
help: ''
new_revision: false
preview_mode: 1
display_submitted: true


entity_load failure: Adding revision capability to entity with existing data and unticking "create new revision" still creates a revision I am having trouble with entity_load returning an empty array on an entity api custom entity which previously was fine. The only change I've made is to add revision support which apart from creating the revision table etc. has also created a revision ID column in my custom entity table and filled this with NULL by default.

In troubleshooting why this is and trying to pin down if the revision is causing my problem, I've come across something which seems peculiar to me: creating an Article and unchecking "create new revision" still creates a revision.

My custom entity revision table is currently completely empty and I've been debugging and stepping through the code within entity_load but I cannot see where the problem is.

Where is my problem with the entity_load? Is the new revision being created despite unchecking the option a localised problem?

So I experimented and contrary to what I perceived, saving a node (as an example of an entity) even without "save a new revision" checked, still saves a revision...

So somewhere in the confusing bowels of the entity loading procedure it was diving through Drupal-shaped rabbit holes and trying to load revision information because it noted that the custom entity was revision enabled (where I enabled it in hook_entity_property_info). Because I'd only added the revision capability after using the entity there was none. So I had to do some SQL work.

Firstly I selected all information in the original table into the new table. In doing so, the auto-increment setup on the revision_id column populated the revision_id column in the revision_id with unique incremental values.

Secondly I did a big ol' looping thing to get all the revision_ids from the revision table and one-by-one put them in the original table. Details of that query are here after I had a little bit of trouble, but it might help someone else out.

Now it's working.


Content Moderation: Remove transition from select list programmatically How do I alter this select list programmatically in my module?

Permissions won't work here since all the roles can use the 'Request publish' transition, but the roles that can also use the 'Published' transition don't need to see 'Request publish'. I think the easiest way to make this change is to remove 'Request publish' from the dropdown list.

I'm working with hook_field_widget_form_alter()

The code that I'm trying to override is from formElement() in ModerationStateWidget.php.

Thanks.

Thanks @No Sssweat. You put me on the right track.

Since this is the node form, I opted to use hook_form_BASE_FORM_ID_alter().

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 */
function MY_MODULE_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $roles = \Drupal::currentUser()->getRoles();
  if (array_intersect(['role_1', 'role_2', 'role_3'], $roles)) {
    $options = isset($form['moderation_state']['widget']) ? $form['moderation_state']['widget'][0]['state']['#options'] : [];
    $options = array_diff_key($options, [
      'request_publish' => 'Request Publish',
      'request_unpublish' => 'Request unpublish',
      'request_delete' => 'Request Delete'
    ]);
    $form['moderation_state']['widget'][0]['state']['#options'] = $options;
  }
}


Views Editing Section Missing I upgraded a site from D6 to D7 and am coming across an interesting error with being able to edit my existing views. My views are all listed, but when I click on the edit button to edit a view the whole configuration section is missing- all the edit page shows is:

  Breadcrumb

  Title of view

  Auto preview
  Preview with contextual filters:
  Separate contextual filter values with a "/". For example, 40/12/10.
  Update Preview

New views do have the configuration area. Any help or ideas on what I might use to search for a solution to someone else that might have had this issue would also be appreciated. I haven't been able to come up with the right search terms to help find the answer. Thanks!

It turns out the problem was that the views were content panes and I hadn't enabled content panes in the CTools module. As soon as I turned that on they worked fine again.


Render multiple taxonomy term input as unordered list We have a content type allowing input from taxonomy term lists, and some fields allow multiple values.  When there are multiple values, the output always seems to string them together inline, as much as will fit the available display width. We are aware of the option "separated" with the option of commas, spaces, or slashes, but that still renders multiple terms on the same line if they fit.

What's desired is to render multiple terms in a one-item-per-line list, preferably an unordered list with or without bullets.  I tried looking at the CSS but all I could do was to add bullets, although it still rendered multiple terms inline. Suggestions? Thanks.

This may not fit your need exactly, but did you know that the Separator in the 'Multiple field settings' accepts html?

That means that you could use "
" as the separator, and they'll render on different lines, even if they are not in a list.

Would that be enough for your needs or do you need a list?

====================== Edit based on comments =======

Maybe just a simple css rule added to your theme then that places the break there for you:

.your-content-type .your-field-class a {
    display: block;
}

It looks, based on your comments, that the above example may be something like this for you:

.node-content-type .field-name-field-client a {
        display: block;
}

That should do it for you.  The 'block' (vs inline) display will put each link on a separate line.  If you do that, you can remove all the commas and other separators, or those will appear on separate lines too (because of the block display of the link).

** Note: I added one more selector (the content type selector) to make this rule even more specific.  Based on the rule above, this 'display: block' property will be applied only to nodes of this specific content type (so if you use this tag somewhere else, they won't just come out on separate lines unexpectedly).  Does that make sense?

To find what the content-type class for your node is, look into the page source again and find the line that looks like this:

The content type should be the second word in the class... in Drupal, all pages have the content type they belong to as a class, so that's awesome for theming!!

Finally, after changing your css, you may not see the result right away - you may need to clear your cache before your change will be applied.

Hope this helps!


Give a specific user role the ability to edit, delete users other specific role I'm working in Drupal 7.

I want to give to a specific user role named "test role" the ability to edit, and delete users whose role is students.
Users with that role should not modify the admin account, and any other account with other roles.

Sounds like a combination of the following:

http://drupal.org/project/role_delegation - Adds a permission to assign roles per role
http://drupal.org/project/administerusersbyrole - Allows controlling, based on roles, which users can admin which other users.


Adding content to a database table during module install I created a custom module and in the ".install" file, I create a table using hook_schema().

I have about 90 error codes that I have to associate with an error message.

What is the most effective way to populate my table with those values during module install?

Thank you!

As alternative of implementing hook_install(), if the module needs to be sure those data are present in the database before it runs, you can implement hook_enable(). The difference between those hooks is that hook_install() is executed once, when the module is installed; hook_enable() is executed all times the module is enabled, which happens also when the module is installed. Using hook_enable() requires you to first verify the data are not already present in the database before to write them.
Implementing hook_enable() is what the Forum module does to create the taxonomy vocabulary, and the taxonomy reference field it uses. (See forum_enable().)

Keep in mind that if you need to insert too much values in the database, then you should find another way to do it, as code taking too much time to be executed would cause a PHP timeout, and the code would not be complete the data insertion.
The alternative is using batch operations, or queue operations.


Get paths of all open webforms I have a project to QA all of our open webforms. We have about two screens (using the default pager) of open webforms.

The simple-but-hard way is to copy each link, but I wonder if there is an easier way. Can I programmatically pull up the path for all open webforms? Or is there a module?

I looked at building a view of webforms, but there was only an option to create a view of webform submissions, not of webforms themselves.

You can do it in a custom module using entity.query service

$query = $this->entityTypeManager()->getStorage('webform')->getQuery();
$webform_ids = $query->condition('status', 'open')->execute();

$webforms = Webform::loadMultiple($webform_ids);
$webform_urls = [];
foreach($webforms as $webform){
  $webform_urls[] = $webform->toUrl()->setAbsolute()->toString();
}

Here is a demo module that uses entity.query in a controller to output those path as links with title as the title of each webform.


Add html to registration page I have a registration form, and in the beginning of my registration page I want to show a title, subtitle and an image. A wireframe is like this:

As you can see there are checkboxes (select field) of my register form. But I would like to know how I can add the upper part to my page (Title, subtitle, logo).

What would be the best way to do this?

You have to override the theme you are using in Drupal.

There is a good overview of this here.


How to get Location as Tokens? I would like to use a node location values (for example location:country-name) as tokens.
Is it possible to use something like [node:location:country-name] ?

I think I found a solution for this is a patch to the Location module here.


Which hook for a warning message? Which Hook should I use to simply print a message if a configuration is not done yet?

The only idea i've got was hook_node_view, but maybe someone knows something better ?

Traditionally that's what hook_requirements() is for

  Check installation requirements and do status reporting.

Emphasis mine.

It's how modules declare that they are missing a required Javascript library, for example.

It hooks your module into the status report at /admin/reports/status.

Drupal doesn't have a mechanism for displaying messages in response to a requirement failure; so if you need to show something to the user, hook_node_view() makes as much sense as anything else IMO.

Actually that's not strictly true (I didn't read the docs properly)...hook_requirements() does already handle that in one way or another. From the docs relating to the 'runtime' phase:

  any requirement with a severity of REQUIREMENT_ERROR severity will result in a notice on the administration configuration page.

So if your users have access to the admin config page you can use this hook to automatically display them a message. But if the message needs to be on a different page, you'll have to take a different route with the advice in @FreeRadical's answer.