I am using Drupal 8.2.6 and I would like to create a block that would appear on a custom content type page.
It is kind of a booking block which sends an e-mail to the site admin that a visitor would like to book a product (the custom content type).
I assume I would need a form which only consists of a submit button and a block which renders the form.
But the real point would be sending the mail with the product's reference to the site admin.
As I found here, I could get the values I need using this snippet:
if ($node = \Drupal::routeMatch()->getParameter('node')) {
$field_my_custom_value = $node->field_my_custom_value->value;
}
But I am not sure in which scope of my code I should use it. This example was for rendering the values within a custom block, where as my case would be sending a mail with the values.
And could anyone remind me as well how to send a mail from a custom module in Drupal 8?
Thanks a lot
So, after solving it myself after a day's whole worth of documentation, here are the solutions, as I am going to revert back my question to earlier revisions, in case anyone needs it.
So, given the snippet in the question above, I declared the variables in the buildForm() function
public function buildForm(array $form, FormStateInterface $form_state) {
$field_value = '';
if ($node = \Drupal::routeMatch()->getParameter('node')) {
$field_value = $node->field_name->value;
}
$form['field_value'] = array(
'#type' => 'value',
'#value' => $field_value,
);
// And then you add the definition for other form items and submit button
}
And for sending the mail using the value, you retrieve the value using $form_state like this:
public function submitForm(array &$form, FormStateInterface $form_state) {
$module = 'your_module_name';
$key = 'any_key_you_would_like';
$to = 'receiver#email.address';
$langcode = 'en';
$params = array(
'body' => 'Node is booked',
'subject' => $form_state->getValue('field_value'),
);
$mailer = \Drupal::service('plugin.manager.mail');
$mailer->mail($module, $key, $to, $langcode, $params, NULL, TRUE);
}
Some values are quite tricky to get from the node, such as the node title which uses $node->getTitle() instead of $node->field_name->value so you would like to check your fields using Drupal 8's Devel + Kint module to know what attributes and methods to use.
Related
I'm creating a form in moodle using moodleform class. I have many fields in the form. What I'm wanting to do is when the user fills in the first field, I want to get the data that he/she entered, search the relevant DB table for a field that matches that input, then populate the other fields for that record.
Please note that the user hasn't pressed any submit button yet. I've been trying to find a function that gets the entered data but all efforts have been in vain. What I found was a get_data() method but I don't even know how to use that correctly. I've been reading the moodle docs but nothing is helping. I'm not a beginner to coding but neither am I an expert.
Here's a code snippet:
class requestcourse_form extends moodleform
{
function definition()
{
global $CFG, $currentsess, $DB, $USER, $currentrecord;
$mform =& $this->_form; // Don't forget the underscore!
// Form header
$mform->addElement('header', 'mainheader','<span style="font-size:22px">'.get_string('courserequestform','block_usp_mcrs'). '</span>');
// Course Code field.
$coursecodearray = array();
$coursecodearray[0] = get_string('choosecoursecode', 'block_usp_mcrs');
$allcoursecodes = $DB->get_records_select('block_usp_mcrs_courses', 'id > 0', array(), 'id', 'id, course_code');
foreach ($allcoursecodes as $id => $coursecodeobject) {
$coursecodearray[$id] = $coursecodeobject->course_code;
}
$coursecode = $mform->addElement('select', 'coursecode', get_string('coursecode', 'block_usp_mcrs'), $coursecodearray);
$mform->addRule('coursecode', get_string('required'), 'required', null, 'client');
$mform->setType('coursecode', PARAM_RAW);
// Course Name field. TODO: Course Name to pick automatically after entering Course Code
$coursenamearray = array();
$coursenamearray[0] = get_string('choosecoursename', 'block_usp_mcrs');
$allcoursenames = $DB->get_records_select('block_usp_mcrs_courses', 'id > 0', array(), 'id', 'id, course_name');
foreach ($allcoursenames as $id => $coursenameobject) {
$coursenamearray[$id] = $coursenameobject->course_name;
}
$mform->addElement('select', 'coursename', get_string('coursename', 'block_usp_mcrs'), $coursenamearray);
$mform->addRule('coursename', get_string('required'), 'required', null, 'client');
$mform->setType('coursename', PARAM_RAW);
Any help would be appreciated.
You have to achieve this using javascript, as Moodle has no functionality to fill data in a nested way.
Add AMD module js file where you are calling your mform for display purpose.
In the file where you render your mform
$mform->render();
add below line to call you amd js file.
$PAGE->requires->js_call_amd('local_acestructure/registration', 'init');
In your amd js file make httprequest / ajax call to fetch data based on your course_code select drop down change.
Thank you.
I am trying to learn drupal so right now my website resides on my localhost. I am using DRUPAL 7. I have created a contact us page in my drupal site using drupal's contact module. I want to add one more fields(Phone Number) to the existing contact form and need to sent the value along with the email. How is it possible to do something like this.
I have used the following code in my contact module page
function mymodulename_form_contact_site_form_alter(&$form, &$form_state) {
$form['phone'] = array(
'#title' => t('Phone'),
'#type' => 'textfield',
'#required' => TRUE,
);
$order = array(
'name',
'mail',
'phone',
'subject',
'cid',
'message',
'copy',
'submit'
);
foreach ($order as $key => $field) {
// Set/Reset the field's
// weight to the array key value
// from our order array.
$form[$field]['#weight'] = $key;
}
}
But the field is not showing up on the website page. Please help.
Thanks
Now its all fine. I had placed the code in the existing contact module file. That was the issue. Now I create a custom module and placed the similar code there. Now its all fine.
Only change needed to make it working is instead of using this
function mymodulename_form_contact_site_form_alter(&$form, &$form_state) {
use the below line
function mymodulename_form_contact_site_form_alter(&$form, &$form_state, &$form_id) {
Hope this helps someone.
So this is the problem I am running into. If I have a comment object, I want to create a renderable array that is using the display settings of that comment. As of now this is what I have:
$commentNew = comment_load($var);
$reply[] = field_view_value('comment', $commentNew, 'comment_body', $commentNew->comment_body['und'][0]);
Which works fine because I dont have any specific settings setup for the body. But I also have image fields and video embed fields that I need to have rendered the way they are setup in the system. How would I go about doing that?
Drupal core does it with the comment_view() function:
$comment = comment_load($var);
$node = node_load($comment->nid);
$view_mode = 'full'; // Or whatever view mode is appropriate
$build = comment_view($comment, $node, $view_mode);
If you need to change a particular field from the default, use hook_comment_view():
function MYMODULE_comment_view($comment, $view_mode, $langcode) {
$comment->content['body'] = array('#markup' => 'something');
}
or just edit the $build array received from comment_view() as you need to if implementing the hook won't work for your use case.
Im in the process of integrating the Inline Registration module (http://drupal.org/project/inline_registration) with the Privatemsg module(http://drupal.org/project/privatemsg).
Issue is with passing newly created user info to Privatemsg function so that the message is authored by new user.
Offering a paid solution at http://www.freelancer.com/projects/PHP-Drupal/Drupal-Inline-Registration-Bug-Fix.html. Customized module code included there as well.
Thanks for the help.
/**
* Submit routine for inline registration form.
*/
function inline_registration_submit($form, &$form_state) {
$status_save = $form_state['values']['status'];
unset($form_state['values']['uid']);
unset($form_state['values']['status']);
user_register_submit($form, $form_state);
$form_state['values']['name'] = $form_state['user']->name;
$form_state['values']['uid'] = $form_state['user']->uid;
// $form_state['privatemsg']['author']['#value'] = $form_state['user'];
$form_state['values']['status'] = $status_save;
}
/**
* Form function for privatemsg.
*/
$form['privatemsg']['author'] = array(
'#type' => 'value',
'#value' => $user,
);
Privatemsg builds the message array/object (D7) in privatemsg_new_validate(). That is then saved in $form_state['validate_built_message']. So you need to add a second validate function that runs after the linked one and change the built message array to whatever you want.
Not really sure where exactly you want to do that, because both the new and reply form is explicitly protected against anonymous access.
I am modifying an already contributed drupal module (Inline Ajax Search) to handle searching of a specific content type with some search filters (i.e. when searching for help documentation, you filter out your search results by selecting for which product and version of the product you want help with).
I have modified the module some what to handle all the search filters.
I also added in similar functionality from the standard core search module to handle the presenting of the search form and search results on the actual search page ( not the block form ).
The problem is that when i submit the form, i discovered that I'd lose all my post data on that submit because somewhere, and i don't know where, drupal is either redirecting me or something else is happening that is causing me to lose everything in the $_POST array.
here's the hook_menu() implementation:
<?php
function inline_ajax_search_menu() {
$items = array();
$items['search/inline_ajax_search'] = array(
'title' => t('Learning Center Search'),
'description' => t(''),
'page callback' => 'inline_ajax_search_view',
'access arguments' => array('search with inline_ajax_search'),
'type' => MENU_LOCAL_TASK,
'file' => 'inline_ajax_search.pages.inc',
);
}
?>
the page callback is defined as such (very similar to the core search module's search_view function):
<?php
function inline_ajax_search_view() {
drupal_add_css(drupal_get_path('module', 'inline_ajax_search') . '/css/inline_ajax_search.css', 'module', 'all', FALSE );
if (isset($_POST['form_id'])) {
$keys = $_POST['keys'];
// Only perform search if there is non-whitespace search term:
$results = '';
if(trim($keys)) {
require_once( drupal_get_path( 'module', 'inline_ajax_search' ) . '/includes/inline_ajax_search.inc' );
// Collect the search results:
$results = _inline_ajax_search($keys, inline_ajax_search_get_filters(), "page" );
if ($results) {
$results = theme('box', t('Search results'), $results);
}
else {
$results = theme('box', t('Your search yielded no results'), inline_ajax_search_help('inline_ajax_search#noresults', drupal_help_arg()));
}
}
// Construct the search form.
$output = drupal_get_form('inline_ajax_search_search_form', inline_ajax_search_build_filters( variable_get( 'inline_ajax_search_filters', array() ) ) );
$output .= $results;
return $output;
}
return drupal_get_form('inline_ajax_search_search_form', inline_ajax_search_build_filters( variable_get( 'inline_ajax_search_filters', array() ) ) );
}
?>
from my understanding, things should work like this: A user goes to www.mysite.com/search/inline_ajax_search and drupal will process the path given in my url and provide me with a page that holds the themed form for my search module. When i submit the form, whose action is the same url (www.mysite.com/search/inline_ajax_search), then we go thru the same function calls, but we now have data in the $_POST array and one of them is indeed $_POST['form_id'] which is the name of the form "inline_ajax_search_search_form". so we should be able to enter into that if block and put out the search results.
but that's not what happens...somewhere from when i submit the form and get my results and theme it all up, i get redirected some how and lose all my post data.
if anybody can help me, it'd make me so happy lol.
drupal_get_form actually wipes out the $_POST array and so that's why I lose all my post data.
according to this: http://drupal.org/node/748830 $_POST should really be ignored when doing things in drupal. It's better to find a way around using it. One way is the way described in the link, making ur form data persist using the $_SESSION array. I'm sure there are various other and better ways to do this, but yeah, drupal_get_form was the culprit here...