How to pass Webform elements from controller to custom twig template

23 hours 41 minutes ago

I'm pretty new to Drupal and probably this is simple but I got stuck with this.

What I'm trying to do: I have created a custom module where I have defined a custom route to display my webfrom in custom twig template.

How and what to return from Controller so my webform elements will be available in custom twig template.

my_module.module /** * Implementation of hook_theme * * Since we have a lot to explain, we're going to use Twig to do it. */ function my_module_forms_theme($existing, $type, $theme, $path) { return [ 'my_template' => [ 'variables' => ['test_var' => NULL], 'render element' => 'form' ], ]; }

my_module/src/Controller/MyModuleController.php namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyModuleController extends ControllerBase {

public function content() { $my_form = \Drupal\webform\Entity\Webform::load('my_form_id'); $form = \Drupal::entityManager() ->getViewBuilder('webform') ->view($my_form);

$build = [ '#theme' => 'my_template', '#form' => $form, ]; return $build;

} }

In my twig template, I want to be able to use form elements like below. Please let me know how to achive this.

my-template.html.twig {{ form.element.name }} {{ form.element.email }}

Thanks

Alan

import address data from CSV

1 day ago

I migrate my content from an old D7 site to D8 site. All went well, except the addresses from field address where not migrated to the new address field.

Then I use feeds, feeds_migrate, content-import... Nothing work for this.

Then finaly start learning how to do this in a custom module. I used the plugin from the module addres, I wrote my own plugin. No migration seems to work.

I have a CSV file with the addresses. There is also a NID row that is unique, I also try with the title field who also is unique. I try to import this csv file into my content type business. The nodes are existing with the NID numbers. Just try to fill the address in each content. All addresses are in Belgium.
Below my YML file in a custom module.

id: migzaal label: Adres veld migratie source: plugin: csv path: modules/custom/adresmigratie/assets/adresinvoer.csv header_row_count: 1 ids: - Nid process: nid: Nid field_adres: plugin: addressfield destination: plugin: 'entity:node' default_bundle: business overwrite_properties: - 'field_adres/address_line1' - 'field_adres/locality' - 'field_adres/postal_code' - 'field_adres/country'

Can someone guide me in the right direction. Thanks.

Belba

Drupal - add machine-name as css class to my blocks

1 day 1 hour ago

So I would like to give my blocks the internal machine name of the block as a CSS class? I can add the block ID and the block type as presprocess via theme.theme:

function xxx_theme_preprocess_block(&$variables) { // adding custom attribute class for block if ($variables['elements']['#base_plugin_id'] == 'block_content') { $blockType = strtr($variables['content']['#block_content']->bundle(), '_', '-'); $variables['attributes']['class'][] = 'block--type-' . $blockType; } }

but how exactly do I get the machine name of the block? Does anyone have a tip for me? Would I like to stick to programming and not install a module, or can I get the machine name more quickly via the Twigtemplate? Would be very grateful for any help.

Bavra

Bavramor

Filter date from current date to upcoming 7 days?

1 day 1 hour ago

I have a week type calendar view. It currently displays form SUN to SAT of the current week.

But I need to display it starting from current date to current date + 7 days

How can I achieve this?. I am using Calendar Module and created a view using it.

My view is displayed only if I add a contextual filter. With default value as current date. This adds a filter criteria from dates starting from the start of the week and end of the week.

user46121

composer install error

1 day 2 hours ago

I can't install anything because of this error:

[RuntimeException] Could not scan for classes inside "/app/vendor/symfony/serializer/src/" which does not appear to be a file nor a folder

and subsequently:

Could not scan for classes inside "/app/vendor/symfony/yaml/src/" which does not appear to be a file nor a folder

I navigated to that directory and the src folder is indeed missing...

I'm using Lando and switch the PHP to 7.1. I tried deleting the vendor directory and rerunning lando composer update and lando composer install but get the same errors.

AlxVallejo

Warning: Invalid argument supplied for foreach() in form_select_options() (line 2837 of includes/form.inc)

1 day 3 hours ago

I get the following erros on selecting the selectbox. Here onchang of this field will populate another checkbox with city details id zipcode using ajax callback.

$zipcode_options = get_all_zipcodes_ascending(); // Populate Ort on auktion clone. $selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL; $selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected; $ort_options = _ajax_city_dropdown_options($selected); $form['zip_code'] = [ '#type' => 'select', '#title' => t('PLZ'), '#options' => $zipcode_options, '#default_value' => isset($auktion->zip_code) ? $auktion->zip_code : "", '#select2' => ['width' => '100%', 'placeholder' => t('Enter a zipcode'), 'allowClear' => TRUE], '#empty_option' => '', '#validated' => TRUE, '#required' => TRUE, '#ajax' => array( 'event' => 'change', 'callback' => 'ajax_example_dependent_dropdown_callback', 'wrapper' => 'dropdown-second-replace', ), ];

Referenced many links but cannot find a solution to resolve this issue.

References:

https://www.drupal.org/node/586576

populate drop down from results using ajax

http://techqa.info/drupal/question/203725/help-understand/solve-this-warning:-invalid-argument-supplied-for-foreach%28%29-in-views-that-requires-class-registry-clean-to-mend

developer

Get Checkbox Value From Another Form

1 day 4 hours ago

How do i get the value of a checkbox from another form/page and how do i make it so if the checkbox is enabled, it'll allow a button to be visible?

checkbox in SettingsForm.php:

$form['#tree'] = TRUE; $form['clients_enabled'] = array( '#title' => t('Enable PixelPin OpenID Connect'), '#type' => 'checkboxes', '#options' => array('pixelpin' => $this->t('Enable')), '#default_value' => $clients_enabled, );

button ion LoginForm.php:

public function buildForm(array $form, FormStateInterface $form_state) { $definitions = $this->pluginManager->getDefinitions(); foreach ($definitions as $client_id => $client) { foreach ($this->pluginManager->getDefinitions() as $client_name => $client_plugin) { if (!$this->config('pixelpin_openid_connect.settings.' . $client_id) ->get('enabled')) { $url = \Drupal::service('path.current')->getPath(); $find = 'login'; $pos = strpos($url, $find); if ($pos === false){ $value = 'Register Using @client_title'; } else { $value = 'Log in with @client_title'; } $element = 'clients_enabled[' . $client_plugin['id'] . ']'; $form['pixelpin_openid_connect_client_' . $client_id . '_login'] = array( '#type' => 'submit', '#value' => t($value, array( '@client_title' => $client['label'], )), 'visible' => array( ':input[name="' . $element . '"]' => array('checked' => TRUE), ), '#name' => $client_id, '#prefix' => '<div>', '#suffix' => '</div>', ); } } } return $form;
Callum

Retrieve contents from a JSON URL using cURL and display them in an HTML table

1 day 5 hours ago

I am trying to display contents retrieved from an external URL using JSON (the cURL method). So i wrote the below function:

function file_get_contents_curl() { //JSON URL which should be requested $gry_str = "?timezone=" . urlencode(date_default_timezone_get()) . "&dateFrom=" . date('Y-m-d') . "&dateTill=" . date('Y-m-d'); $json_url = 'https://www.example.com/json/financial-calendar.json' . $gry_str; // Initializing curl $ch = curl_init(); //Configuring curl options $options=array(CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array('Content-type: application/json'), CURLOPT_URL => $json_url); //Setting curl options curl_setopt_array($ch, $options); //Getting resutls $results= curl_exec($ch); //Getting json result string }

I want the contents retrieved to be displayed in an HTML table. So i am using this:

<script id="calendarContentTemplate" type="text/html"> <![CDATA[ <tr> <td class="calendar-local-time"><%= time %></td> <td class="region"><%= region %></td> <td class="title"><%= title %></td> <td><%= forecast %></td> <td><%= previous %></td> </tr> ]]>

and my constructed table like this:

<table class="calendar-table"> <thead> <tr> <th class="time">Time</th> <th class="region">Region</th> <th class="title">Event</th> <th class="forecast">Forecast</th> <th class="previous">Previous</th> </tr> </thead> <tbody> <tr> <td class="calendar-local-time"></td> <td class="region"></td> <td class="title"></td> <td></td> </tr> </tbody> </table>

Nothing is being displayed on the table. Am I doing something wrong? Or do I need a Drupal function to make it work? Forgot to mention that its for the front page.

I have read about the drupal_json_output() function. But I am not sure if I have to use it. When I tried using it my webpage appeared only HTML.

It is very weird, because when I open Firebug I can see in the Net section. I am receiving Status as 200 Ok for request, but the response is completely empty.

Any help is greatly appreciated.

paranod

Call to undefined function menu_load() in .../public_html/includes/menu.inc on line 579

1 day 6 hours ago

I really need your help. Actually, my journey begin with the installation Drupal and some modules. After a couple of days I suddenly get an issue "500 Internal Server Error".

I asked my hosting provider why this happened, they said "That because of the file .htaccess and you should add to this file php display error". So i did this and I get a new issue :

Fatal error: Call to undefined function menu_load() in public_html/includes/menu.inc on line 579.

By the way that's line 579 else {$return = $function($value);}. P.S I am a beginner in PHP. I really want to study Drupal more and create cool sites, but this problem...

user20059

Can not login with HybridAuth

1 day 7 hours ago

I installed Drupal HybridAuth module on my site for social authentication. I configured this module and it is displaying fine on site block. But when I try to login with any Social Media account details, it is processing correctly, but I cannot login in my site. How can I solve this? Here's a link to the site: example.com

Subhajyoti De

How to export custom module form content as PDF file in drupal 7?

1 day 9 hours ago

I have a custom module with some form fields. I want to submit this form and generate pdf file of user filled values in new tab. I am trying with TCPDF but it doesn't display any fieldset ( as border ).

In submit funciton , I am taking $form array and using drupal_render($form) that render form values as html ( if I print ). If I pass this html to WriteHTML($html, true) , it gives pdf but there is no styling left on that form.

atyagi

The Facebook Autopost module "user hasn't authorized the application"

1 day 10 hours ago

I have a problem with the Facebook Autopost module for Drupal 7.28): After publishing a node, I get an authorization error.

Facebook SDK threw an error: OAuthException: (#200) The user hasn't authorized the application to perform this action

I have checked permissions "Publish Actions", "Publish Stream", "Manage Pages" for Administrator role in fbpermissions module.

Also, I have submitted "manage_pages" in my app but cannot submit "publish_actions" because of this:

It looks like you haven't made any API requests to access content with the publish_actions permission in the last 30 days.

Don't know what to do now. Have no idea why it's not working and what Facebook app permissions are missing. Was googling it for an about 2 hours. Checked all found solutions... none of them worked...

Jazi

Set node to flagged by default

1 day 13 hours ago

I'm using flags on my site as a way of filtering content through views, when a user views a certain node content type, I have a rule setup which resets the value of my flag and sets it against that user for that node, the views will reference this information and change their output accordingly.

The problem I have at the moment is what happens when anonymous users enter the site for the first time, they have no flag set, and thus none of the views show anything, until they travel to one of these special nodes.

What I'm looking for is: is it possible to set a flag to a default value, so that everyone has this node tagged until it gets changed?

Andrew Morris

Action links available options / caching

1 day 14 hours ago

I have some action links defined in module.links.actions.yml which uses a custom "create entity" route. For entity creation I set up some restrictions and at some point the access is denied. The problem is that whilst the access to the page is denied, the action link is still visible until I clear all caches.

Is there a way to tell Drupal not to cache the links or to programmatically clear the links cache? Or some options I can add in the yml file to prevent caching?

Thanks.

Marius Ilie

Styling a "programmatically created block" in drupal 10

1 day 15 hours ago

I'm new to Drupal dev, I'm messing around creating some custom modules and explore how the env of drupal 10 works... I've created a custom block that i called "Copyright":

<?php declare(strict_types=1); namespace Drupal\plugin_play_module\Plugin\Block; use Drupal\Core\Block\Attribute\Block; use Drupal\Core\Block\BlockBase; use Drupal\Core\StringTranslation\TranslatableMarkup; #[Block( id: 'copyright_block', // id is the internal machine name, admin_label: new TranslatableMarkup('Copyright'), category: new TranslatableMarkup('Custom') ) ] class Copyright extends BlockBase { #[\Override] public function build(): array { $date = new \DateTimeImmutable(); return [ '#markup' => \t('Copyright @year&copy; My Company', ['@year' => $date->format('Y')]), ]; } }

and after I placed it in footer region using UI, I wanted to style it a little... Based on some inspection:

I have added some css:

.block__content{ text-align: center; color: green; }

but at the end, nothing changed here's the config for that custom module :

#plugin_play_module.info.yml name: Plugin Play Module description: playing with plugins type: module core_version_requirement: '>=9' libraries: - plugin_play_module/copyright_block #plugin_play_module.libraries.yml copyright_block: css: layout: css/styles.css: {}

here the tree structure of the web/modules/plugin_play_module

│   ├── plugin_play_module │   │   ├── **css** │   │   │   └── styles.css │   │   ├── **js** │   │   ├── plugin_play_module.info.yml │   │   ├── plugin_play_module.libraries.yml │   │   ├── plugin_play_module.module │   │   ├── plugin_play_module.services.yml │   │   ├── **src** │   │   │   └── **Plugin** │   │   │   ├── **Block** │   │   │   │   └── Copyright.php │   │   │   ├── ...
tsukingo

Form and gated content

1 day 17 hours ago

UPDATED from earlier:

I am using a simple Drupal form that collect user info before allowing the user access to donwloadable content. NOTE: This is using the form API and I am no longer using a modal; just using a regular page created by a hook. Here is the scenario:

<?php function my_form_menu() { $items = array(); $items['form/userinfo'] = array( //this creates a URL that will call this form 'title' => 'Download Form', //page title 'description' => 'A form that gathers user infomation', 'page callback' => 'drupal_get_form', //this is the function that will be called w hen the page is accessed. for a form, use drupal_get_form 'page arguments' => array('my_form'), //name of the form 'access callback' => TRUE ); return $items; } function my_form() { if (!empty($_COOKIE['Drupal_visitor_downloadbypass'])) { drupal_goto('this is where the pdf file will go'); // rest of the page will not execute because drupal_goto ends the request. } $form['name']['first'] = array( '#type' => 'textfield', '#title' => t('First name'), '#required' => TRUE, ); $form['name']['last'] = array( '#type' => 'textfield', '#title' => t('Last name'), '#required' => TRUE, ); $form['name']['title'] = array( '#type' => 'textfield', '#title' => t('title'), '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => 'Submit', ); return $form; } function my_form_submit($form, &$form_state) { // $form_state['values']['example'] contains the submitted value of 'example' element. user_cookie_save(array('downloadbypass' => 1)); $form_state['redirect'] = 'this is where the pdf file will go'; }

So here is my question: Now my form page is not showing up and I didnt change the hook except for the form name argument. The form will need to redirect back to the previous page and open the file in a new window upon submission.

Thanks!

phi

DataGuy

localhost subsites configuration

1 day 18 hours ago

I know how to install a single instance of Drupal very well but I want to create a number of sub-sites under my Drupal installation. My file structure is as follows:

drupal7_main -sites --drupal7_sub1 settings.php --drupal7_sub2 settings.php

I'm developing on my localhost and the plan is to duplicate the structure on the production server.

However, only drupal7_main works. When I visit localhost/drupal7_main, Drupal is ready and configurable as usual; when I visit localhost/drupal7_sub1, I get the following error.

Not Found
The requested URL /drupal7_sub1 was not found on this server.

I get the same for drupal7_sub2.

I'm trying to learn this process and would appreciate some help.

sisko
Checked
23 hours 14 minutes ago
most recent 30 from drupal.stackexchange.com
Subscribe to Drupal StackExchange feed