Interaction between two forms in a single controller - forms

I'm trying to work with two forms in a single controller in Symfony2. The page is displaying a list of e-mail addresses with checkboxes to select them.
The first form is a research form and the second is used to remove e-mail addresses. There is also a pagination in my page.
My problem is that I can't remove an e-mail address with a research when the e-mail address is not displayed in the first page.
public function emailsAction(Request $request, $paginationParams)
{
$searchForm = $this->createForm(new SearchFormType(), null, array());
$searchForm->handleRequest($request);
if ($searchForm->isValid()) {
// FETCH E-MAILS WITH SEARCH
} else{
// FETCH E-MAILS WITHOUT SEARCH
}
// here I slice the result depending on the pagination params
$removeForm = $this->createForm(new RemoveFormType(), null, array(
'emails' => $emails
));
$removeForm->handleRequest($request);
if ($removeForm->isValid())
{
$formData = $removeForm->getData();
// here I remove the e-mails
}
...
$params['remove_form'] = $manageSubscribersForm->createView();
$params['search_form'] = $searchAbonneActuForm->createView();
return $this->renderView('my_template.html.twig', $params);
}
If I understand it correctly, the problem is that my removeForm is created with the spliced array and without the search applied when handling the removeForm.
When I search for a name, say johnsmith, it displays me on page 1, one result which is johnsmith#email.com.
If johnsmith#email.com is on page 2 without search, the removeForm handling my request is created with a spliced array not containing johnsmith, so the removeForm is not considered valid.
How should I do to create my removeForm, taking account of the search done before when submitting the removeForm? Or maybe I'm doing this wrong ?
I'm not a native english speaker so if anything is not clear, feel free to ask.

You can use a hidden field with the current page index, that will help you make your search again.
Or you can use an event listener to modify the form field before the submission for the validation.

Related

How to get the "body" and "subject" fields of a draft when extending compose UI?

We are developing a Gmail Addon in which we extend the compose UI.
This extends the compose window in which you can compose your e-mail.
We need the 'From', 'To', 'Subject' and 'Body' of the message that is being composed.
The 'From' can be read from the Session object like this
var mySelf = Session.getEffectiveUser().getEmail();
The 'To' can be read from the draftMetadata from the event object of the function being called.
function composeEmail(event) { console.log(event.draftMetadata.toRecipients); }
The 'Subject' and 'Body' can't be read from the event object of the function since it is a composeTrigger. The argument contains these objects:
{
formInput = {},
clientPlatform = web,
formInputs = {},
parameters = {},
draftMetadata = {
toRecipients = [test #test.com],
subject = ,
bccRecipients = [],
ccRecipients = []
}
}
Surprisingly to me, the subject key is there but not being filled in (yes I did type in a subject).
Question:
How can I get the 'Subject' and 'Body' of the E-mail being composed by the user in the extended composer UI?
Extra information:
The contextual trigger action contains the following object as event object:
{
clientPlatform = web,
messageMetadata = {
messageId = 16e agg7323451256989f68,
accessToken = AAGdOAawdaAOW8PWchmdawdk0N13STKnBPMAOXVjZVHyQMfAawdBtgEIrS6N8y5h2BOZnKFPlfsl5VBsyPiF7YiONOoP7XVjKZawdi - E6vI - jVU92dPmfj3RNmXfawdawdeaNMrXehAFLm
}
}
By reading an email through the contextual trigger a messageId is being added in which the getBody and getSubject methods can be used.
As of now, the Compose Trigger Event never returns the value of the subject field.
I have filled a bug for this here. Click the ★ icon to follow this Issue and get updates. This will also help prioritize this Issue.
As a workaround, you can use the contextual trigger to:
Get the messageId
Find drafts that have that messageId associated to them
Get the draft by their draftId
Fetch the subject line from the Headers object on the draft.
This only works on drafts that are replying to a specific message.
I've never done this before so this is a guess. I looked at the compose dialog html with the developer tools and this is what I noticed.
There seem to be a bunch of hidden inputs that are used to store values that are typed into the compose dialog. So I would try something like:
formInputs.body or perhaps formInput.body taking the name of the key from names of this hidden elements. This is just a guess.

How to auto load last submission (single submission)?

I built multiple webforms in Drupal. I want user to
Submit only ONE submission by form.
Auto load last submission when they go again on webform submitted.
How can I do this?
You could use the email webform component, set it as unique and check the User email as default, if you'd have one in your webform.
Autoloading a webform submission might be possible with by creating a views block with a contextual filters to the user giving the uid provided & a relation to webform.
As you might not want an additional webform component for your webforms (or not all of them), you could always create a module, include the webform functionality and retrieve the submitted data on a webform instance with hook_form_alter() as:
/**
* Implements hook_form_alter().
*/
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
// get current user
global $user;
// include webform functionality
module_load_include('inc','webform','includes/webform.submissions');
// make sure to only alter webform forms
if (strpos($form_id, 'webform_client_form_') !== FALSE) {
// check if the user is a an authenticated user
if (in_array('authenticated user', $user->roles)) {
// build $filters array for submission retrieval
$filters = array(
'nid' => $form['#node']->webform['nid'],
'uid' => $user->uid,
);
/**
* When not using a unique webform component for 1 submission
* you can use a submission of the user on a webform instance
* to prevent another submission.
*/
// get submissions of the user by webform nid
if ($submissions = webform_get_submissions($filters)) {
// disable the form to limit multiple submissions per instance
$form['#disabled'] = TRUE;
/**
* Webform instance submission data of the current user
* can be found in $submissions[1]->data array
*/
# render your submission with Form api
}
}
}
}
Hope this helps.
Limiting to only 1 submission per webform can be done via Webform -> Form Settings -> Total Submissions Limit and Per User submission limit as shown in this screenshot
To autoload user submission, since above would not allow you to show the webform would be via using the submission id of the webform they already submitted. Based on this code
module_load_include('inc','webform','includes/webform.submissions');
$sid = 10;
$submission = webform_get_submissions(array('sid' => $sid));
$nid = $submission[$sid]->nid;
$web_submission = webform_get_submission($nid, $sid);
$node = node_load($nid);
$output = webform_submission_render($node, $web_submission, NULL, 'html');
print $output;

Mandrill mergetags: send email only when all merge tags are replaced

This question is related to this Check email template after meta tag replacement and before sending in Mandrill.
I would like to know if there is a way to configure the Mandrill to send an email only when all the merge tags in the email template have been replaced. Is this possible?
AFAIK this isn't possible to configure with Mandrill.
You can (maybe should) perform this using the API however - take advantage of the render method to pre-render the outgoing email, and then look for any un-replaced fields.
function has_merge_tags($string)
{
return ( strpos("|*", $string) === false AND strpos("*|", $string) === false);
}
function send_email($template_code, $merge_fields)
{
$mandrill = new Mandrill(APIKEY);
// pre-render the template with the merged fields
$result = $mandrill->templates->render($name, array(), $merge_fields);
if (has_merge_tags($result['html']))
{
// throw exception, log it, whatever
}
really_send_email($result['html']);
}
https://mandrillapp.com/api/docs/templates.php.html#method=render

Field validations in sugarcrm

I just started using SugarCRM CE for the first time (Version 6.5.15 (Build 1083)). I'm quite impressed with the ease of use when adding new fields or modules, but there's one quite indispensable thing that seems to be missing: Validation of user input.
I would for example like to check a lot of things:
Check if a emailadres has a valid format, using some regular expression
Check if a postalcode exists (maybe do a webswervice call to validate it)
Do a calculation to see if a citizen service number is valid
etc.
The only thing I seem to be able to do in studio is make a field required or not, there doesn't seem to be any standard way to execute a validation on a field.
All I can find when I google on it is lots of ways to hack into the source code, like this one: http://phpbugs.wordpress.com/2010/01/22/sugarcrm-adding-javascript-validation-on-form-submit/ And even then I don't find any examples that actually do a validation.
Am I just missing something? Or is editing source code the only way to add this?
I don't think the "standard" validations are available in the CE edition.
What surprises me is that you can't define a validation somewhere and attach it to a field. I kind of expected this, since the rest of the system is very well structured (modules, packages, etc..)
I now for instance created a 11-check, this is a very specific check for a dutch bank account number. to get this to work, I did the following (based upon examples I found googling around):
I added the bank account to contacts in studio and after that edited \custom\modules\Contacts\metadata\editviewdefs.php
I added the following snippets:
'includes'=> array(
array('file'=>'custom/modules/Contacts/customJavascript.js')),
array (
0 =>
array(
'customCode' =>
'<input title="Save [Alt+S]" accessKey="S" onclick="this.form.action.value=\'Save\'; return check_custom_data();" type="submit" name="button" value="'.$GLOBALS['app_strings']['LBL_SAVE_BUTTON_LABEL']>',
),
1 =>
array(
'customCode' =>
'<input title="Cancel [Alt+X]" accessKey="X" onclick="this.form.action.value=\'index\'; this.form.module.value=\''.$module_name.'\'; this.form.record.value=\'\';" type="submit" name="button" value="'.$GLOBALS['app_strings']['LBL_CANCEL_BUTTON_LABEL'].'">'
)
),
And in customJavascript.js i placed this code:
function check_custom_data()
{
if (!eleven_check(document.getElementById("bankaccount_c").value)){
alert ('Bank account not valid');
return false;
} else {
return check_form('EditView');
}
function eleven_check(bankaccount) {
bankaccount=bankaccount.replace(/\D/, "");
charcount=bankaccount.length;
var som=0;
for (i=1; i<10; i++) {
getal=bankaccount.charAt(i-1);
som+=getal*(10-i);
}
if (som % 11==0 && charcount==9) {
return true
} else {
return false
}
}
}
This check now works the way I want it to work, but I'm wondering if this is the best way to add a validation. this way of adding a validation doesn't however accommodate PHP validations, for instance, if I want to validate against some data in the database for one or another reason, I would have to use ajax calls to get that done.
Email validation is in the pro edition, I had assumed it was in CE as well but I'm not 100% sure.
The other 2 are a lot more specific - postcode validation would depend upon your country so would be difficult to roll out. For these you will need to write your own custom validation.
I know its late, but maybe still someone needs this.
You can just add your custom javascript validation as a callback in your vardefs like this:
'validation' =>
array (
'type' => 'callback',
'callback' => 'function(formname,nameIndex){if($("#" + nameIndex).val()!=999){add_error_style(formname,nameIndex,"Only 999 is allowed!"); return false;}; return true;}',
),
I documented it here as its not well documented elsewhere:
https://gunnicom.wordpress.com/2015/09/21/suitecrm-sugarcrm-6-5-add-custom-javascript-field-validation/
You can add custom validation code to the following file: ./custom/modules/.../clients/base/views/record/record.js
There you can add validation code. In this example, I will validate if the phone_number is not empty when an accounts has a customer-type:
EXAMPLE CODE IN RECORD.JS:
({
extendsFrom: 'RecordView',
initialize: function (options) {
app.view.invokeParent(this, {type: 'view', name: 'record', method: 'initialize', args:[options]});
//add validation
this.model.addValidationTask('check_account_type', _.bind(this._doValidateCheckType, this));
},
_doValidateCheckType: function(fields, errors, callback) {
//validate requirements
if (this.model.get('account_type') == 'Customer' && _.isEmpty(this.model.get('phone_office')))
{
errors['phone_office'] = errors['phone_office'] || {};
errors['phone_office'].required = true;
}
callback(null, fields, errors);
}
})
Don't forget to repair en rebuild!
The full documentation can be found here

How do I clear one set of errors on a two form page in zend

I have a one page website that has two seperate forms that need to be posted back to the same page, the problem being, that if I submit one form, the error checking is done on both, so displays error messages for both. What I need is that if form one is submit, only form ones' error messages appear, and not form twos. Is this possible in zend?
It isn't a problem for zend to do - but it is a problem for you to solve!
If you give your form a hidden field, or if you have a field ID unique to one form, you should be able to check which form has been submitted in your controller, then you tell zend which form you want it to check. Something like the following should do the job, it will check for a field with the ID unique_form_one_field which obviously should only be on form one, this could be a hidden field for example:
// Get the forms:
$form1 = $this->_helper->formLoader('form_one');
$form2 = $this->_helper->formLoader('form_two');
// Check if there is a POST:
if (!$request->isPost())
{
// It isn't show the forms:
$this->view->form_one = $form1;
$this->view->form_two = $form2;
}
else
{
// It is, get the POST data:
$post_data = $request->getPost();
// Check if form one has been submitted:
if (isset($post_data['unique_form_one_field']))
{
// Check if form one is valid:
if (!$form1->isValid($post_data))
{
// Its got an error, display the forms again, form one will now be populated with the data and also the error messages:
$this->view->form_one = $form1;
$this->view->form_two = $form2;
}
else
{
// Form one was valid - do what you want to process it:
}
}
else
{
// Check if form two is valid:
if (!$form2->isValid($post_data))
{
// Its got an error, display the forms again, form two will now be populated with the data and also the error messages:
$this->view->form_one = $form1;
$this->view->form_two = $form2;
}
else
{
// Form two was valid - do what you want to process it:
}
}
}