Drupal StackExchange

Entity reference field hidden widget or edit disabled on custom form

6 days 5 hours ago

I have a custom node creation form I am rendering within a views preprocess hook. In that form I have two entity reference fields. I am setting the [#value] and [#default_value] of those reference fields programmatically.

On form submit the values I've set are created, but only if the fields are "editable" by the user. I want to make the fields "disabled" and/or "hidden" from the user. Not just hidden with CSS but with the entire autocomplete widget being made inaccessible. The field needs to be type "hidden".

How can I make an autocomplete entity reference disabled and/or inaccessible to the user creating the content?

Or another way of putting it, how can I add entity reference values programmatically on form submit without the user being able to interact with the fields?

Here are some things I've tried that do not work:

  1. $form['field_entity_reference']['#access'] = false; // Setting #access to false seems as though it should work because the form fields still exist when debugging $form, but it does not work as it prevents the value from being submitted.
  2. Adding ['#attributes']['readonly'], changing ['#type'] to hidden or another widget type, adding ['#attributed']['disabled']. None work
  3. Entity prepopulate - This does not work for this particular situation as some values cannot be provided by tokens

Code for reference

function <theme>_preprocess_views_view_field(&$variables) { $view = $variables['view']; if ($view->id() == '<view>') { $field = $variables['field']; switch($field->options['id']) { case '<view_field>': $node = \Drupal::entityTypeManager() ->getStorage('node') ->create(['type' => '<node_type>']); $form = \Drupal::service('entity.form_builder')->getForm($node, 'secondary'); // Set default_value and value $form['field_entity_reference']['widget']['#default_value'] = (int)$cid; // Note this is using the "select list" widget for the entity reference field $form['field_entity_reference']['widget']['#value'] = (int)$cid; // Same as above // Stuff that doesn't work. Values do not submit unless field is editable by user, or the field is not hidden/disabled $form['field_entity_reference']['#access'] = false; // Value does not submit $form['field_entity_reference']['widget'][0]['#attributes']['readonly'] = 'readonly'; // Doesn't make field read only $form['field_entity_reference']['widget'][0]['value']['#type'] = 'hidden'; // Seems autocomplete widget and select widget do not have a "hidden" type $form['field_entity_reference']['widget'][0]['target_id']['#type'] = 'textfield'; // Seems one cannot change the type to textfield // Change view field output to the form $variables['output'] = $form; break; } } }
Jason

How to conditionally display some things in the message text created by the Message module?

6 days 6 hours ago

I am using the Message module to record some activity.

I have a Rule generating a Message. The Message Type has a couple of fields, and I am setting them in the rule. That part all works great. I can verify the contents of each of those message fields.

Now what I'm trying to do is to conditionally display some things in the message text. I have a couple of Message Text rows and they all display what I expect them to. But for one of these, I want only want to display something if one of the tokens matches a condition.

I have selected the PHP Code filter type on that particular Message Text box, but I just don't know to actually evaluate the field values of the current message. I've tried t() and token_replace() and I just am not getting it.

So here is a simple question for this problem I'm having. Say I have a text field on this message type called field_foo. And I want the message text to display the length of that field. I basically want something to the effect of <?php strlen(this-message:field_foo) ?>.

How do I reference my message instance's field?

franksj

Get the uri/path value of an image in the field template

6 days 7 hours ago

I have created a custom field template for an image - field--field_images.tpl.php with the following code:

<?php $url = file_create_url($field_images['uri']); $url = parse_url($url); $imglink = $url['path']; ?> <div id="slideshow"> <?php foreach ($items as $delta => $item): ?> <div data-thumb="<?php print render($imglink); ?>" data-src="<?php print render($imglink); ?>" data-time="1500" data-trasPeriod="4000" data-target="_blank" ></div> <?php endforeach; ?> </div>

currently $imglink returns the value of the root folder "www". I need to find a way to get the path to the image file associated with the field e.g "http://www.example.com/sites/default/files/image.jpg" any help with this would be greatly appreciated.

UPDATE:

I think I'm almost there. Here is the code in my field-field_images.tpl.php file:

<?php foreach ($items as $delta => $item): ?> <div data-thumb="<?php $img_src = $element['#object']->field_images['und'][0]['uri']; $link = image_style_url('thumbnail', $img_src); print ($link); ?>" data-src="<?php $img_src = $element['#object']->field_images['und'][0]['uri']; $link = file_create_url($img_src); print ($link); ?>" data-time="1500" data-trasPeriod="4000" data-target="_blank" ><?php render($item); ?></div> <?php endforeach; ?>

and you can see the output here: http://www.kfpa.co.za/dev/?q=node/2

The one problem is that it loops through and creates the correct number of elements for the uploaded images, but when it creates the URLs it's only creating for the item as specified for by 'x' in <?php $img_src = $element['#object']->field_images['und'][x]['uri']; i.e if I change 'x' to '2' the third photo displays. How do I change this code so that it finds the correct URL for corresponding image in the loop?

flamesquirrel

Database error with migration

6 days 8 hours ago

I am trying to migrate users and a few other entities from a Drupal 7 site to Drupal 8 with the built-in migration modules and Migrate Plus. I have added a database array in settings.php but something is missing to get the migrations to "see" the right database. I am getting this error.

[Mon May 11 22:22:56.025896 2020] [php7:error] [pid 6389:tid 140003403929344] [client 62419] PHP Fatal error: Method Drupal\user\Plugin\migrate\source\d7\Role::__toString() must not throw an exception, caught Drupal\migrate\Exception\RequirementsException: No database connection configured for source plugin d7_user_role in /var/www//web/core/lib/Drupal/Component/Utility/Unicode.php on line 595, referer:

I have tried adding

shared_configuration: source: key: database_key

But it did not work.

Any help is greatly appreciated.

Thanks, Josh

Josh

Get display mode of product or product variation where an 'add to cart form' is used in hook_form_alter for the add_to_card_form

6 days 9 hours ago

I'm using Drupal 10 and the commerce module. I'm using a product display mode 'card' that uses the variations 'add to cart form' format. In hook_form_alter I am hiding the quantity field:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) { if (strpos($form_id, 'commerce_order_item_add_to_cart_form_commerce_product_') === 0) { $form['quantity']['widget'][0]['value']['#type'] = 'hidden'; } }

This works fine, but the problem is that it is obviously hiding the field for every view mode. I would like to only hide it for a my 'card' view mode. How can I get the display view mode of the product (or product variation) where the the 'add to cart form' is used.

Mike

Change the Pay button text

6 days 9 hours ago

I have created Drupal 9 website. On the website we accept donations using Commerce with Commerce Stripe as the payment processor. By default, the payment button says "Pay and complete purchase". As users are not purchasing anything, I want to change the text to something like "Donate Now". I have searched for answers online but all seem to point to the module String Overrides, which is D7 only and doesn't look like is will have a D8/9 option.

Any idea how to change the text in Drupal 9?

FrankDesign

What are all the steps needed to migrate from Video Embed WYSIWYG to Core Media (images/video fields too)?

6 days 9 hours ago

As the title suggests, I'm in the process of upgrading from Drupal 9 to 10 and would like to finally migrate over to Core Media, as opposed to just using inline video/images/files as we have for the last many years.

I have followed the following blog post https://blog.horizontaldigital.com/how-migrate-video-embed-wysiwyg-drupal-core-media but feel like I am missing something as it didn't seem to do anything for me.

I copy and pasted the supplied Update Hook code into a custom module and ran a database update, which told me the hook was applied, however, I don't seem to notice anything changing to my site.

Am I missing something? Is there another step after this in order for me to uninstall video_embed_wysiwyg and use core media for all active content?

Any help/suggestions would be greatly appreciated (explain in simple terms, preferably with depth). I'm not one who has lots of knowledge with hooks/php in general but can use it when needed.

Many thanks in advance.

ACanadianCoder

BrowserTest on a multisite gives an error

6 days 9 hours ago

My sites directory looks like this:

default, site1, site2, site3.

The default directory is empty. I want to run tests against my site1 database. So I have put its details in phpunit.xml

Here is my phpunit.xml set up.

<php> <!-- Set error reporting to E_ALL. --> <ini name="error_reporting" value="32767"/> <!-- Do not limit the amount of memory tests take to run. --> <ini name="memory_limit" value="-1"/> <!-- Example SIMPLETEST_BASE_URL value: http://localhost --> <env name="SIMPLETEST_BASE_URL" value="http://d8.site1.dev"/> <!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix --> <env name="SIMPLETEST_DB" value="mysql://site1:site1@localhost/site1"/> <!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output --> <env name="BROWSERTEST_OUTPUT_DIRECTORY" value=""/> </php>

And then my actual test:

<?php namespace Drupal\Tests\my_module\Functional; use Drupal\Core\Url; use Drupal\Tests\BrowserTestBase; /** * Simple test to ensure that main page loads with module enabled. * * @group my_module_tests */ class LoadTest extends BrowserTestBase { /** * Modules to enable. * * @var array */ public static $modules = ['my_module']; /** * A user with permission to administer site configuration. * * @var \Drupal\user\UserInterface */ protected $user; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->user = $this->drupalCreateUser(['administer site configuration']); $this->drupalLogin($this->user); } /** * Tests that the home page loads with a 200 response. */ public function testLoad() { $this->drupalGet('node/add/product_list_page'); $this->assertResponse(200); } }

Then from the core directory of Drupal I run:

../../vendor/bin/phpunit --group my_module_group

Then I get this error:

1) Drupal\Tests\my_module\Functional\LoadTest::testLoad copy(/var/www/site/docroot/sites/default/default.settings.php): failed to open stream: No such file or directory

Why is it looking in my empty default directory and not site1 for this file?

chap

How to reference external JS callback in custom module

6 days 10 hours ago

So I apologize if I mess the terms here up, I'm relatively new to using jQuery in Drupal. I'm trying to implement a custom Google Map application with the V3 API. When I started mocking the module up I had no problem invoking the google maps function callback without my JS being wrapped in a closure. However, needing to use jQuery functions pointed me to wrapping my JS in a closure and referencing jquery, as well as attaching my js to the Drupal.behaviors object. The problem that I have is that now it seems that the callback on my Google Maps script tag is out of scope. I'm not sure if this is due to the closure, due to how I'm loading the script, or something else that I haven't come across yet. The specific JS error I get is

Uncaught (in promise) message: "initMap is not a function"

My module JS is

(function ($) { Drupal.behaviors.gmap_json = { attach : function (context, settings){ var map, alumLayer, chapterLayer, assocLayer, userLayer; function initMap() { map = new google.maps.Map(document.getElementById('json-map'), { zoom: 4, center: {lat: 38.43, lng: -90} }); alumLayer.setStyle({ icon: 'purple.png', }); } } }; alert('it works'); }(jQuery));

And my module php is

function gmap_json_block_info() { $blocks = array(); $blocks['gmap_json'] = array( 'info' => t('Google Maps with GeoJSON'), ); return $blocks; } function gmap_json_block_view($delta = '') { $block = array(); if ($delta == 'gmap_json') { $block['subject'] = ''; $block['content'] = '<div id="json-map" style="width:1100px; height:500px; margin:auto;"></div>'; } $path = drupal_get_path('module', 'gmap_json'); drupal_add_js('https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap', 'external'); drupal_add_js($path. '/gmap_json.js', 'file'); return $block; }

So, what am I doing wrong and how can I either bring my callback into scope? Or what's the right way to set this up.

EDIT: I have attempted to implement both the answer as well as one of the comments.

drupal_add_js('https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap', array('type' => 'external', 'defer' => 'defer'));

Adding a "defer" via array doesn't produce any changes, and changing the order of my calls to the js only changes where the error gets called.

nizz0k

Full phrase search

6 days 11 hours ago

Now I'm using "Search_api" module and when I input, for example, "test case" - it's output all articles which consists both of this words separately. But I want to make search with exact phrase "test case". How can I do it? Maybe there is another module, or I can rework this one?

Nikita Yunoshev