Drupal Pass User Info to Privatemsg Module - *Paid - php

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.

Related

How to automatically fill other form fields after one field is filled?

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.

Sonata admin/swiftmailer how to take back information from the list

I am currently trying to use swiftmailer in my project. I am currently working on Sonata Admin and I wanted to know how I could retrieve the object displayed in a list to be able to retrieve the associated mail addresses and thus send an e-mail to all the addresses contained in this list. I want to go through the list displayed by sonata because their filter system works very well and I would use it to choose the people I want to send an email to. I saw on the symfony documentation that it was possible to send mail to an address table in this form:
$to = array('one#example.com', 'two#example.com', 'three#example.com');
$message = (new \Swift_Message('Hello Email'))
->setFrom('send#example.com')
->setTo(array($to))
->setBody('html content goes here', 'text/html');
$mailer->send($message);
But i don't know how to take back the object form the list.
From this grid.
Can you help me thanks ?
Ps :
I just think putting a button down the list to send an email to all the people displayed in the list.
Thanks a lot.
Edit :
I'm still searching and i found that the sql request was like 't0.id' and 'c0.id'. t0 and c0 are the name of the object ? Is it always that ? What is the difference between t0 and c0 ?
You can do this by adding an action to your admin list.
To do so, first create a new class in YourAdminBundle\Controller folder, extending Sonata\AdminBundle\Controller\CRUDController.
Your custom action could look like this for instance :
/** #property YourAdminClass $admin */
public function batchActionSendMail(ProxyQueryInterface $selectedModelQuery ,$type = 'sendMails') {
if (false === $this->admin->isGranted('EDIT')) {
throw new AccessDeniedException();
}
/* selected objects in your list !! */
$selectedModels = $selectedModelQuery->execute();
try{
foreach ($selectedModels as $selectedModel){
// your code to retrieve objects mails here (for instance)
}
//code to send your mails
}
catch(\Exception $e)
{
$this->addFlash('sonata_flash_error', "error");
}
$this->addFlash('sonata_flash_success', 'mails sent')
return new RedirectResponse($this->admin->generateUrl('list'));
}
To make this custom CRUD controller active, go to services.yml, get to your class admin block, and complete the third param of arguments property by referencing your custom CRUD controller:
arguments: [null, YourBundle\Entity\YourEntity,YourAdminBundle:CustomCRUD]
Finally, to allow you to use your custom action, go to your Admin Class and add this function :
public function getBatchActions()
{
if ($this->hasRoute('edit')) {
$actions['sendMails'] = array(
'label' => $this->trans('batch.sendMails.action'),
'ask_confirmation' => true, // by default always true
);
}
return $actions;
}
The action will be available in the dropdown list at the bottom of your admin list, next to the "Select all" checkbox.

Drupal 8 - Reading node fields values within a custom module

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.

Moodle cohort_add_cohort error

I'm developing a custom Moodle authentification plugin for Moodle 2.7.
When a user is authenticated I want them to be added to a specific cohort. If that cohort does not exist I need it to be created automatically. I use the user_authenticated_hook() function in my authentification plugin to achieve this.
My code for creating the cohort is this
$data = new stdClass();
$data->name = 'Name string';
$data->idnumber = 'ID string';
$data->description = 'Description string';
$cohortId = cohort_add_cohort($data);
I have included cohort/lib.php in the auth.php file and I have declared the global variables $DB, $CFG and $SESSION at the first line of the user_authenticated_hook() function.
The authentification works without the part about cohorts. But with the cohort part in place authentication fails and I am redirected to the login page.
The page title is changed to "Error" but that is the only error message I get.
What Am I doing wrong? I hope somebody will be able to help me create cohorts and add members.
It might be because the global $USER object doesn't exist yet or hasn't been populated.
Do you have debug switched on in your config.php?
$CFG->debug = 32767;
$CFG->debugdisplay = 1;
It might be better to respond to the user_created event. So if a user is created by another method, they will still be added to the cohort. eg:
Create a local plugin eg:
/local/add_cohorts
Create an events.php
/local/add_cohorts/db/events.php
Which has something like this
$handlers = array (
'user_created' => array (
'handlerfile' => '/local/add_cohorts/lib.php',
'handlerfunction' => 'local_add_cohorts_user_created',
'schedule' => 'instant',
'internal' => 1,
),
);
Then in /local/add_cohorts/lib.php have
function local_add_cohorts_user_created($user) {
// Do your cohort processing here and add the user
// Use $user->id to add to the cohort members
}
Then create a version.php and install the plugin, then the event handler will be registered.
Events api - https://docs.moodle.org/dev/Events_API

How to send new password from Magento CSV import of Customers

We have been trying to modify the Customer.php file ( import/export ) to get it to send out the new account details automatically as it imports the customers from a CSV file.
We are working in the right area as we dropped a simple mail() call which was called (we received the emails) for every new row. The problem arises when trying to get it to generate a new random password and send out the new account details - it never sends any mail and we cannot figure out why! Code follows ( Edited from app/code/local/Mage/ImportExport/Model/Import/Entity/Customer.php )
/**
* Update and insert data in entity table.
*
* #param array $entityRowsIn Row for insert
* #param array $entityRowsUp Row for update
* #return Mage_ImportExport_Model_Import_Entity_Customer
*/
protected function _saveCustomerEntity(array $entityRowsIn, array $entityRowsUp)
{
if ($entityRowsIn) {
$this->_connection->insertMultiple($this->_entityTable, $entityRowsIn);
// BEGIN: Send New Account Email
$cust = Mage::getModel('customer/customer');
$cust->setWebsiteId(Mage::app()->getWebsite()->getId());
foreach($entityRowsIn as $idx => $u){
// Failed
$cust->loadByEmail($u['email']);
$cust->setConfirmation(NULL);
$cust->setPassword($cust->generatePassword(8));
$cust->save();
$cust->sendNewAccountEmail();
//$cust->sendPasswordReminderEmail(); // this call doesnt work either
}
// END: Send New Account Email
}
if ($entityRowsUp) {
$this->_connection->insertOnDuplicate(
$this->_entityTable,
$entityRowsUp,
array('group_id', 'store_id', 'updated_at', 'created_at')
);
}
return $this;
}
Inorder to improve performance magento 'caches' object, so when trying to load an object in a loop you either need to load a new instance or call it reset() method
$website_id = Mage::app()->getWebsite()->getId();
foreach($entityRowsIn as $idx => $u){
$cust = Mage::getModel('customer/customer');
$cust->setWebsiteId($website_id);
$cust->loadByEmail($u['email']);
$cust->setPassword($cust->generatePassword(8));
$cust->save();
$cust->sendNewAccountEmail(); // if you are getting 2 email then remove this line
}
If you are load a large number of customers then you may run in to memory issues and my need to look a other technique using reset()
If this code is being run from the Administration section of Magento then you will need to make sure that you set the correct Website ID ( Mage::app()->getWebsite()->getId() will return the incorrect one ).
From the front end this code will work fine but for Admin work you should use '1' or whatever your Front end websites ID is as the getId() method was returning '0' in the Admin area! Small gotcha but had me going for hours!
I had found this script on how to Auto generate password for existing customers
$passwordLength = 10;
$customers = Mage::getModel('customer/customer')->getCollection();
foreach ($customers as $customer){
$customer->setPassword($customer->generatePassword($passwordLength))->save();
$customer->sendNewAccountEmail();
}

Categories