Drupal StackExchange

How can I set value to hidden field (Form Api) and send them with post method?

1 month 3 weeks ago

I’ve created a form with Form Api in a custom module.

I send datas with post method to a web service.

In buildForm()

$form['mode'] = array( '#type' => 'hidden', '#value' => 'INTERACTIVE', ); $form['amount'] = array( '#type' => 'textfield' ); $form['signature'] = array( '#type' => 'hidden', // here is the field I need to set its value on submit because its value depends on other field. '#value' => '' ); $form['#action'] = 'https://url-webservices.fr/‘

It works. But I need to set value to hidden fields 'signature' on submit.

How can I set value to hidden field and send them with form with post method ?

Something like this but it doesn't work :

in submitForm() form_state->setValue('signature', $signature);

I’ve studied some examples and I can do that :

In validateForm()

$signature = 'string-to-send'; $form_state->setValue('signature', $signature); $form_state->setRebuild();

And in buildForm() :

$signature = $form_state->getValue('signature'); $form['signature'] = array( '#type' => 'hidden', '#value' => $signature );

Of course, it works only when page is reloaded when the form is rebuilt. If datas is send to an external URL with POST method, the field value is empty.

Sébastien Gicquel

How do I make theme suggestions for pagers?

1 month 3 weeks ago

I am trying to create theme suggestions function for pagers in my *.theme. Is this possible in Drupal 8? If it is possible, what is wrong with the following code? Is suggestions_pager_alter the right way to access the hook call so I can add a theme suggestion to a page, so I can override the template. I am not worried about the functions logic.

function mytheme_suggestions_pager_alter(array &$suggestions, array $variables) { // Add template suggestions based on the current view mode. print_r(); exit; }
purencool

Entity form in ctools modal popup, whilst passing in values from current node

1 month 3 weeks ago

I need to open an entityform in a modal popup. I have got this working using 'Modal operations'‎ and 'Modal forms' modules following this guide: http://julian.pustkuchen.com/en/comment/reply/599. My link looks like the following:

<a href="modal/entityform/job_application/nojs/0" class="ctools-use-modal ctools-modal-modal-popup-large btn"><?php print t('Apply') ?></a>

The problem now is that I need to pass certain data (e.g. the nid) of the currently viewed node into the entityform.

I am happy to use hook_form_alter or similar, but obviously hooking the entityform has no knowledge of the currently viewed node. My other, pretty hacky, idea was to grab data with javascript and put it in that way, but I need some sort of popup event to work from, which I don't think exists.

Is there another approach to this I could be using, or am I going down the right track?

Chris

Broken/missing handler error for my custom views filter?

1 month 3 weeks ago

I am trying to write a custom filter for views. The goal is to filter by alias, but that's not important now. It seems like I am missing a step to get view to recognize my filter hander after adding my filter in hook_views_data_alter as in the following:

/** * Implements hook_views_data_alter(). */ function alias_views_filter_views_data_alter(array &$data) { $data['node']['alias'] = [ 'title' => t('alias filter'), 'filter' => [ 'title' => t('alias filter'), 'help' => t('Provides a custom filter nodes by their alias.'), 'field' => 'nid', 'id' => 'entity_alias', ], ]; }

I am able to get the filter to show in a view filter list. Now, my filter handler defined in /docroot/modules/custom/alias_views_filter/Plugin/views/filter/Alias.php but it does not seem to be picked up by views and I always get Broken/missing handler whenever I try to add the filter. Here is my handler definition:

<?php namespace Drupal\alias_views_filter\Plugin\views\filter; use Drupal\views\Plugin\views\display\DisplayPluginBase; use Drupal\views\Plugin\views\filter\StringFilter; use Drupal\views\ViewExecutable; use Drupal\Core\Form\FormStateInterface; /** * Filters by alias. * * @ingroup views_filter_handlers * * @ViewsFilter("entity_alias") */ class Alias extends StringFilter { /** * The current display. * * @var string * The current display of the view. */ protected $currentDisplay; /** * @var views_plugin_query_default */ public $query; /** * Constructs a new StringFilter object. * * @param array $configuration * A configuration array containing information about the plugin instance. * @param string $plugin_id * The plugin_id for the plugin instance. * @param mixed $plugin_definition * The plugin implementation definition. * @param \Drupal\Core\Database\Connection $connection * The database connection. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $connection) { parent::__construct($configuration, $plugin_id, $plugin_definition); // this does seem to get evaluated at all ? die('Death in handler'); } protected function defineOptions() { $options = parent::defineOptions(); $options['fields'] = ['default' => []]; return $options; } /** * {@inheritdoc} */ public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) { parent::init($view, $display, $options); $this->valueTitle = t('Filter by alias'); } public function buildOptionsForm(&$form, FormStateInterface $form_state) { parent::buildOptionsForm($form, $form_state); $this->view->initStyle(); } function query() { $this->ensureMyTable(); $field = $this->tableAlias."nid"; //table_alias.".nid"; $nids = $this->getNidsByAliasString($this->value); if (!empty($nids)) { $this->query->addWhere('AND', $this->options['group'], $field, $nids, 'IN'); } } function getNidsByAliasString($aliasString) { $query = db_select('url_alias'); $query->condition('alias', '%'.$aliasString.'%', 'LIKE'); $result = $query ->fields('url_alias') ->execute(); $nids = array(); foreach ($result as $data) { array_push($nids, end(explode("/",$data->source))); } return $nids; } }

Am missing a step or naming the filter incorrectly?

Checking the logs, I am getting these errors:

Notice: Undefined index: field in Drupal\views\Plugin\ViewsHandlerManager->getHandler() Notice: Undefined index: table in Drupal\views\Plugin\ViewsHandlerManager->getHandler() Notice: Undefined index: id in Drupal\views\Plugin\ViewsHandlerManager->getHandler()
awm

How to set default value for entity reference programmatically in a form?

1 month 3 weeks ago

I have a custom form that I created programmatically.

$target_type = 'node'; $selection_handler = 'default'; $selection_settings = ['page']; $data = serialize($selection_settings) . $target_type . $selection_handler; $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt()); $key_value_storage = \Drupal::keyValue('entity_autocomplete'); if (!$key_value_storage->has($selection_settings_key)) { $key_value_storage->set($selection_settings_key, $selection_settings); } $form['terms_default_node'] = [ '#type' => 'textfield', '#title' => $this->t('Terms of Business - default page'), '#autocomplete_route_name' => 'system.entity_autocomplete', '#autocomplete_route_parameters' => [ 'target_type' => $target_type, 'selection_handler' => $selection_handler, 'selection_settings_key' => $selection_settings_key, ], '#default_value' => \Drupal\node\Entity\Node::load(1)->value, // What do I put here? ];

I don't get how to make the default value of the field be "Terms of Business (1)".

Autocomplete works, saving works, but I don't know how to recall that saved value again and make it as default_value when I open this form again.

This field doesn't have any widgets, etc. And I can't find anything in Google

mevsme

How to get Final SQL query when using Views?

1 month 3 weeks ago

How do I get complete SQL query from Views, the one I could run in mysql directly.For example biggest stumbling block is fields part. Like below

SELECT users_node.uid AS users_node_uid, node.created AS node_created, node.nid AS nid, users_node.mail AS users_node_mail, 'user' AS field_data_field_first_name_user_entity_type, 'user' AS field_data_field_last_name_user_entity_type, 'node' AS field_data_field_purchase_date_node_entity_type, 'node' AS field_data_field_serial_number_node_entity_type FROM {node} node LEFT JOIN {users} users_node ON node.uid = users_node.uid WHERE (( (node.status = '1') AND (node.type IN ('product_registration')) )) ORDER BY node_created DESC LIMIT 50 OFFSET 0

this lines are problematic field_data_field_first_name_user_entity_type, field_data_field_last_name_user_entity_type etc

They are not real fields in DB, they somehow get rewritten somewhere, but I can't find where and how. How to get the FINAL query to DB in drupal when using views?

p.s. in image, you can see what I get for those fields in phpmyadmin if I run query. Not really useful.

Blissful

Why is the db connection to migrate silently failing?

1 month 3 weeks ago

I'm using D10, drush 12, ddev. In settings.local.php I have:

$databases['migrate']['default'] = array ( 'database' => 'd7', 'username' => 'db', 'password' => 'db', 'host' => 'db', 'port' => '3306', 'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql', 'driver' => 'mysql', );

In the code when I do:

$db = Database::getAllConnectionInfo();

the var_dump shows 'migrate' being part of the array:

array(2) { ["default"]=> array(1) { ["default"]=> array(11) { ["database"]=> string(2) "db" ["username"]=> string(2) "db" ["password"]=> string(2) "db" ["host"]=> string(2) "db" ["port"]=> int(3306) ["driver"]=> string(5) "mysql" ["prefix"]=> string(0) "" ["namespace"]=> string(34) "Drupal\mysql\Driver\Database\mysql" ["autoload"]=> string(45) "core/modules/mysql/src/Driver/Database/mysql/" ["pdo"]=> array(6) { [3]=> int(2) [1000]=> bool(true) [1005]=> bool(true) [20]=> bool(true) [1013]=> bool(false) [17]=> bool(true) } ["init_commands"]=> array(1) { ["sql_mode"]=> string(33) "SET sql_mode = 'ANSI,TRADITIONAL'" } } } ["migrate"]=> array(1) { ["default"]=> array(9) { ["database"]=> string(2) "d7" ["username"]=> string(2) "db" ["password"]=> string(2) "db" ["host"]=> string(2) "db" ["port"]=> string(4) "3306" ["driver"]=> string(5) "mysql" ["prefix"]=> string(0) "" ["namespace"]=> string(34) "Drupal\mysql\Driver\Database\mysql" ["autoload"]=> string(45) "core/modules/mysql/src/Driver/Database/mysql/" } } }

but when I try to create a connection, with

return Database::getConnection('migrate');

I receive:

In ExceptionHandler.php line 46: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.node_type' doesn't exist: SELECT `name`,`type`,`description` from node_type ORDER BY `name`; Array ( ) In StatementWrapperIterator.php line 110: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.node_type' doesn't exist

and dumping the connection variable shows a connection to the default db but not to the migrate db.

Let me add context and more code. I began with a working module for D10 providing a drush 12 custom command. At that point, the command made no use of a database. I simply wanted to add an option to the command that makes use of a database. I mention this for two reasons: to point out that the structure of using a drush custom command had already bene in place and working, and to point out that this is a drush command, in case it could be how drush interacts with the database(s) that makes a difference.

I had been bootstrapping drush to the configuration level. In adding the new feature I upped that to the database level:

#[CLI\Bootstrap(level: DrupalBootLevels::DATABASE)]

I added the following use entries:

use Drupal\Core\Database\Connection; use Drupal\Core\Database\Database;

Once I have determined that the drush command has been entered with the option request to use the database, I call the method to establish the connection and do a simple query (I prefer to added new functionality in steps...easier to test).

if ($options['db']) { $db = $this->getD7DbConnection(); if (!$db) { $this->logger()->error(dt("There is no migrate database configured in the site settings.")); return NULL; } $file = Drupal::service('extension.path.resolver')->getPath('module', 'mymodule') . '/data/items.db.yml'; return $this->scanDb($db, $file); }

This method succeeds. It contains the db connection info showing two db's, default and migrate, shown above in the var_dump:

private function getD7DbConnection() { $db = Database::getAllConnectionInfo(); if (isset($db['migrate'])) { return Database::getConnection('migrate'); }

return FALSE;

}

This method then fails. I threw a simple query into it for now just to prove or disprove a connection:

private function scanDb(Connection $db, $file) { $results = $db->query('SELECT * from node_type ORDER BY name;');

return $results;

}

And that's all there is. At this point I'm simply attempting to connect to the db, as a result of the request via drush option, and do a simple query.

JAyenGreen

Not able to make simple node path show up in "crumbs module"

1 month 3 weeks ago

I have read all the documentation, and I have been clicking about wildly for hours, and I have used the "debug" tab for the Crumbs module, and I still cannot get the simplest path to show up:

Home > Content type > Node title

It always gives me: Home > Node title

This seems a simple task. Someone please give me the steps...

Many thanks.

rsgracey

Drupal Planet

Balint Pekker: Automatic Updates

1 month 3 weeks ago
The Automatic Updates initiative will not only address the often painful process of manually installing crucial security updates but will also make it significantly easier for your Drupal site to remain up-to-date with the security advisories and the latest protections against potential threats. Let's dive into the details and see how it works.