How to validate field in inline entity form referenced field I have created field "Referenced"  which is entity reference field of other content type. Also this field have inline entity form functionality means its giving two button "add new node" and "and existing node"

Once we clicked on "add new node", publication content type node form will open. i want to make field_author entity reference field inside the inline entity form

Inline entity form only makes the connection to some structure and displays it, it doesn't change it. In your case the Inline entity form is showing the Create node form of a certain type (you haven't mentioned which type is in your case), but you can't change the structure through the Inline entity form.

If you want to add a User reference field to that node type you have to go through Structure > Content types > [Your type] > Manage fields.

There you can add a new field (or use an existing one if it makes sense to your structure) of the type Reference > User.

Once you add that field when you go to created nodes that reference that node type through the Inline entity form, you will see the User reference field among the fields after clicking on "Add new node".


How to show a notification at a speicific page based on visitor's country? I need to notify (only notify) users ordering through my Drupal Commerce based website that we don't serve their country, if they are not from a specific country. How can I achieve this on the checkout page only?

I know smart IP module can help me determine the country per IP, how can I implement the notification at the checkout page, before user proceed with his order.

If you can sort out the Smart IP bid and you get the user's country then you can use Context and Context GeoIP.

Create a new Context where you can choose the countries you don't deliver as a condition and show block as a reaction. Your block might be a modal box informing your users.


Generate page for each json entry I'm new to Drupal.
I want to customize the search module in order to show results from an external JSON.
I was able to insert JSON data in the search page, but now I want to generate a page for each result. Something like blog posts.
I'm using the latest Drupal 6 Version.

Please give me some ideas how can I generate the pages for each Drupal result.

Anticipated thanks!

I've used Feeds JSONPath Parser module to parse a JSON feed and insert the objects as a specific content type (e.g. blog posts).

It works well but I'm unsure about your search results, you might just have to set the template to link to each of the content nodes by getting the node based on a specific field that you know will be unique for all of your nodes? e.g. title?

If you don't want to actually store the parsed data as content, and just want to display them as a page, then you'll need to use the hook_menu() function. I've linked to API 6 as you noted you were using D6.


Why am I seeing "Undefined index: und" when I'm using LANGUAGE_NONE? I've never seen this before, I'm getting an

  Undefined index: und in mymodule_page_alter...

on a line where I'm checking this

$node->field_override_ads[LANGUAGE_NONE][0]['value'] == 0

Is this a bug, or am I missing something?

if(count($node->field_override_ads) && $node->field_override_ads[LANGUAGE_NONE][0]['value'] == 0)

You need to check if a value even exists before checking the value. And I'd actually write it this way:

if(count($node->field_override_ads) && !$node->field_override_ads[LANGUAGE_NONE][0]['value'])


How add additional css classes to description field in webform component? I want to add additional CSS classes to webform component description field.

in default mode, this item is wrapped inside a div element with "description" class like below:

here is description text

Now I want to add extra CSS classes beside description.

How can I do this? via a module and form alter operation or via theme functions hook?

Please guide me.

you can do this by using jquery on ready do this something like
jQuery(document).ready(function() {
         jQuery('#YOUR_FORM_ID .description').addClass('new-desc-class');
});


Is there a way to run hook_form_alter after themes implementation? I'm using the material_admin theme, which has a hook_form_alter()  implementation.

I see that my module's hook_form_alter() is executed before the theme hook. Both hooks are editing the same form property, so the change done in my code is always overridden.

In my hook_module_implements_alter() implementation I see only the modules that implement hook_form_alter(). The theme's implementation is not there.

How can I control its execution?

I think you cannot have a module hook executed the same hook implemented by a theme. If we look at the hook invoking code, we see that the theme hooks are invoked separately and after the module hooks.

The best bet would be to remove it from the theme and put it in a module, or trying with #after_build.

FormBuilder.php contains the following code.

$this->moduleHandler->alter($hooks, $form, $form_state, $form_id);
$this->themeManager->alter($hooks, $form, $form_state, $form_id);


Adding fmath editor plugin to ckeditor through wysiwyg module How to add fmath editor plugin to ckeditor through wysiwyg module.
The link (http://www.fmath.info/plugins/drupal/doc.jsp) provides documentation for ckeditor module but it does not explains the steps for wysiwyg module.

This started out as hacking it in, but things are always nicer in a module. The code is on my Github but if you just want the module it is hosted here for the moment. Full install instructions are similar to your link above and are including in the README for the module.

Basically, if you have the Wysiwyg CKEditor module installed already, you'll need to:

Install fMath plugin:
Download the plugin for CKEditor from the fMath site
and unzip the package.
Copy the folder fmath_formula to sites/all/libraries/ckeditor/plugins folder
Install the fMath WYSIWIG module (linked above):

Download and add the module to Drupal and activate it.
Enable the fMath button in the WYSIWYG profiles page for the wanted formats (e.g. Full HTML).

Now, the button on toolbar should be displayed. When you click the editor, it should show up.
You will not be able to save the image to the page until you complete the next steps.
Install the server side script to generate the images:

Go to www.fmath.info/editor/ and download editorPhpServerSide-vx.x-x.zip
Unzip the file.
Create on your server a folder "capture", it must be available from www.yourserver/capture
Copy the file imageCapture.php to this folder, it must have the permission to execute.

Create a folder img in capture folder (capture/img).
Edit the file imageCapture.php and change www.yourserver.com with your server url

Edit the file sites/all/libraries/ckeditor/plugins/fmath_formula/dialogs/configMathMLEditor.xml
to add or edit the property "urlGenerateImage" to
http://yourserver/capture/imageCapture.php
Test

Clear the cache of your browser (temporary files).
Create an equation and save.


Customize admin toolbar Is it possible to make admin toolbar partially visible to newly created users in Drupal 8? For example, the user would be able to observe the Reports, but not be able to add new modules, so the 'Extend' entry is not visible to him?

Yes, as Neo mentioned, the toolbar utilizes menu permissions so it only displays items available to the user. So if the user has permissions for Use the administration toolbar & View site reports (or whatever permission needed for a sub-item in the admin menu), they will see only the report menu items.


403 error - unable to login into admin Recently I created two pages for http 403 and 404 and assigned them so that on error those two will be shown.
But today when I tried to login to my admin in my site: http://www.indiacustomercare.com/admin
it is giving error "Error 403 - Permission Denied".

The message:"Unfortunately the page you are looking for is not accessible by you." is from the page I had assigned for http 403.

Looks like I did some silly mistake, my other two D6 sites have no problem logging in.

How do I login into admin again?

this may seem a silly suggestion, but have you tried going to /user rather then /admin the former being the login page, the latter being the admin pages once logged in?


Rule check if field value changed give always true I need a rule that checks if the value of a field has been changed by a particular role.

I created a rule with event "After updating existing content".

I added two conditions :

user has role :

Parameter: User: [site:current-user], Roles: Web Team

NOT data comparison :

Parameter: Data to compare: [node:body], Data value: [node-unchanged:body]

What I expect is to see the rule fired when a user with role "Web Team" changed the value of the body field of a node.

I expect the rule NOT to be fired when a user with role "Web Team" edit and save a node without changing anything.

And I expect the rule NOT to be fired when a user with no "Web Team" role edit and save a node.

But everytime the user with role "Web Team" edit and save a node, regardless if he changes something or not, the rule is fired.

I tried to change the event in "Before saving content" with no more success.

The log displayed after the save is the following :

0 ms Reacting on event Before saving content.
12.599 ms Evaluating conditions of rule test2. [edit]
19.604 ms The condition user_has_role evaluated to TRUE [edit]
23.194 ms The condition data_is evaluated to FALSE [edit]
23.23 ms AND evaluated to TRUE.

How AND can be evaluated to TRUE if one of its conditions is evaluated to FALSE?

I did many tests but really don't see how to solve that.

I hove somebody could help me.

Here is the rule exported :

{ "rules_test2" : {
    "LABEL" : "test2",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "workflow_rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "5" : "5" } }
        }
      },
      { "NOT data_is" : { "data" : [ "node:body" ], "value" : [ "node-unchanged:body" ] } }
    ],
    "DO" : [
      { "workflow_rules_set_state" : {
          "node" : [ "node" ],
          "workflow_state" : { "value" : { "11" : "11" } },
          "workflow_comment" : "Title or body modified by webteam. The content should return to contributors for validation."
        }
      },
      { "drupal_message" : { "message" : "node-title = [node:title]\r\n\r\nnode-body = [node:body]\r\n\r\nnode-unchanged-title = [node-unchanged:title]\r\n\r\nnode-unchanged-body = [node-unchanged:body]\r\n" } }
    ]
  }
}

Best regards

You have to use :value for the body or other textarea fields.

The problem is there:

{ "NOT data_is" : { "data" : [ "node:body" ], "value" : [ "node-unchanged:body" ] } }

Should be:

{ "NOT data_is" : { "data" : [ "node:body:value" ], "value" : [ "node-unchanged:body:value" ] } }


Display view block in custom field View block need to display in custom field and need to pass nid as a argument for that view block. Help me on this.

Solution: we can use insert_view module to add view in CCK field.


Hide CCK fields for users without references with node I have a role "worker".
I have one content type "task" that can be viewed just by "workers".
"Task" has 3 fields:

field-A: a user reference field to select a "worker" user;
field-B: one textfield that can be view from any "worker";
field-C: one textfield that can be view just from "workers" related to the node using field-A.

How can I set permissions to let users view just the fields they are allowed to?
Content_permission just has a per role granularity, so I can't use it in a dynamic context and with many categories.
User Reference Access just set permission to the whole node.
I'm looking for something like Taxonomy Access, but with a per field granularity.

Have you checked the Field Permission module which allows site administrators to set field-level permissions to edit, view and create fields on any entity.


ubercart - many "in checkout" orders I have a problem that too many of the orders coming in don't get completed and remain in checkout. It appears as though it doesn't even try to send to paypal.

I don't think that the issue is that the form is failing validation because of 2 reasons:

wouldn't most of these people try to correct their info and submit again?
i have also javascript validation on the page.

This issue has been with me for quite some time, and I would LOVE to get rid of it...

In checkout is a stage when someone adds something to the cart but does not go through the checkout process. It has nothing to do with the way your site functions. Just the user didn't want to checkout.

This problem (most likely) is Shopping Cart Abandonment (Google it).

UC Followup is a module that helps users push through "Adondoned Carts".
http://www.drupalmodules.com/module/ubercart-followup


Nodes that point to panel pages I'm having an issue with deciding how to display nodes that in turn point to panel pages.

My site currently has a lot of panel pages that have static content. I have a view on my front page that displays nodes which in turn point to these panel pages. However, when a user clicks on a node link, they'll of course see the node in isolation.

In order for me to point users to the correct page, I've been using redirects. So if a user clicks on featured article on the home page,  a redirect pushes them to the panel page I've set up instead of just the node view.

Have I made this overly complicated? Is there a way to making this workflow a lot simpler?

@MPD was correct. I had neglected to use the node override panel page correctly. Thank you!


How do I change the name of the "view" node tab for a specific content type? I am using Drupal 8. I have a content type "hotel". I would like to change the default tab name "View" only for this content type "hotel". I can change the default tab name "View" by mymodule.links.task.yml (please see below code), but it applies to all content types.

entity.node.canonical:
  route_name: entity.node.canonical
  base_route: entity.node.canonical
  title: 'Summary'

So how do I change the default tab name "View" ONLY for a content type?

In your theme open file THEMENAME.theme, and the add code below:
function MYTHEME_preprocess_menu_local_task(&$variables) {
  if (isset($variables['element']['#link']['title']) && $variables['element']['#link']['title'] == 'View') {
    $node = \Drupal::request()->attributes->get('node');
    if ($node && $node->getType() == 'hotel') {
      $variables['link']['#title'] = t('Hotel View');
    }
  }
}

Clear all cache and see result.


Why is the Commerce product's price hidden in my view for Anonymous User? I have a very strange problem with the Views and Drupal Commerce. I would like a list of products and their prices, but in the view - and ONLY in the view, the price is hidden for anonymous users. I can see it when I am logged in, and if I go to the actual product page it is showing for all users, just not on the view!  STRANGE!  I've made sure that anonymous users can access the checkout, which they can.

I'm using

Drupal 7.54
Drupal Commerce 7x 1.13
Views 7x 3.14

The view is pulling in the price through fields

Content: Product
formatter: Rendered Product
View Mode: Content: Teaser (also tried Commerce Product: Content: Teaser)

If I add a relationship it looks fine when logged in but the whole view completely disappears when not logged in.

I've never run into this issue with views before and I've done quite a few e-commerce sites.  I assume that this is a permission problem somewhere, but I can't seem to find it and I'm feeling completely stupid for not being able to trouble shoot this.  Can anyone give me any hints?

A first possible solution is to give the "View any product of any type" permissions to anonymous. Here is a relevant screenprint about it:

Another solution is to disable SQL rewriting within the Advanced > SQL Settings section of the view. This can have security implications if your using contextual or exposed filters. So make sure that your filters or contextual filters (i.e. relationships) are properly limiting access.

For more info, refer to comment nr 5 or comment nr 6 of the issue about "Views results empty for unprivileged user when using Relationship: Content: Referenced Product"


How can I limit a list of node tokens to only a particular node type? We have many content types and fields, and the "Edit Node Type" page is taking about 30 seconds to load.  The culprit appears to be a module that lists all of the available "node" tokens, using this code:

$form['modulename']['token_help'] = array(
  '#theme' => 'token_tree',
  '#token_types' => array('node'),
);

'#token_types' => array('node') gives Node tokens for every content type, even though the form will only pertain to the one Content Type.

Is there a way to limit the token tree to display only node tokens pertaining to a specific content type (without using Token Tweaks module)?

I'll just answer this as a "No".  Token Tweaks is what I needed to use to prevent long page loads (30 seconds at times...)


Should I Unset PHP variables in Drupal? We all know php's variables(array, integer,string) would be taking large memory. So PHP recommend to unset the variables to optimize the memory.

Should I do that in Drupal too ? or Is Drupal internally handling such a things ?

No, Drupal is not doing anything to handle this; the very fact you're asking might suggest you're not totally sure how this works, as Drupal has no power over the efficiency of the code you write.

GC runs every time a function finishes, so unless you've identified an actual problem in one specific function, clearing up every single variable after you've used it, even though you theoretically can, would surely be considered premature optimisation.

Bottom line: Drupal cannot help you to write efficient code, you need to apply what you know from PHP. Whether you want or need to free the memory for every single variable manually depends on your requirements and specific code.

I would personally say you're over-thinking this a bit, as in an ideal world your functions should be small and modularised enough for this not to be an issue anyway. React to real problems, not perceived or potential ones, when it comes to optimisation.


How to change the behaviour of a module i often need to change/add new behaviours to existing modules, but i don't really know what is the correct way to do this.

For example i have installed the webform module. What i need to add is this:

on the list of submitted forms i need a button (create user) which creates a new user using some data of the submitted form.

What should i do?

Should i change the module code or is there a way i can inject this behavior by creating a new module?

I'd like the second option more than the first, are there some tutorials on how to do this?

Most of the time you will want to try to stay away from modifying the modules directly. This can be done, but it makes it more difficult to upgrade to future versions of the module.

A lot of modules allow for modification, and Drupal itself is designed for you to be able to modify things at many stages in the process of building a page. So if you can inject functionality it is best to do so.

This isn't always possible to do in which case you can either modify your local copy of the module. Or you can create an issue on the modules issue queue with a patch, which may get picked up in a future release of the module.

How to inject behavior is a very broad subject (I am sure specifics are already answered or can be asked on this site).

Most of the time you will want to create a module, and implement hooks which will allow you to modify things.


Where should I search uncompressed .css? I try to update styles on a Drupal site. But when I go to sites/default/files/css/ I find only set of gzipped .css files. Where should I search uncompressed files to edit them? Developer Tools shows path to gzipped files, naturally.

when I go to sites/default/files/css/ I find only set of gzipped .css files

You need to change your configuration.

Go to Configuration > Performance

and unchecked the aggregate and compress CSS files box, Save Configuration.

You then need to go to /sites/all/themes/YOURTHEMENAME/css folder and hopefully you should see .css files now. (Assuming you are using Drupal 7 and NOT using Drupal 8)

(might need to re-start FileZilla to seem them, assuming you are using FileZilla that is.)


Basic kernel test fails with Type of Drupal\KernelTests\Core\Entity\EntityKernelTestBase::$modules must be array Trying to port a Drupal 7 module to 9 with accompanying test and getting this error immediately when running it:
PHP Fatal error:  Type of Drupal\KernelTests\Core\Entity\EntityKernelTestBase::$modules must be array (as in class Drupal\KernelTests\KernelTestBase) in /var/www/html/docroot/core/tests/Drupal/KernelTests/Core/Entity/EntityKernelTestBase.php on line 12

The test:
class MyModuleTest extends EntityKernelTestBase {

  use NodeCreationTrait;

  /**
   * @var \Drupal\mymodule\Query\YearsQuery
   */
  protected $query;

  /**
   * @var array $modules
   */
  protected static $modules = [
    'node',
    'mymodule',
    'mymodule_test',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() : void {
    parent::setUp();
    ...

I checked around some of the core classes - the $modules declaration looks the same. Note that I am using PHPUnit 9.

From KernelTestBase:
 /**
  * Modules to enable.
  *
  * The test runner will merge the $modules lists from this class, the class
  * it extends, and so on up the class hierarchy. It is not necessary to
  * include modules in your list that a parent class has already declared.
  *
  * @see \Drupal\Tests\KernelTestBase::enableModules()
  * @see \Drupal\Tests\KernelTestBase::bootKernel()
  *
  * @var array
  */
 protected static $modules = [];

You'll need to match this declaration in your own code (though you can add to the array).


Synchronize two displays of a view? I have a view with several tiers of arguments, navigated like so:

Camp > Date > Photo Gallery

I need a way to display a block of all the tags associated with the given content. So when Camp is selected, I need to display the tags associated with content for that camp. When Date is selected, I need to display the tags associated with content for that date AND that camp.

I've tinkered with Panels, I've installed EVA, I tried Views Field, and I just can't figure out how to do this thing.

I got this working, and I didn't need Eva, Views Field, or Panels. I just needed good ol' fashioned Views.

I created a View with a Page and a Block.

Page displays images and takes contextual filters Term (of vocab Camp) and Date.
When the value is not in the URL, a summary is displayed.

Block displays Terms (of vocab Tags) and takes the same two contextual filters. When the filter value is not available, I choose Provide default value > Raw value from URL > and select relevant path component.

I set the block to display on all pages, but on pages that don't pass it recognized arguments it just doesn't appear because it's empty.

Voilá. So much simpler than I thought.


Can A View Load All Data, And Filter (Hide) With CSS? When using an exposed filter in a view, any data that doesn't meet the filter is removed from the page. Partially for SEO reasons, I'd like all the data to load (and stay in the HTML), but then the exposed filters will simply use CSS to hide the data that doesn't match the filter.

Does that make sense? Is it possible?

A module might be able to help you with this
https://drupal.org/project/mixitup_views (drupal 7 + 8)
Loads all items and might be close to what you need
https://www.drupal.org/project/isotope (drupal 7 + 8) A highly customizable module that is probably harder to implement as well
Some other alternative modules
https://www.drupal.org/project/views_semantic_tabs (drupal 8) might be a good fit
https://drupal.org/project/shuffle (drupal 8)
Not sure if it loads all results at once but it offers the filtering you described
https://drupal.org/project/views_quicksand (drupal 7)
does not load all results at once by has the filtering effect that you need so it might be a starting point
NOTE: all or almost all above module use JS libraries that you have to pay for if you implement them in commercial products
A custom alternative
Create a view that displays all results
and use global text area to rewrite all the elements to be part of a container div
and add classes to the container based on the categories you want filterable
Then use this code https://codepen.io/terf/post/jquery-filter-divs
in your custom module or theme changing box class with your container's class name


"Taxonomy with depth" view I have a taxonomy tree like this:

balls

basketball

color

red
green

volleyball

color

red
green

If a Taxonomy term has children, I want to show them; if there aren't children I want to show the nodes associated with the taxonomy term.

My view settings are the following.

This is similar to Show all child nodes of a taxonomy term D7, but I cant get it to work.

I use Content: Has taxonomy terms (with depth), and I set the depth to 1. It doesn't work as expected.

You need Taxonomy Menu Trails module if you have a nested menu tree with taxonomy terms.
Try this: https://drupal.org/project/taxonomy_menu_trails


Export content in features using UUID features I read the UUID feature description and it says it is used to export content in feature. I installed the module but did not know how to export the content.

The uuid module has been reworked, and, as of 2012.05.25, uuid_features has not been updated to address those changes (though there is a patch RTBC).

In the meantime, to export nodes using uuid_features in Drupal 7:

Install features version 7.x-1.0-rc2.
Install uuid version 7.x-1.0-alpha1. (Not the latest version.)
Install uuid_features version 7.x-1.0-alpha1.
Enable the features module, the uuid module, the uuid_node module, and the uuid_features module
Go to Configuration > System > Universally unique identifiers, and click the "Create missing UUIDs" button
Go to Structure > Features > Create feature, and from the "Edit components" dropdown, select "Content: uuid_node", then pick the nodes you'd like to export into your Feature


How to sign emails to setup DKIM and DMARC After setting up my Drupal 8 site in the server, I noticed that none of the emails go to the inbox in Gmail and it all gets stored in Spam. Upon further investigation I found that this is because the emails are being sent via the PHP Mailer and its not being signed and authenticated.

I'm not that familiar with Drupal programming, therefore any suggestions and instructions on how I can get this configured via code/modules etc would be greatly appreciated.

Please check out the following two modules to have your Drupal mails send by a mailserver. Apart from that it may already be sufficient to just set a SPF record for your domain as DKIM and DMARC has actually nothing to do with Drupal.

PHPMailer

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

  Adds SMTP support for sending e-mails using the PHPMailer library.
  Comes with detailed configuration instructions for how to use Google
  Mail as mail server.

SMTP Authentication Support

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

  This module allows Drupal to bypass the PHP mail() function and send
  email directly to an SMTP server. The module supports SMTP
  authentication and can even connect to servers using SSL if supported
  by PHP.

How To use an SPF Record to Prevent Spoofing & Improve E-mail Reliability

https://www.digitalocean.com/community/tutorials/how-to-use-an-spf-record-to-prevent-spoofing-improve-e-mail-reliability

  A carefully tailored SPF record will reduce the likelihood of your
  domain name getting fraudulently spoofed and keep your messages from
  getting flagged as spam before they reach your recipients.


User Reference For a Particular role I am using Drupal 7 . and in a content type i created a field with user_reference,  which is working fine.

And while creating a content it shows all users.

Now i want to show  only User with particular role..

Does anybody tell me how to do this. Is there is any module avialable for this

I would use the Entity Reference module (rather than user reference). I would then create a view (display: entity reference) filtering only Users with that desired role.

In the field settings you can choose the designated View under "Entity Selection" - "Mode": "Views: Filter by an entity reference".

This is at least how I solved this problem in the past. I hope this helps.


How to find which block is causing PHP errors? I'm cleaning up a Drupal 7 site and currently its spitting out a bunch of PHP syntax errors pointing to some block that is causing it. It doesn't say which block but only says php_eval() error. So I'm assuming its in a block somewhere.

How would one find the culprit of which block it is that is causing this php error?

http://i.imgur.com/KJk1jr4.png

The most probable cause of the error is a missing or a mismatched parenthesis in the PHP code you are using in your custom blocks or functions. To solve the missing parenthesis error in PHP blocks or in other areas, the code has to be checked from the beginning to search for it. But it's really hard to check all PHP code. One way to avoid errors is to use proper indentation in the code. Once all the parentheses in the code have been set correctly, parse error: syntax error, unexpected $end will be fixed.

What causes this error?

In fact, this error means that PHP has finished analyzing your code, but you forgot to close a symbol somewhere in your page or in those that were included. There could be a number of causes:

This issue could happen when someone used <? instead of <?php somewhere, but your server's php.ini disables short open tags. Check this line in your php.ini - "short_open_tag = On".
You forgot to close a quote, so PHP is continuing to analyze your code until it finds the closing quotation mark.
You forgot to close a bracket, so from the last opening, PHP considers all the code that follows as part of a block that never ends.
You forgot to close a parenthesis, so from the last open parenthesis, PHP considers all the code that follows as part of a specific block (condition, arguments of functions etc) that does not end.
You forgot a comma, so for PHP there is an instruction in your code that has no end.

NOTE: This means that the problem may not be on the line mentioned in the error message, as the missing symbol could be anywhere after that point.


Can't attach #ajax to altered form displayed in block I have a module that displays an existing signup form in a block.

function my_contact_block_view($delta = '') {
    switch ($delta) {

        // Newsletter signup block
        case 'newsletter_signup':
            $block = my_contact_get_emma_block();
            break;
    }
    return $block;
}

I make some minor alterations to the form. Some markup elements are removed from the form (this works), and I am attaching an #ajax property to the submit element (this doesn't seem to work):

function my_contact_get_emma_block(){
    $form = drupal_get_form('my_contact_emma_form');

    // get wrapping markup
    $header = variable_get('my_contact_emma_block_header', '');
    $footer = variable_get('my_contact_emma_block_footer', '');

    // unset some stuff
    unset($form['heading']);
    unset($form['copy']);
    unset($form['required_blurb']);
    unset($form['privacy_blurb']);

    // alter some stuff
    $form['fname']['#attributes']['placeholder'] = t('First');
    $form['lname']['#attributes']['placeholder'] = t('Last');
    $form['email']['#attributes']['placeholder'] = t('Email');

    // config to submit via ajax
    $form['submit']['#ajax'] = array(
    'callback' => 'my_contact_emma_form_ajax_submit',
    'wrapper' => 'brd-contact-emma-form',
    'method' => 'replace',
    'effect' => 'fade',
    );

    // render the form
    $form = drupal_render($form);
    $markup = $header . $form . $footer;

    // return renderable array for block
    return array(
        'subject' => t('Event Email Sign-Up?'),
        'content' => array(
            '#type' => 'markup',
            '#markup' => $markup,
        ),
    );
}

Unfortunately, it never hits my ajax submit function.  Instead the page submits to the normal submit routine (my_contact_emma_form_submit).

/**
 * Ajax callback function. (Never called)
 */
function my_contact_emma_form_ajax_submit($form, $form_state) {
  // Dummy/dumb validation for demo purpose.
  if (!empty($form_state['input']['email'])) {
    return 'Subscribed !';
  }
  else {
    return $form;
  }
}

What am I doing wrong?

drupal_get_form will return a builded form/ rendered form. i.e Your form has been already prepared based on the specification done in the form callback, like its finalized.

So making changes to the return values of drupal_get_form wont work.

If you want to alter any of the form then you should use any of the following hook

hook_form_alter
hook_form_FORM_ID_alter


Use the same login credentials with different core versions I have a Drupal 7 site, and I createda  new Drupal 8 site. I would like to use the login credential from the Drupal 7 site in the Drupal 8 site.

How can I achieve this?

You could set up the existing Drupal 7 site as an OAuth provider and then set up the Drupal 8 site to allow for OAuth logins and then you could share credentials between the sites.

You won't get any sync for free but at least you wouldn't have to enter the password again.


How to extract query placeholders for debug purposes? When I cast query to string, I can see WHERE that will be passed to the database, like this:

WHERE  (idProperty = :db_condition_placeholder_0)
  AND  (idCategory = :db_condition_placeholder_1)

But how can I extract these placeholders?

This can be done using arguments:

echo (string)$query;
var_dump($query->arguments());

This simple code will give you both query and arguments, for simple debugging.


Achieve single node field edit to have different values for each user? I am trying to create lets say and activity node which allow each user to insert a different value without having to create a node. for example:

I created activity1 node, and then I will allow user a to edit activity1 and insert value "a", and user b can also edit activity1 and insert value "b", and both can see their own activity1(the same node) but with different values for each user.

is this achieveable? as I tried using uniquefields module and that is the one I want for this case.

look forward for some response!

thank you

As you described it, it is not possible with core Drupal's field system. While you can create a node editable by many users with a multivalue field, the field (and its values) do not have property of ownership. Thus, your requirement to see different values for different users would not work.

There are alternative ways to achieve this. One path is to add 2 fields to the user profile.

Activity: an entity reference to your activity node.
Value: the user's field value you want to capture.

If the values are inherent single property of a user, you can add them directly to the user profile and use a Field Group to present it as combination of fields for the user to enter.

If the user can have many different Activity & Value combinations, you could use either use something like Field Collection or ECK/Inline Entity Form to present an embedded form in the user profile where users can add many different Activity/Value combinations.


Scalable way to add custom css/js to a page So I'm working on a site where the ability to add custom javascript is core to the site's functionality. Right now, I'm using the Code Per Node module to handle this, but I have a feeling it's going to be a bit unwieldy when I'm dealing with 20 or 30 pages with custom javascript. Also, I'd love to have a way to keep the js in source control, not the database.

In my mind, the idea solution would be able to either upload or reference an existing javascript file to be loaded in a script block at the bottom of the page. Or, alternatively, pay close attention to how I'm calling things on the DOM and just have all of javascript files minified into one that would be called by my theme's .info file.

Is there a better alternate approach to this problem?

I had a theme, called bikeswitzerland. There I had a file template.php, where I added the following code:

function bikeswitzerland_preprocess_page($vars)
{
       $nid = array_keys($vars["page"]["content"]["system_main"]["nodes"]);
       $nid = $nid[0];

       $alias = drupal_get_path_alias("node/" . $nid);
       $theme_path = drupal_get_path('theme', 'bikeswitzerland');

       switch($alias)
       {
       case 'ask-us':
              drupal_add_css($theme_path . "/css/ask_us.css");
              break;
       };
}

Use preprocess_page hook in your theme. Upload your css files into a dir and create a table in the database, that stores the mapping between the page aliases/urls and appropriate css files.

Then inside the function check, what is the current page url and attach the appropriate css, like I did. And you'll solve your problem.


Why this message "You are not authorized to access this page." coming on user edit page? I am facing a strange behavior today, when I signup via Facebook or twitter and then go to user edit page it show this message:

  You are not authorized to access this page.

Even if try to access this page from admin login the same error is coming.
But if in signup via email then everything working fine.

I am using these modules as well LoginToboggan, HybridAuth Social Login.

Ohhhhh,
At last i figured it out. when i signup via Facebook or Twitter , user's language does not save and when i access the user edit page it gives error that you are authorized to access this page,
and now i write my own function which set the default language for user and everything working like charm !!! thanks


How do I speed up `drush test-run` (compared to the SimpleTest UI)? I have a number of Feature modules for which I've written tests to assure they work as expected. For performance reasons, I've overridden the parent's setUp() method in each test case so that it doesn't create a brand new database each time.

When I run my tests in the SimpleTest admin UI, all of my Feature modules' tests take about 15-20 seconds total to complete. When I run them via drush test-run [feature-group-name], they take about 75 seconds total. I noticed that drush seems to pause in between test cases to output something like the following:

Contact page 7 passes, 0 fails, and 0 exceptions  [ok]
No leftover tables to remove.                     [status]
No temporary directories to remove.               [status]
Removed 1 test result.                            [status]
 Group  Class  Name

If you're curious, my setUp() function looks like this:

public function setUp() {
  $this->setup = TRUE;
  // Prevent PHP warnings about a missing public_files_directory variable:
  $this->public_files_directory = variable_get('file_public_path');
}

Any ideas why drush is so much slower than the admin UI? I'd really like to get drush more performant, as I want to integrate these tests into a continuous integration environment.

Thanks!

Consider using "php scripts/run-tests.sh" instead of "drush run-test". The former supports parallel test execution which improves runtime (as long as you have multiple test-classes). Compare:

$ php scripts/run-tests.sh --url http://d45.l User
...
Test run duration: 11 min 45 sec
$ php scripts/run-tests.sh --url http://d45.l --concurrency 3 User
...
Test run duration: 4 min 13 sec
$ php scripts/run-tests.sh --url http://d45.l --concurrency 6 User
...
Test run duration: 3 min 7 sec


Access denied at password reset page when logging in I run a D7 site that for some reason is not allowing users to reset their passwords, but only on the server. The email with the one-time login link is sent just fine, but when the user clicks on the link, they get a 403 page with the generic "You are not authorized to access this page" message. I know this must be server environment specific, because with a clone of the site on my local machine (sending the email using the SMTP module), it works just fine. I'm guessing the issue happens in user_edit_access(), where it is comparing the value of $account->uid with $GLOBALS['user']->uid, but that's just a guess at this point.

Any suggestions as to what the problem could be? The servers are using Varnish, so that's one thought that came to mind, but I'm not sure how to figure that out.

Thanks.

Comment out the /* $cookie_domain = $_SERVER['HTTP_HOST']; */ from settings.php from the path \sites\defaults will work for you.

or else use the below code in settings.php:

<?php
/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on its full domain name. If you have multiple domains pointing at the
 * same Drupal site, you can either redirect them all to a single domain (see
 * comment in .htaccess), or uncomment the line below and specify their shared
 * base domain. Doing so assures that users remain logged in as they cross
 * between your various domains. Make sure to always start the $cookie_domain
 * with a leading dot, as per RFC 2109.
 */
$cookie_domain = '.your_domain.com';
$conf['https'] = TRUE;
?>

On sites with anonymous users, it is handy not to set this so that you login as admin on one tab and anonymous on another by not using "www" on one of them.

source


How can I copy a body field from one node to another node? I'm trying to write a small module that copies the body content from one node to another node. The module does almost what it should and everything arrives so far. However, I have to open the node to be copied once, then save it and then open it again. Then it has taken over everything correctly. But I would like to have the field already copied when I open the node. Since this is my beginnings in module development, I would of course appreciate any tips. I am also sure that this can be done more elegantly.
/**
 * Implements hook_form_alter().
 */
function copy_fields_from_model_contract_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $nid = 6766;
  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $node = $node_storage->load($nid);
  if ($nid == '6766') {
    $getcontract = $node->field_vertragsinhalt->value;
  }

  $nid = 6716;
  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $node = $node_storage->load($nid);
  if ($nid == '6716') {
    if ($form_id == 'node_buch_anlegen_edit_form') {
      $node->field_vertragsinhalt->value = $getcontract;
      $node->body->format = 'full_html';
      $node->save();
      dpm("Testsetest");
    }
  }
}

Use hook_ENTITY_TYPE_prepare_form if you want to change a field value before the form is built for an existing node:
<?php

use Drupal\node\NodeInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_ENTITY_TYPE_prepare_form() for node entities.
 */
function mymodule_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state) {
  if ($operation == 'edit') {
    if ($node->id() == '6716') {
      $node->field_vertragsinhalt->value = $getcontract;
      $node->body->format = 'full_html';
      // don't save the node yet, it will be saved after submitting
    }
  }
}

For the more common case of setting field values when creating new nodes see Pre-populate an entity reference field (media image) when creating a node


View output that goes from list to three-column grid? I'm working on a news site, which has a front page generated via Views.

Originally I was told it was just a straight list of stories, so I used the unformatted list display type, using on of the fields ("section") to group rows. Now, however, I'm being told it'd be nice to have the first ten stories display as an unformatted list, then have the next ten display in some sort of three-column configuration (similar to the "grid" display type).

Any idea how I'd do that? Thanks!

I am thinking to create two views. And add them one above the other in a panel. The first view has 10 items in an unformatted list then the next ten would have a grid display of the same content but with an offset of 10.


Have can I have a view grouped by nested hierarchy? I have a nested taxonomy as follows:

Some forms will only have the taxonomy of "Basic Forms", some will have taxonomy of "overtime forms", etc.
So I want my Forms view to look like this example:

How can I get my view to recognize my nested taxonomy?

EDIT TO ADD:
I have made some progress and what I have is repeating the parent taxonomy:

Forms_IT is the parent term-I'd like to start at the next one but can't seem to figure that part out either.

General & Quincy are on the same level.  OT Approval is a subcategory to General but it is not appearing as such and it is repeating the parent and child taxonomy when it lists out the nodes.

This is how I want it:

Any ideas on this?  Is it simply a sorting issue?

7/25 - Edited again to add a pic of my setup and group by.

Create a list of all nodes that you want in your Views,
add the field for their taxonomy terms to show where they belong,
add the Parent relatinship for your taxonomy reference field to your Views. You may need to first add the relationship to the taxonomy reference field first, to get the Parent one to show as an option, in which case you'll en up with two relationships, the second one set to use the first one.
Add the Taxonomy Name field and set it to use the Parent Relationship. This field will show the parent term of the one the node is tagged with
Under Format use the "Group by field" option and set the first one to the Parent Field, and the second "Group by field" to the (sub-term) regular taxonomy field.

This should get you fairly close, I can't predict OTOMH where the nodes that have been tagged with only the parent taxonomy.


Multilingual content Migration I have Multi-Language website, I need this website to migrate new Drupal website.

I can use node export module for export the content; however, I have a multi-language site, how should I handle those translation nodes ?

It is much easier to create an xml view of your content in each language and import it with feeds module and xpath. Or if it is easier for you, you can export to csv with views data export and import to your new drupal with feeds csv parser. It is much easier and more reliable as you have total control of your content. Though be careful with the delimiters if using csv. XML is safer.


Create Content Type with a Default Title How would for the Title of something to be default, static, unchanageable?

I've got a content type (plus others planned) that I plan on using as a data submittal for stuff similar to a "Quote of the Day" or "Create an Event for the Calendar" type content. I plan on keeping these "nodes" hidden for the most part and using views to view, edit, add, delete. The title will be mostly wasted space and unneeded.

How Can I do a Default, unchangeable Title for "Create" screen? Or... change a title for a content type to a different field type (Say... Date Field)?

The Automatic Nodetitles module can do what you're looking for. When used in conjunction with the Token module, you have lots of options.


Can hook_field_extra_fields be used with field collections? I have a field collection view that I have to manipulate some data on before it gets displayed, so I was going to use hook_field_extra_fields with the extrafield_views_integration module.  This worked great for me on nodes, but I'm not seeing the extra field get displayed on field collections.  Is there any way to get around this?

function my_module_field_extra_fields() {
  $extra['field_collection']['my_field_collection']['display'] = array(
    'some_extra_field' => array(
      'label' => 'TESTING FIELD 123',
      'description' => 'This is a test of hook_field_extra_fields on FCs',
      'weight' => 100
    ),
  );

  return $extra;
}

The entity name for a Field Collection is actually field_collection_item and not field_collection (if you run var_dump(entity_get_info()) you'll see this).

This means your implementation should actually look as follows:

/**
 *  Implementation of hook_fields_extra_fields().
 */
function my_module_field_extra_fields() {
  $extra = array();

  $extra['field_collection_item']['my_field_collection']['display'] = array(
    'some_extra_field' => array(
      'label' => t('TESTING FIELD 123'),
      'description' => t('This is a test of hook_field_extra_fields on FCs'),
      'weight' => 100,
    ),
  );

  return $extra;
}

Also, dont forget your t()'s ;-)


How to use CiviCRM contact data latitude and longitude in drupal gmap formatted view Environment
Drupal 7.67
civicrm 7.x-5.13.4
GMap Module 7.x-2.11
Location 7.x-3.7
Views 7.x-3.23

What is working
I have CiviCRM contact data for organisations which has been successfully geocoded using google
I have view in Drupal that can access and display this contact data in a table including company names and latitude and longitude
I can display a google map in the contact record in CiviCRM, so I know the Lat & Long is correct

Problem
When I change from a table to a gmap format in the view no map is displayed,

View setup

  Format Format:GMap | Settings Show:Fields | Settings open Add Fields
  CiviCRM Website: Website URL (Website) CiviCRM Contacts: Contact ID
  CiviCRM Contacts: Organization Name (Retailer) CiviCRM Address: Full
  Street Address (Address) CiviCRM Address: Postal Code (Postcode)
  CiviCRM Phone Details: Phone (Phone) CiviCRM Tags: Name (Name) CiviCRM
  Custom: Organisation Fields: LALG Member Benefits (LALG Member
  Benefits) CiviCRM Address: Latitude (Latitude) CiviCRM Address:
  Longitude (Longitude)

GMap format settings

  Grouping field Nr.1

  You may optionally specify a field by which to group the records.
  Leave blank to not group. Macro [gmap ] Enter a macro. If left
  unchanged, it takes the default settings from
  /admin/config/services/gmap. See the documentation on GMap macros.
  Data Source

  Latitude field -> Latitude

  Format must be degrees decimal. Longitude field -> Longitude

  Format must be degrees decimal. Marker handling

I am also log messages when executing the view:

  php   Fri 7 Jun - 10:43am Notice: Array to string conversion in strtr()
  (line...  gjw
  php   Fri 7 Jun - 10:43am Notice: Array to string conversion in strtr()
  (line...  gjw
  php   Fri 7 Jun - 10:43am Notice: Array to string conversion in strtr()
  line...   gjw
  php   Fri 7 Jun -> 10:43am Notice: Array to string conversion in strtr()
  (line...  gjw

Details

  Type  php Date    Friday, 7 June 2019 - 10:43am User  gjw
  Location https://ref.lalg.org.uk/admin/structure/views/view/retailers/edit/retailers?destination=retailers
  Referrer  https://ref.lalg.org.uk/retailers Message   Notice: Array to
  string conversion in strtr() (line 1835 of
  /var/sites/r/ref.lalg.org.uk/public_html/includes/bootstrap.inc).
  Severity  notice

There is a good recipe for using leafhttps://civicrm.stackexchange.com/questions/12862/how-to-put-your-civicrm-contacts-on-a-leafleft-map-in-5min if you are happy to slightly switch track. For D7

Also you will get more Civi eyeballs if you post on that channel, and while I appreciate this is a 'drupal' question, more civi folk use drupal than drupal folk use civi ;-). Good luck


How can I add Zurb Foundation as a library? I'm trying to add Zurb Foundation framework to my theme library file. However, when I add the following code to my library, I'm not getting any result.

I would be grateful to hear what is the problem with the code and what is the right way to load a library?

This is my theme folder structure (Zurb Foundation folder location):

|-Theme Name
|  |-includes
|  |  |-foundation
|  |  |  |-css
|  |  |  |-js

Library file:

foundation:
  version: 6.x
  css:
    includes/foundation/css/app.css: {}
    includes/foundation/css/foundation.css: {}
    includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/what-input.js: {}

You created the library, alright, but you need to call the library.

In [theme_name].info.yml add the following:

libraries:
  - '[theme_name]/foundation'

Also you need to modify your [theme_name].libraries.yml file and add dependencies:

foundation:
  version: 6.x
  css:
    base:
      includes/foundation/css/app.css: {}
      includes/foundation/css/foundation.css: {}
      includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/what-input.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

As per Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme


Rules with VBO in views I have a view (using the table display format) that is showing all the node of a content type (A), and that content type has a reference to nodes of another content type (B). I added a VBO field to that view.

How can I create a content type B node for each node of the selected node (content type A) by setting the values just one time in the content type B create form?
(I need to create B nodes with the same field values for each node of A.)

The best way to get started is to watch the video series Learn the Rules Framework.  It will demonstrate how to create the node and populate any data fields according to the content in your type A node.


Where should I store 3rd Party external js libraries? This is a follow up to Define JavaScript library in Drupal 8

I have a third party library that I don't want to bundle with a module. In Drupal 7 I could just ask the user to extract to sites/all/libraries what is the best practice in Drupal 8?

One option is to do it exactly like in D7. Put it in /libraries or /sites/all/libraries and use the libraries module to detect the location.

location.module itself unfortunately doesn't work that well in 8.x yet, so you have to define an 8.x-1.x library and then use the libraries API to get the location and dynamically alter. Or I guess you could also do that part yourself.

I'm doing that in the JW Player project, see jw_player_libraries_info() + jw_player_library_info_alter(). It unfortunately still requires a bit of code, maybe that will improve in the future when libraries.module works better in 8.x.


Upload an Image via a Link When I create a new article in Drupal 7, there's a field to upload an image that will be associated with the article.  That image can only be uploaded directly from my computer.  Is there a way to make it so that Image fields will accept a link instead of a direct file upload?

Thanks!

Checkout FileField Sources for this problem. It lets you use remote file transer.


Commerce Invoice Entity Print Styling I am using Commerce Invoice and Entity Print to generate .pdf-files of invoices. In Entity Print settings, I set the paper size to A4 and selected TCPDF as printing engine.
Then, I customized commerce-invoice.html.twig to my needs, which works fine.
But I cannot get rid of the two black borders that seperate the document header and footer I think.

Would be nice if anyone could give me a hint where these come from. I alread also tried to override entity-print.html.twig and remove the styles from there. Also I unchecked the checkbox in the entity-print settings.
But these borders still appear on every .pdf-generation.
Thank you very much in advance!

What I found out is:
Every available printing engine has it's own requirements for the HTML-structure of the generatred invoice.
TCPDF needs a header and footer-tag inside the document. If you dont provide this elements, TCPDF will render them empty, but will in fact attach an hr-tag after the empty header and before the empty footer.
I switched to DOMpdf as printing engine, which also offers the possibility to define a page header and footer, but ignores them when empty and doesn't render any additional HTLM by default.
pro: DOMpdf supports more CSS rules and makes it easier to style the invoice with CSS
con: DOMpdf takes some seconds to render/print the document from the HTML, while TCPDF is very fast.


When exporting a Feature, how can I turn off all page cache related settings? I’m trying to export a Feature that would be used in a typical development environment. I want to have anything related to page caching turned off. But on the create feature page I’m not seeing where to do this. I would have thought there would be a Strongarm variable that reads Cache pages for anonymous users but there isn’t one. Also looking for the same for ‘Aggregate and compress CSS files’ and ‘Aggregate JavaScript files’.

So to clarify, how can I export the following in a Feature?

Cache pages for anonymous users -> OFF

Aggregate and compress CSS files -> OFF

Aggregate JavaScript files -> OFF

The variables are named:

cache - Cache pages for anonymous users
preprocess_css - Aggregate and compress CSS files.
preprocess_js - Aggregate JavaScript files.


How can I access the main menu in template_preprocess_page? I would like to assign the main menu of my site to a variable using template_preprocess_page() so that I can just use something like {{main_menu}} in the page template. Any ideas on how I would go about doing this, without having to assign the Menu to a Region?

Remember your menu can be a block, and to render it, you just have to load and get its view in a preprocess function.

THEME.theme file

use Drupal\block\Entity\Block;
function THEME_preprocess_page(&$variables) {
  $menu = Block::load('id_main_menu');
  $variables['main_menu'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($menu);
}

page.html.twig

...
{{main_menu}}
...

Attention
You must create your block 'main_menu' in somewhere, (module install, block structure page...)


Use taxonomy_get_term_by_name when there are duplicate names across multiple taxonomy categories UPDATE: I see that most likely the best way to accomplish this is to grab the term id from $content['field_tags']. However I'm not sure how to do that.
Whenever I retrieve $content['field_tags'][value] all that gets returned is an array object. And when I attempt to render it all I get is the tag name.

I'm attempting to grab the taxonomy term id in the node template for a content type. I'm grabbing the taxonomy term by referencing the field that contains the taxonomy terms. Like so

$tag = render($content['field_tags'][$i]);

I then use taxonomy_get_term_by_name in order to grab the id for that term like so.

$term_array = taxonomy_get_term_by_name(render($content['field_tags'][$j]));
$term = reset($term_array);
$term_id = $term->tid;

It works like a charm except for one issue. I have a taxonomy category for tags as well as events, and when there is a term with the same name in both the 'event' and 'tags' category it grabs the event term id instead of from the 'tags' category, which I want.

Is there another way to grab the specific term id for the tag field? Would it be possible to grab the term id directly from this object?

$content['field_tags'][$j]

Yes, you should pull the term ID directly from the field value rather than first rendering it to a term name, then trying to look up the term based on the name.


Pass data to hook_preprocess_html from custom module I'm trying to create a custom Drupal 7 module where it renders a custom page template. I want the data on /animals and /animals/getanimal to be in a custom HTML template.

After much searching and few successes, I've found that hook_preprocess_html works and that I can stop Drupal from loading the default template, but I'm struggling to pass data to my templates from the menu hook.

Is there a way to pass data from the menu hook to hook_preprocess_html, or is there another way where I can load my own custom template from the URLs in my custom module?

/**
 * Implements hook_menu()
 * @return mixed
 */
function animal_farm_menu() {

  $items['animals'] = array(
    'title'           => 'Discover animals',
    'page callback'   => 'getDiscover',
    'page arguments'  => array(),
    'access callback' => TRUE,
    'type'            => MENU_NORMAL_ITEM,
    'menu_name'       => 'main-menu',
  );

  $items['animals/getanimal'] = array(
    'title'           => 'all animals',
    'page callback'   => 'getAnimal',
    'page arguments'  => array(),
    'access callback' => TRUE,
    'type'            => MENU_NORMAL_ITEM,
    'menu_name'       => 'main-menu',
  );

  return $items;
}

function getDiscover()
{
  $result = ['cat','dog','monkey','cow'];
  return $result;
}

function getAnimal()
{
  $result = ['cat','dog','monkey','cow'];
  return $result;
}

/**
 * Implements hook_preprocess_html().
 */
function animal_farm_preprocess_html(&$vars) {

  $node = menu_get_object();

  $path = current_path();

  // echo $path;

  // Add a new theme suggestion when viewing node's of mynodetype.
  if ($path == 'animals') {
    $vars['theme_hook_suggestions'][] = 'html__mynodetype';
    $vars['data'] = [1,2,4,'monkey'];
  }

  if ($path == 'animals/getanimal') {
    $vars['theme_hook_suggestions'][] = 'animal_farm_discover';
    $vars['data'] = [1,2,4,'monkey'];
  }

}

/**
 * Implements hook_theme().
 */
function animal_farm_theme($existing, $type, $theme, $path) {
  $theme = array();

  //Add our templates/html--mynodetype.tpl.php to the theme registry
  $theme['html__mynodetype'] = array(
    'template' => 'html--mynodetype',
    'path' => drupal_get_path('module', 'animal_farm') . '/templates',
  );
  return $theme;
}

D7's html.tpl.php doesn't contain menu in $vars, as it's supposed to represent the template that contains the high-level HTML document. This data is in page.tpl.php via $main_menu / $secondary_menu vars.

If you need menu data in hook_preprocess_html() you can do something like call menu_tree_all_data('main-menu') in your code which will retrieve the menu data for main-menu.


SMTP server per role Mails must be sent to certain roles from certain domains.
Is it possible to setup SMTP server per role? (through rules or by coding)

MTA's can usually handle complex routing, such as handling multiple domains. Your specific rub will be the connection and routing to the MTA with the appropriate credentials to send the email.

You will need to setup a custom SMTP table where each role can setup their details, then within rules (or a custom module) create the logic to connect to the MTA with the appropriate credentials.

I hope this helps, or at least provides a gateway to an exact answer.


How to change "Description" in File field to drop down instead of text field? What is the best way to modify the File field so the "Description" field is a select box instead of a text field. I.e. I want to go from:

To this:

I tried a quick experiment, editing the File modules file.field.inc file, which resulted in the screenshots above, but if I can avoid forking the File module and instead do it some other way it would be great.

You can use hook_field_widget_form_alter() to add your own #process callback to the element.

In the callback you can just change the description field from a textfield to a select.


Where do I add a new cache context for an entity? I have not been able to get adding a cache context to work for entities in drupal 8.  Specifically I'm going for headers:User-Agent. I tried many variations on the following in a module.

 use Drupal\node\NodeInterface;
 use Drupal\Core\Entity\EntityInterface;
 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;

 function hook_entity_view_alter(&$build, EntityInterface $entity, EntityViewDisplayInterface $display){
   if($entity->getType() == 'relevant_type'){
    $build['#cache']['contexts'][] = 'headers:User-Agent';
   }

 }

I'm trying to get node access to be checked when that context changes. I have also tried it in the hook_entity_build_defaults_alter() function.

You should indeed use hook_entity_build_defaults_alter(). Its documentation even explicitly states this:

  Alter entity renderable values before cache checking in drupal_render().

  The values in the #cache key of the renderable array are used to determine if a cache entry exists for the entity's rendered output. Ideally only values that pertain to caching should be altered in this hook.

It probably didn't work for you because you forgot to clear the render cache after implementing that hook.

That hook is invoked in https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityViewBuilder.php/class/EntityViewBuilder/8

Also see https://www.drupal.org/developing/api/8/cache/contexts for an overview of cache contexts (what they are, how to use them, which ones core ships with).


How do I write automated tests? I saw that Drupal 7 includes some kind of testing framework (I haven't tried it out yet since my existing sites are still in Drupal 6 and likely won't migrate any time soon). How can you write automated testing for a Drupal 6 site, is there a module for this? How much can actually be tested automatically rather than requiring manual testing?

http://drupal.org/project/simpletest - it provides essentially the same testing API as the core D7 module and you still have to write the tests yourself. There is also http://drupal.org/project/simpletest_automator that apparently will help you 'record' your actions on a site into a SimpleTest for you.

Additional helpful links:

http://drupal.org/project/selenium
http://drupal.org/simpletest


Commerce orders view for user and his subusers The task is to create a view which will contain all orders of user and his subusers. I use the Commerce Kickstart and Subuser module. I have default view called "My orders" which prints all orders of the logged in user.  I don't know, how to integrate the subuser relationship properly. How can I do it?

Added: this is the sample. it works only for one user. I need it to be worked for user and his subusers

The result should be the following: the one table like at the screenshot but with different (specified) users - the current user and his subusers...

Orders are entities. Views 3 on Drupal 7 fully supports entities.

Sub Users are entities as well, with the Relation module connecting the users.

The relationships that exist are deep and abstract to Views and, while it may be possible to do this with SQL, the resulting view would be very complex and inelegant.

So your question is more about how to construct a view with the right series of relationships so that you are given a complete list of orders out of a set of users. The most straightforward way to do this is to create a view of orders (so the base table is the order table) and then to use the contextual filters to provide a list of owner user_id's based on the currently logged in user using PHP.

Hint: You could use the following (UNTESTED) php snippet that makes use of a subuser function to provide an array of user ids:

// Updated with a tested bit of code:

<?php
// never use the global $user variable directly.
$account = $GLOBALS['user'];
// the subusers module abstracts this relationship easily for us
$subusers_children = subuser_load_all($account);
// views requires a return statement.
// the subuser_load_all() returns full objects, we just need the uids
$allusers = array_keys($subusers_children);
$allusers[] = $account->uid;
return implode(',',$allusers);

Here's an export of a view that works (sort of). The user permissions for this would have to be reworked to make it secure. Works with user 1 if user 1 has subusers and those subusers have orders.

// Edit 2: Did some more testing, found the view wasn't working and after some debugging, it started working correctly, limiting the users to our sub users group. Sorry about the weird problems initially introduced.

<?php
$view = new view();
$view->name = 'user_orders_with_subusers';
$view->description = 'Display a list of completed orders for a user.';
$view->tag = 'commerce';
$view->base_table = 'commerce_order';
$view->human_name = 'User orders with subusers';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['title'] = 'All orders';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = 25;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
'order_number' => 'order_number',
'created' => 'created',
'changed' => 'changed',
'commerce_order_total' => 'commerce_order_total',
'status' => 'status',
);
$handler->display->display_options['style_options']['default'] = 'order_number';
$handler->display->display_options['style_options']['info'] = array(
'order_number' => array(
'sortable' => 1,
'default_sort_order' => 'desc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
'created' => array(
'sortable' => 1,
'default_sort_order' => 'desc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
'changed' => array(
'sortable' => 1,
'default_sort_order' => 'desc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
'commerce_order_total' => array(
'sortable' => 0,
'default_sort_order' => 'asc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
'status' => array(
'sortable' => 1,
'default_sort_order' => 'asc',
'align' => '',
'separator' => '',
'empty_column' => 0,
),
);
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['text']['id'] = 'text';
$handler->display->display_options['empty']['text']['table'] = 'views';
$handler->display->display_options['empty']['text']['field'] = 'area';
$handler->display->display_options['empty']['text']['content'] = 'You have not placed any orders with us yet.';
$handler->display->display_options['empty']['text']['format'] = 'plain_text';
/* Field: Commerce Order: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'commerce_order';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
/* Field: Commerce Order: Order number */
$handler->display->display_options['fields']['order_number']['id'] = 'order_number';
$handler->display->display_options['fields']['order_number']['table'] = 'commerce_order';
$handler->display->display_options['fields']['order_number']['field'] = 'order_number';
$handler->display->display_options['fields']['order_number']['link_to_order'] = 'customer';
/* Field: Commerce Order: Line items */
$handler->display->display_options['fields']['commerce_line_items']['id'] = 'commerce_line_items';
$handler->display->display_options['fields']['commerce_line_items']['table'] = 'field_data_commerce_line_items';
$handler->display->display_options['fields']['commerce_line_items']['field'] = 'commerce_line_items';
$handler->display->display_options['fields']['commerce_line_items']['settings'] = array(
'view' => 'commerce_line_item_table|default',
);
$handler->display->display_options['fields']['commerce_line_items']['delta_offset'] = '0';
/* Field: Commerce Order: Created date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'commerce_order';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'Created';
/* Field: Commerce Order: Updated date */
$handler->display->display_options['fields']['changed']['id'] = 'changed';
$handler->display->display_options['fields']['changed']['table'] = 'commerce_order';
$handler->display->display_options['fields']['changed']['field'] = 'changed';
/* Field: Commerce Order: Order total */
$handler->display->display_options['fields']['commerce_order_total']['id'] = 'commerce_order_total';
$handler->display->display_options['fields']['commerce_order_total']['table'] = 'field_data_commerce_order_total';
$handler->display->display_options['fields']['commerce_order_total']['field'] = 'commerce_order_total';
$handler->display->display_options['fields']['commerce_order_total']['label'] = 'Total';
$handler->display->display_options['fields']['commerce_order_total']['click_sort_column'] = 'amount';
$handler->display->display_options['fields']['commerce_order_total']['settings'] = array(
'calculation' => FALSE,
);
/* Field: Commerce Order: Order status */
$handler->display->display_options['fields']['status']['id'] = 'status';
$handler->display->display_options['fields']['status']['table'] = 'commerce_order';
$handler->display->display_options['fields']['status']['field'] = 'status';
/* Contextual filter: Commerce Order: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'commerce_order';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'php';
$handler->display->display_options['arguments']['uid']['default_argument_options']['code'] = '$account = $GLOBALS[\'user\'];
$subusers_children = subuser_load_all($account);
$allusers = array_keys($subusers_children);
$allusers[] = $account->uid;
return implode(\',\',$allusers);';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['uid']['break_phrase'] = TRUE;
/* Filter criterion: Commerce Order: Order state */
$handler->display->display_options['filters']['state']['id'] = 'state';
$handler->display->display_options['filters']['state']['table'] = 'commerce_order';
$handler->display->display_options['filters']['state']['field'] = 'state';
$handler->display->display_options['filters']['state']['operator'] = 'not in';
$handler->display->display_options['filters']['state']['value'] = array(
'cart' => 'cart',
'checkout' => 'checkout',
);

/* Display: User Orders */
$handler = $view->new_display('page', 'User Orders', 'order_page');
$handler->display->display_options['path'] = 'orders-subusers';
$handler->display->display_options['menu']['title'] = 'All Orders';
$handler->display->display_options['menu']['weight'] = '15';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$handler->display->display_options['tab_options']['type'] = 'normal';
$handler->display->display_options['tab_options']['title'] = 'Orders';
$handler->display->display_options['tab_options']['description'] = 'User orders in the store.';
$handler->display->display_options['tab_options']['weight'] = '';
$handler->display->display_options['tab_options']['name'] = 'user-menu';


Display content that reference the logged in user using Views I have a content type Job with a Entity Reference field. This field (field_data_field_job_applicants) has a target type of User, and maximum number of values set to 10.

What I have got working so far is adding the users (specifically their uid) to this list when they click "Apply Job" on a job page.

What I am trying to do now is: when a job applicant logs in, they will see a collection of jobs they applied for.

More specifically, I want to tell the Views block to only display jobs where [current-user:uid] is referenced by field_data_field_job_applicants.

Create a content view and add a contextual filter for the field you created. My test contextual filter was called Content: User Ref Test. Your contextual filter will have the same name as the field you created.

2 . In the contextual filter's settings, click Provide Default: User ID from logged in User. This will only show content where the user has been referenced.


Pathauto is prepending  to the urls In my pattern for pathauto I'm using [nodesymlink:menu-link:parent:url:path]/[nodesymlink:menu-link:title] and for menu items that are children of the front page it is prepending <front> to the beginning of the url instead of just leaving it blank.

Perhaps it's an issue with the nodesymlinks module. Has anyone had this issue before? The urls still work, but I don't want the text <front>/ in front of my urls.

As stated in my comment above, the issue is with pathauto and not with nodesymlinks.

Basically, pathauto is replacing the standard [node:menu-link:parent:url:path] or your [nodesymlink:menu-link:parent:url:path] with the <front> slug instead of just removing it when the parent menu item is the front page.

I have been looking into a fix and couldn't find any. This is why I wrote a custom module to remove the front slug from the paths generated by pathauto. I'm including the link to future proof the answer in case the post gets updated and I'll also copy/paste the full code at the end of this answer.

Also, if you're a beginner, follow the link for more info on how to create a custom module in Drupal 7 and the like. Otherwise, just drop this code into your custom module and it should fix the situation you're describing. The function's code is well commented in case you need extra info.

Good luck.

<?php

/**
 * Implements hook_pathauto_alias_alter().
 *
 * Needed so that we remove the buggy slug <front> from paths when their
 * nodes are a sub-menu-item of the front page while using this pathauto
 * pattern: [node:menu-link:parent:url:path]/[node:title]
 *
 * If the parent is the homepage, all menu child entries will get <front>
 * added to the beginning of their URL alias which looks really ugly and
 * doesn't work on all operating systems. We need to remove it.
 *
 * Pathauto 7.x-1.2 doesn't handle this properly. Maybe later versions will.
 */
function yourmodule_pathauto_alias_alter(&$alias, array &$context) {
    //Init the slashed front slug value
    $front_slug_slashed = '<front>/';

    //If the alias contains the slashed front slug, remove it
    //Note that pathauto will later check if the generated slug is a duplicate
    //and append an incrementing number to it so no need to worry about this
    if(strpos($alias, $front_slug_slashed) !== false) {
        //Save the non-modified alias for logging
        //Note: no better way to clone a string in PHP?
        $original_alias = $alias . '';

        //Remove the front slug from within the alias
        $alias = str_replace($front_slug_slashed, '', $alias);

        //Log to Drupal's watchdog as notice
        $msg = '';
        $msg .= 'Altered pathauto alias from "' . check_plain($original_alias);
        $msg .= '" to "' . check_plain($alias) . '"';
        watchdog('sk', $msg, array(), WATCHDOG_NOTICE);
    }
}


How to trigger a rule when clicking on a link? I am looking for a way to trigger a rule when clicking on a link. What I am actually trying to do, is fireing a VBO with a Button, instead of the Dropdown solution. For this, I created a Rules-Component that does the job, but I don't know how to fire that rule, as it should start from within a view.

take a look at Rules Link:

  This module lets you create links which trigger arbitrary
  functionality with the help of Rules.


Error Message: "You must change the sites/all/libraries/mpdf/graph_cache permissions to be writable, as mPDF requires write-access to that directory." I'm getting the following error message:

"You must change the sites/all/libraries/mpdf/graph_cache permissions to be writable, as mPDF requires write-access to that directory."

The problem is that it is writable by apache and it has the correct permissions.

drwxr-xr-x.  2 hpadmin apache      22 Jul  2 10:51 graph_cache

Actually, it looks like it's not writeable by the "apache" user. It's read only. It is writeable by the "hpadmin" user though. Currently "hpadmin" is the owner and "apache" is the group.

drwxr-xr-x.  2 hpadmin apache      22 Jul  2 10:51 graph_cache

vs

drwxrwxr-x.  2 hpadmin apache      22 Jul  2 10:51 graph_cache

You can adjust the permission to group writeable with

chmod 775 sites/all/libraries/mpdf/graph_cache

or change "apache" to the owner with

chown apache:apache sites/all/libraries/mpdf/graph_cache


How do you edit content of a Drupal\Core\Render\Markup instance via a preprocess function in Drupal 8? From doing some experimentation, the only way I've been able to find to get the string property out of an instance of Drupal\Core\Render\Markup is to use the __toString() method:

$variables['fields']['title']->content->__toString();

But I'm guessing those initial underscores indicate that this is a private function, not to be used on the outside. Is there some better method to get at the content? My ultimate goal is modifying that content in some way.

You can't edit the content. There is no public method to change it.

Usually you simply override it with a new instance:

$variables['fields']['title'] = Drupal\Core\Render\Markup::create('New content');

The double underscore indicates a magic function, which would be called automatically if you use the object in a string context. This is readonly.

If you want to add a string to the old markup, that would be an example how the magic function __toString() works:

$variables['fields']['title'] = Drupal\Core\Render\Markup::create($variables['fields']['title'] . '!!!');


Print a View Field in Twig I have to convert the following D7 to D8 in my view twig file. I tried the following but its not working.

D7 Code :

<?php print $view->result[$id]->field_field_document_upload[0]["rendered"]["#file"]->filesize; ?>

D8 code in Twig :

   {{ view.result[id].field_field_document_upload[0]["rendered"]["#file"].filesize }}

What's the issue

It's impossible to say without knowing what exact template you are overriding, but you can't really convert your old PHP print statements to twig just like that.

What you can do however is put {{ dump() }} into your twig file, which is the twig equivalent to var_dump() in PHP. This will output all your available variables.

More info on {{ dump() }} here.


How can I quickly re-save all the nodes on my site (to trigger a rule that activates on content update)? I made some mistakes configuring a certain content type on my site.  To fix these mistakes, I made a rule that performs some actions "when existing content is updated."  However, I don't want to go through my site and manually save all the nodes again one by one.  Is there a way to use Rules or Views Bulk Operations to quickly re-save all the nodes?

VBO has an "Execute PHP code" action.
Run it, and input "node_save($entity);" (without the quotes) in the textbox.
That will do the trick, while handling the timeouts for you.


How do I get request parameters when using fragment AND query with drupal_goto I was successful in using fragment with drupal_goto, but when I use it AND query, I am not able to get the request parameters using $_GET from the query.

I can see the request parameters in the URL, but it returns NULL.  The URL is constructed as http://mydrupalsite/?code=success#overlay=admin/vendor/auth-stripe.

I am attempting to use $_GET['code'] to get the parameter.  I also tried $_REQUEST

I'm guessing you're trying to access the $_GET from the page that's loaded in the overlay (admin/vendor/auth-stripe).  If that's the case, then you've constructed the url wrong.  It should be:
http://mydrupalsite/#overlay=admin/vendor/auth-stripe%3fcode%3dsuccess

That said: where are you actually constructing this URL?  If you're doing it properly, all of that should be taken care of for you automatically.


How to get webform field value in hook_webform_results_access In webform 7.x-4.11 I use this :

if (webform_results_access($node)) {
    $actions['resend_app'] = array(
      'title' => t('Resend Appointment'),
      'href' => 'ical/' ,
    );
  }

I use it to add a "Resend Appointment" option (just as "resend email") when editing a webform.

I would like to add in the "href" some field value of this webform. How can I do that?

$submission->data[$sid][0]

for exemple:

if (webform_results_access($node) && ($node->nid == '23')) {
      $actions['resend_ical'] = array(
      'title' => t('Resend ical'),
      'href' => 'ical?' . $submission->data[5][0] . '&' . $submission->data[6][0] . '&' . $submission->data[35][0] . '&' . $submission->data[36][0] . '&' . $submission->data[24][0] . '&' . $submission->data[34][0] . '&' . 'node/' . $node->nid . '/submission/' . $submission->sid ,
      'query' => drupal_get_destination(),
    );
  }

this is that simple!


Adding media icon to text editor. How? I've enabled the Media editor and would like an Add Media icon to be available in my text editor (CKeditor). How would I enable this feature?

Do you also have wysiwyg module installed. You can go to admin-config- ckeditor there you can choose for different editor types like full-html which buttons are availible. To upload images i like to use the kcfinder module.


Path to Images for Content Type In a custom module I'm trying to display results from mysql DB based on items users selected in a form. One of the fields in the content type I'd like to display is an image associated with the node. This image appears to be housed in the table 'file_managed' in a field called 'filename' - or at least that's where the NAME of the file is located. I'm able to retrieve that field fine using SQL and joins and when I echo the result it shows the following (for example):

nameoffile.png

So I tried calling that with php using:

$icon = $row['filename'];
echo $icon; // works fine

$output .= '<img src="' . $icon . '" />';

And it just shows a blank image icon (not the image nameoffile.png).

So then I think well I must have the path wrong. So I dragged the image icon from the search results page (where it displays just fine) into a new tab and this is the URL I get:

http://pf.dev/sites/default/files/styles/thumbnail/public/PPP_CCYCL_CLP_ChrevonCycle_A_8Red.png

But of course I don't want to use an absolute path, esp. since this is on the dev. server.

So my question is this: how do I find the paths to my content type images so I can display them correctly in my custom module?

There are a couple of things you can do. First, instead of grabbing the filename field from the {file_managed} table, you'll want to grab the uri.

Then you can use file_create_url() to generate a url to the original file:

$icon = file_create_url($row['uri']);
$output .= '';

Or if you want to run the image through an image style, you can use image_style_url() (you'll need to know the machine name of the image style)

$icon = image_style_url('image_style', $row['uri']);
$output .= '';


Conflict with db_set_active and variable_get I am running a drupal multi-site system, with shared code and seperated DB. Each individual multi-site represents one continent and can have different language versions.

What i want:
I am working on a module, that gathers all available languages on all multi-sites into one big continent/language map.

To query cross-multi-site data i use db_set_active([multisite]) and manually fetch some data via db_query().

foreach ($multisites as $multisite) {
  db_set_active($multisite['db']); //switch context
  $links = db_query(Select language from {languages} etc...)) // run query
  do_somthing_with_data($links) //work with data
  db_set_active(); //switch to default
}

This works pretty fine,
but there are already drupal-core functions in language.inc i want to use (e.g. language_negotiation_get_switch_links()).

foreach ($multisites as $multisite) {
  db_set_active($multisite['db']); //switch context
  $links = language_negotiation_get_switch_links(...,...) // run core-function
  db_set_active(); //switch to default
}

Here is my problem:
Several core functions use variable_set() and variable_get(). They are persistent and initialized on bootstrap.

When changing the active database with db_set_active(), incoming queries have the new context, but values fetched with variable_get() are inconsistent, because they store data from default database, filled on bootstrap.

In a nutshell:
I want to run core-functions on one multi-site with data from another multi-site. db_set_active() works fine, but data is inconsistent because variable_get() uses data, which is initialized on bootstrap.

Has anyone ever worked with this issue?

Kind regards
larry

Addition:

As I got deeper into development it became more and more complicated. I don't recommend the procedure of cross-multi-site-core-function-calling, because the initialization of core-functionality is triggered during bootstrap.

Here an example:

The multi-site you are browsing to does not need to initialize language.inc, because it has just one language-version. Further in code-progress you switch context to a multi-site with two or more languages but language.inc functionality is not available, because it was not initialized.

I've been reading around, and on db_set_active  API page on d.o the 2 comments on that page mention the problem with caches and multi dbs.

So I went on to look at variable_get API page and it uses global $conf variable. I did a quick search on google on how to "refresh global variables conf" and got this page on d.o DrupalWebTestCase::refreshVariables(). Basically this function refreshes the global variables like so:

protected function refreshVariables() {
  global $conf;
  cache_clear_all('variables', 'cache_bootstrap');
  $conf = variable_initialize();
}

So I'm guessing (I haven't tried it and I don't have a multisite installation at hand to test it) you just need to utilise the code from the above function and clear the variables cache and re-initialize the variables in your foreach loop. I'm not sure how efficient it is so that's another issue if it's not efficient and slows down your page.

global $conf;
foreach ($multisites as $multisite) {
  // Not sure if cache_clear_all should be called before or after switching the database. You should test and figure out what's best.
  cache_clear_all('variables', 'cache_bootstrap');
  db_set_active($multisite['db']); //switch context
  // Re-set $conf global variable so when variable_get gets called it uses the updated $conf.
  $conf = variable_initialize();
  $links = language_negotiation_get_switch_links(...,...) // run core-function
  db_set_active(); //switch to default
}

Hope this helps steer you in the right direction. Good luck


How do I get the order_id and order_number on the checkout completed page? I'm trying to get the order information inside the mymodule_preprocess_page hook.
On the normal page I can get it via the $cart. But the $cart is not available on the checkout page anymore. How do I get the order information specifically the order_id and order_number.
This is what I do on other pages:
  $order_type = 'physical';
  $cart_provider = \Drupal::service('commerce_cart.cart_provider');
  $store = \Drupal::service('commerce_store.current_store')->getStore();
  $cart = $cart_provider->getCart($order_type, $store);
  if ($cart) {
    foreach ($cart->getItems() as $order_item) {
      $orderId = $order_item->get('purchased_entity')[0]->get('target_id')->getValue();
  }

The following should work:

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = \Drupal::routeMatch()->getParameter('commerce_order');


Auto create node reference in Drupal 7 I have made a new content type called wall and used user reference on it. Is there a way to auto create node whenever a new user is registered? I found the Autocreate Node Reference module but it doesn't have version 7 so I'm looking for an alternative.

This is a good example where Rules module can help you. I myself probably just write some custom code, since that's easy for me. But if you don't want to/can't do this, Rules can help you.

You can setup a rule, that is executed when a new user is created that will create a content of the chosen type. With tokens you can populate the values needed.

Using Rules can be a bit complex, but it's very powerful.


Check if a field value is already in the database I want to check if the entered value is already in the database or not. If it is, I want to stop creating the node, and show a message telling the users to change that value; if that value is not found in the database, the user should be able to create the node.

What is the correct function to call to stop the creation process?
How do I check if the field value is already in the database?

You should use hook_node_validate
This allows you to return error on the specific field that fails.
e.g.

if($query->rowCount() > 0) {
  form_set_error('machine_name', t('There already exists another node with same machine name - machine name has to be unique.'));
  // where machine_name is the field in this example
}

You wanna check database if value exists.
Can you elaborate exactly what you wanna check? Is it to ensure a specific field only contains unique values?


Why my website is showing junk characters? My Drupal 6 website is showing junk characters like:

<�h�3�>�C�o�m�m�e�n�t�s�<�/�h�3�>� �<�t�a�b�l�e�>�<�t�r� �b�g�c�o�l�o�r�=�'�#�E�7�E�7�E�F�'�>�<�t�d�>�P�o�s�t�e�d� �O�n�:� �1�2�-�1�3�-�2�0�1�0�

It used to happen once in every 1-2 months, and with any page of the website. Clearing the cache resolve the problem.
I think its the problem with cache_page table and page compression, because when I manually clear the entry in cache_page table for that particular page, it gets resolved.

When we remove � manually, we see:

Comments

Posted On: 12-13-2010

Probably it comes from comment.tpl.php in your theme. At first glance looks like UTF-8 - UTF-16 issue, but only you can really debug that.

The exact part of code you pasted seems to appear in following threads:

https://www.drupal.org/node/76407
https://www.drupal.org/node/28016

See, maybe original developer was using them? Hope it helps you with debugging, we here cen't really help more.


module_load_include not working including inc file I am trying to make it work, but it seems simply not working in Drupal 6. Maybe this is the issue, it does not work on D6?

This is the code:

// $file_path = module_load_include('inc', 'MYMODULE.inc', 'includes/MYMODULE.inc');
$file_path = module_load_include('MYMODULE', 'MYMODULE.inc');

// Testing.
if ($file_path === FALSE) {
  dpm('Failed to include: ' . $filename);
}
else {
  dpm('Successfully included: ' . $file_path);
}

I have tried also adding a drupal_load before and some other things, like changing params, moving the inc file to the root module folder and so, but I allways get the same:

Failed to include: sites/all/modules/MYCOMPANY/MYMODULE/MYMODULE.module

any idea of what am I doing wrong?

Thanks a log.

You need to add inc into your implementation of the function.  Also you don't need to add the extension .inc as part of the filename:

$file_path = module_load_include('inc', 'MYMODULE', 'FILENAME');

Documentation: module_load_include();.


Table format in webforms I have created  a customized form using the Webform module in Drupal 7, but I want to have a table with rows n columns one part of this form. I downloaded the Webform Table Element module, but there is no way to configure it or arrange the rows and columns, and mention labels as I want.

Please suggest me a step-by-step way to include a large table in webforms. How can it be managed without coding?

From your Comment "contain user entered data" i understood you need webform submitted data in Table format, If so then download and install this module Webform Report

  This module allows users to create simple, dynamic reports based on
  data collected by the webform module. It adds a new node type that
  contains the report criteria, and the data displayed is updated
  automatically as webforms are submitted.

See the webform report in below image, hope it helps you!!


In hook_user_login is there a way to know if this is the first time the user has logged in? I'm overriding hook_user_login to redirect users to a specific page when they log in. The problem is I'm using the verification email setting on registration which requires the user to set their password on first login, but I redirect them so some users aren't able to login the 2nd time to the site.

Is there something I can check in hook_user_login that will tell me if this is the first time the user has logged into the site?

Check for $account's access property. It is a timestemp the user logged in previously.

It should be other than a valid time stamp in case to be a first time login.

function MODULE_user_login(&$edit, $account){
debug($account->access);
}


Persisting URL params on form_set_error Scenario

I have a page which looks like
  http://notfound.stackexchange.com?a=1&b=2

After validation, i use form_set_error to display a drupal error message on the same page(url)
but end up without the url params
  http://notfound.stackexchange.com

Question

Is there a way to preserve/persist the url params on form_set_error ?
Is using drupal_goto the correct way (since i can send the url params again) to redirect to the same page ?
hidden form elements to store the params for use on different pages in the process flow, but as a last resort if there is no other way ?

$form_state['redirect'] = FALSE;

This works like a charm since the form is not rebuilt or reloaded.
Below link contains more info
https://drupal.org/node/1850410