Powershell Error Validation - powershell

Function Button_Click()
{
Param([Parameter(Mandatory=$True)]
$telephone,
$calledtoSee,
$wantstoSeeyou,
$pleaseCall,
$willcallAgain,
$returningYourCall,
$ToSelection,
$from,
$telephoneNumber,
$message)
[boolean]$okayContinue=$true
[string]$radioSelectedText
[string]$comboBoxSectionText
[string]$persontoEmail
$callType
$messageCount
$comboBoxSectionText = $ToSelection.GetItemText($ToSelection.SelectedItem)
if($okayContinue){
if($comboBoxSectionText -eq "Please Select Contact"){
[System.Windows.Forms.MessageBox]::Show("Please Select Recipient")
$okayContinue=$false
}
}
if($okayContinue){
if([string]::IsNullOrWhiteSpace($from.Text)){
[System.Windows.Forms.MessageBox]::Show("Please Enter Who The Message is From")
$from.focus()
$okayContinue=$false
}
}
if($okayContinue){
if([string]::IsNullOrWhiteSpace($telephoneNumber.Text)){
[System.Windows.Forms.MessageBox]::Show("Please Enter Telephone Number")
$telephoneNumber.focus()
$okayContinue=$false
}
}
#######################################################################################################################################################
if($okayContinue){
if($telephone.Checked){
$callType = $telephone.Text
}
elseif($calledtoSee.Checked){
$callType = $calledtoSee.Text
}
elseif($wantstoSeeyou.Checked){
$callType = $wantstoSeeyou.Text
}
elseif($pleaseCall.Checked){
$callType= $pleaseCall.Text
}
elseif($willcallAgain.Checked){
$callType = $willcallAgain.Text
}
elseif($returningYourCall.Checked){
$callType = $returningYourCall.Text
}
else{
[System.Windows.Forms.MessageBox]::Show("Please Select Call Type")
$okayContinue=$false
}
}
if($okayContinue){
if([string]::IsNullOrWhiteSpace($message.Text)){
[System.Windows.Forms.MessageBox]::Show("Please Enter Message")
$okayContinue=$false
}
}
if($okayContinue){
$buildPerson=$comboBoxSectionText.Split(',')
$personObject = [pscustomobject]#{
FirstName = $buildPerson[0]
LastName = $buildPerson[1]
Email = $buildPerson[2]
}
$messageObject = [pscustomobject]#{
Message = $message.Text
MessageFor = $personObject
From = $from.Text
CallType = $callType
Telephone = $telephoneNumber.Text
}
}
I've got a form with 6 radio buttons, and 2 text boxes, and a combobox. Now, in terms of error validation, I decided to use a boolean value and check to see that the textboxes are properly filled and that a recipient has been selected. After everything has been filled in, then an object is created.
Am I on the right track when it comes to error validation? Could I be handling it better?

If you want full programmatic control over validation, or need to perform complex validation checks, you should use the validation events built into most Windows Forms controls. Each control that accepts free-form user input has a Validating event that will occur whenever the control requires data validation. In the Validating event-handling method, you can validate user input in several ways. Have a look to Event-Driven Validation. And More explanations here : Extending Windows Forms with a Custom Validation.

Related

Googlesheets: I need to assign a script to textbox that sends an email to an email address located in another spreadsheet

I'm sure this will be a frustrating post for some and I'm very sorry. I don't have any coding background and this will be one of the first scripts I've ever attempted. Thank you again for the help!
What I need to accomplish is to assign a script to a text box that sends an email with the address located in another spreadsheet.
Here is the setup: Picture 1. This is the spreadsheet and tab where I want the email address to be sent from using the textbox (with the E) located to the right of the "In-Game Name"
Picture 1.) http://imgur.com/a/8nVzl
The "In-Game Name" is already being imported from a separate spreadsheet. I have the url for this separate spreadsheet located in a separate tab of the current spreadsheet as you can see by Picture 2.
Picture 2 (left-side) and picture 3 (right-side) because my reputation isn't 10: http://imgur.com/a/q2bsH
You can see the data I'm importing from the second spreadsheet in picture 3 ("in-game name" and "prestige". I do not want to have the email address imported in this manner however.
I would like a script that sends an email from the main spreadsheet and pulls the email address from the second using the spreadsheet key url in the "Player Key Input" tab.
I have a sample of code that tries to accomplish this is currently only serving as comedic relief to angst from this matter.
Once again, I'm sorry if this was a poorly written/explained question. I'm awful with coding. I really appreciate any input!
We were able to get this to work using this script:
/**
* This is a utility function that sends an email.
* It requires a To address, a Subject, and the message Body.
*/
function sendEmail(to, subject, body) {
// The Reply To address is the default address that appears when a user replies to the email.
// If not set to a bogus email, it probably defaults to the owner of the sheet!
var replyTo = "donotreply#mail.com"
// Send the email!
MailApp.sendEmail(to, replyTo, subject, body)
}
/**
* This function is an example of a boilerplate message that you can send.
* You could duplicate this function for other types of messages.
*/
function sendAllianceMessageToUser(row) {
var user = getUserInfoFromRow(row);
sendEmail(user.email, "MCOC Alert", user.name+",\n\nPlease log on to MCOC and check AQ/AW!");
}
/**
* This utility function will retrieve a user's info when supplied with a row number.
* The row number must match the rows on the "Roster/Prestige" sheet.
* This function will not need to change unless the structure of the sheets change.
*/
function getUserInfoFromRow(row) {
// Keep a reference to the current active sheet
//var sheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.openById('1McfUWHPCgh7XWtLgZX6mcnLs_o1MQprBOKbHiwNsVEo').getSheetByName('Roster/Prestige');
// Grab the sheet key in the row that was provided. (In this case, column L)
//var skey = sheet.getRange('L'+row).getValue();
var skey = sheet.getRange('L4').getValue();
Logger.log(skey);
// Open the remote sheet using the ID that was retrieved earlier.
var remote = SpreadsheetApp.openById(skey).getSheetByName('Sheet1');
// Grab the necessary cell values
var ign = remote.getRange('C2').getValue();
var email = remote.getRange('C4').getValue();
var user = new Object();
user.name = ign;
user.email = email;
user.sheet_key = skey;
return user;
}
/**
* These functions are generic image click handlers for each image.
* Each image will call a function based on which row it is placed over.
* MOVING IMAGES WILL BREAK THIS!
*/
function row3_clicked() { sendAllianceMessageToUser('3'); }
function row4_clicked() { sendAllianceMessageToUser('4'); }
function row5_clicked() { sendAllianceMessageToUser('5'); }
function row6_clicked() { sendAllianceMessageToUser('6'); }
function row7_clicked() { sendAllianceMessageToUser('7'); }
function row8_clicked() { sendAllianceMessageToUser('8'); }
function row9_clicked() { sendAllianceMessageToUser('9'); }
function row10_clicked() { sendAllianceMessageToUser('10'); }
function row11_clicked() { sendAllianceMessageToUser('11'); }
function row12_clicked() { sendAllianceMessageToUser('12'); }
function row13_clicked() { sendAllianceMessageToUser('13'); }
function row14_clicked() { sendAllianceMessageToUser('14'); }
function row15_clicked() { sendAllianceMessageToUser('15'); }
function row16_clicked() { sendAllianceMessageToUser('16'); }
function row17_clicked() { sendAllianceMessageToUser('17'); }
function row18_clicked() { sendAllianceMessageToUser('18'); }
function row19_clicked() { sendAllianceMessageToUser('19'); }
function row20_clicked() { sendAllianceMessageToUser('20'); }
function row21_clicked() { sendAllianceMessageToUser('21'); }
function row22_clicked() { sendAllianceMessageToUser('22'); }
function row23_clicked() { sendAllianceMessageToUser('23'); }
function row24_clicked() { sendAllianceMessageToUser('24'); }
function row25_clicked() { sendAllianceMessageToUser('25'); }
function row26_clicked() { sendAllianceMessageToUser('26'); }
function row27_clicked() { sendAllianceMessageToUser('27'); }
function row28_clicked() { sendAllianceMessageToUser('28'); }
function row29_clicked() { sendAllianceMessageToUser('29'); }
function row30_clicked() { sendAllianceMessageToUser('30'); }
function row31_clicked() { sendAllianceMessageToUser('31'); }
function row32_clicked() { sendAllianceMessageToUser('32'); }
function test() {
sendAllianceMessageToUser('4'); // Testing!
}
The question "To pull the email address from another spreadsheet" I would use a formula to have it copied over. Then assign a script to email the address. I am not sure how you would pull info from another sheet via script.
The below formula will pull the spreadsheet data that is in A1 to the cell you assign.
=IMPORTRANGE("YOURSHEETID","Sheet1!A1:A")

To stop form submit on every refresh after one submit in codeigniter

After form submission , any number of refresh is storing the data that many times in the db.
ie. !empty($_POST) is always true after on submission.
How can I stop the submission without redirecting the page/url. As I want to stay in the same page.
I am using form_open() and form_submit() i codeigniter.
in view
<?php echo form_open("",array('method' => 'POST'));?>
/* form fields */
'Send', 'value' => 'Send Notifications',"name"=>"send_notification")); ?>
in controller
`if (!empty($_POST['send_notification'])) {
/* validation rules & data*/
if ($this->form_validation->run() == TRUE){
$this->model->insert($data);
}
}`
How can I stop the duplicate record insertion, I have tried , unset($_POST) , isset() , if($this->input->post()) , nothing seems to work.
Just do a redirect(); to the same age after the insert function.
This worked for me. It may help someone
Controller file :
public function success()
{
$_SESSION['txnid'] = $this->input->post('txnid');
$this->bind->set_order();
$this->load->view('success');
}
Model file :
public function set_order()
{
$txnid = $_SESSION['txnid'];
$qry = $this->db->query("SELECT * from orders where transaction_id = '$txnid'");
$result = $qry->result_array();
if($qry->num_rows() == 0 )
{
//add to database here
}
else
{
// do nothing
}
}
I am adding txnid to database on submit. So if it tries to resubmit, it checks if txnid already exist or not.

Send Email fields not rendering in Sitecore Web Forms For Marketers

I have an issue with the WFFM Send Email Message save action (Sitecore 6.5.0). I'm trying to send an email that includes the form placeholders from the "Insert Field" dropdown in the Send Email editor. Sometimes the fields will render correctly, but most times the email will include the placeholder text instead of the field's actual value.
For example, this is the email that is coming through:
First Name: [First Name]
Last Name: [Last Name]
Email: [Email Address]
Company Name: [Company Name]
Phone Number: [Phone Number]
I think it has to do with the Send Email editor using a rich text editor for the email template, but I've tried adjusting the message's HTML to no avail. This is what the markup looks like: (the <p> tags and labels used to be inline, but that didn't work either)
<p>First Name:
[<label id="{F49F9E49-626F-44DC-8921-023EE6D7948E}">First Name</label>]
</p>
<p>Last Name:
[<label id="{9CE3D48C-59A0-432F-B6F1-3AFD03687C94}">Last Name</label>]
</p>
<p>Email:
[<label id="{E382A37E-9DF5-4AFE-8780-17169E687805}">Email Address</label>]
</p>
<p>Company Name:
[<label id="{9C08AC2A-4128-47F8-A998-12309B381CCD}">Company Name</label>]
</p>
<p>Phone Number:
[<label id="{4B0C5FAC-A08A-4EF2-AD3E-2B7FDF25AFA7}">Phone Number</label>]
</p>
Does anyone know what could be going wrong?
I have encountered this issue before, but was using a custom email action. I managed to fix it by not using the deprecated methods in the SendMail class and instead using the
Sitecore.Form.Core.Pipelines.ProcessMessage namespace's ProcessMessage and ProcessMessageArgs classes.
My use case was a little more complicated than yours, as we were also attaching a PDF brochure to our message (which is why we were using the custom email action in the first place), but here is the code:
public class SendBrochureEmail : SendMail, ISaveAction, ISubmit
{
public new void Execute(ID formId, AdaptedResultList fields, params object[] data)
{
try
{
var formData = new NameValueCollection();
foreach (AdaptedControlResult acr in fields)
{
formData[acr.FieldName] = acr.Value;
}
var senderName = formData["Your Name"];
var emailTo = formData["Recipient Email"];
var recipientName = formData["Recipient Name"];
var documentTitle = formData["Document Title"];
if (documentTitle.IsNullOrEmpty())
{
documentTitle = String.Format("Documents_{0}", DateTime.Now.ToString("MMddyyyy"));
}
Subject = documentTitle;
if (!String.IsNullOrEmpty(emailTo))
{
BaseSession.FromName = senderName;
BaseSession.CatalogTitle = documentTitle;
BaseSession.ToName = recipientName;
var tempUploadPath = Sitecore.Configuration.Settings.GetSetting("TempPdfUploadPath");
var strPdfFilePath =
HttpContext.Current.Server.MapPath(tempUploadPath + Guid.NewGuid().ToString() + ".pdf");
//initialize object to hold WFFM mail/message arguments
var msgArgs = new ProcessMessageArgs(formId, fields, MessageType.Email);
var theDoc = PdfDocumentGenerator.BuildPdfDoc();
theDoc.Save(strPdfFilePath);
theDoc.Clear();
FileInfo fi = null;
FileStream stream = null;
if (File.Exists(strPdfFilePath))
{
fi = new FileInfo(strPdfFilePath);
stream = fi.OpenRead();
//attach the file with the name specified by the user
msgArgs.Attachments.Add(new Attachment(stream, documentTitle + ".pdf", "application/pdf"));
}
//get the email's "from" address setting
var fromEmail = String.Empty;
var fromEmailNode = Sitecore.Configuration.Factory.GetConfigNode(".//sc.variable[#name='fromEmail']");
if (fromEmailNode != null && fromEmailNode.Attributes != null)
{
fromEmail = fromEmailNode.Attributes["value"].Value;
}
//the body of the email, as configured in the "Edit" pane for the Save Action, in Sitecore
msgArgs.Mail.Append(base.Mail);
//The from address, with the sender's name (specified by the user) in the meta
msgArgs.From = senderName + "<" + fromEmail + ">";
msgArgs.Recipient = recipientName;
msgArgs.To.Append(emailTo);
msgArgs.Subject.Append(Subject);
msgArgs.Host = Sitecore.Configuration.Settings.MailServer;
msgArgs.Port = Sitecore.Configuration.Settings.MailServerPort;
msgArgs.IsBodyHtml = true;
//initialize the message using WFFM's built-in methods
var msg = new ProcessMessage();
msg.AddAttachments(msgArgs);
msg.BuildToFromRecipient(msgArgs);
//change links to be absolute instead of relative
msg.ExpandLinks(msgArgs);
msg.AddHostToItemLink(msgArgs);
msg.AddHostToMediaItem(msgArgs);
//replace the field tokens in the email body with the user-specified values
msg.ExpandTokens(msgArgs);
msg.SendEmail(msgArgs);
//no longer need the file or the stream - safe to close stream and delete delete it
if (fi != null && stream != null)
{
stream.Close();
fi.Delete();
}
}
else
{
Log.Error("Email To is empty", this);
throw new Exception("Email To is empty");
}
}
catch (Exception ex)
{
Log.Error("Test Failed.", ex, (object) ex);
throw;
}
finally
{
BrochureItems.BrochureItemIds = null;
}
}
public void Submit(ID formid, AdaptedResultList fields)
{
Execute(formid, fields);
}
public void OnLoad(bool isPostback, RenderFormArgs args)
{
}
}
It is very possible that the Email Action that WFFM ships with is using the deprecated methods, which could be your problem. I do not have time to look into it, but you can decompile the DLL and look to see what their Email Action is doing. Regardless, the above code should work out of the box, save for updating the fields to those that you are using and removing the code for attaching the PDF, should you choose to not have attachments.
Good luck, and happy coding :)
If you change a field on the form in any way (caption, name, type, etc) the link will change and you need to re-insert the placeholder and move it up to its location in your expected email. This is also true if you duplicate a form. You'll have to reinsert all the fields in the email or you will just get the outcome you show above.
Reinserting upon a change will ensure the value is collected!

Need Help with Zend Form dropdown menu validation

I'm working on a zend framework project and I needed the user to select school and then it goes to the next form then select the grade.
Eg User select ABC High School and then select "Grade 8"
Both School and Grade dropdown menu is soft coded fetching the data from the database.
My problem is that when the user selected a school and then on the next grade form if they don't select any values and click onto "submit" it return a validation error "Value is required and can't be empty" which is correct but the dropdown menu then goes empty.
I wanted to know how to repopulate the values back to the grade dropdown menu if the form doesn't validate.
Thanks so much
Here is my code
Here is the function i generate the grade values (Fetching from the database)
public function processSchoolSelectionAction()
{
$form = $this->getSchoolSelectionForm();
if ($form->isValid($_POST))
{
// getting the values
$schoolId = $form->getValue('school');
$schoolYear = new Application_Model_DbTable_SchoolYear();
$schoolYearValues = $schoolYear->getYearValues($schoolId);
array_unshift($schoolYearValues, array ('key' =>'' , 'value' =>'Please Specify'));
$form = $this->getYearSelectionForm();
$form->year->addMultiOptions($schoolYearValues);
$form->schoolId->setValue($schoolId);
$this->view->form = $form;
}
else
{
$data = $form->getValues();
$form->populate($data);
$this->view->form = $form;
}
}
Code processing the year selection form
public function processYearSelectionAction()
{
$form = $this->getYearSelectionForm();
if ($form->isValid($_POST))
{
// getting the values
$schoolId = $form->getValue('schoolId');
$yearId = $form->getValue('year');
$textbookList = new Application_Model_DbTable_TextbookList();
if ($textbookList->checkTextbookExist($schoolId, $yearId))
{ // check if textbookExist
}
else
{
$this->view->message = "Sorry, But the list you requested is currently not available for ordering online.";
}
}
else
{
$data = $form->getValues();
$form->populate($data);
$this->view->form = $form;
}
}
School selection form
<?php
class Application_Form_SchoolSelection extends ZendX_JQuery_Form
{
public function init()
{
$this->setName('schoolSelection');
$school = new Application_Model_DbTable_School;
$schoolValues = $school->getSchoolValues();
array_unshift($schoolValues, array ('key' =>'' , 'value' =>'Please Specify'));
$schoolElement = new Zend_Form_Element_Select('school');
$schoolElement->addMultiOptions($schoolValues);
$schoolElement->setLabel('School');
$schoolElement->setRequired(true);
$schoolElement->setRegisterInArrayValidator(false);
$submitElement = new Zend_Form_Element_Submit('submit');
$submitElement->setLabel("Next");
$this->addElements(array(
$schoolElement,
$submitElement
));
}
}
?>
Grade (Year) selection form
<?php
class Application_Form_YearSelection extends ZendX_JQuery_Form
{
public function init()
{
$this->setName('yearSelection');
$yearElement = new Zend_Form_Element_Select('year');
$yearElement->setLabel('Year');
$yearElement->setRequired(true);
$yearElement->setRegisterInArrayValidator(false);
$schoolIdElement = new Zend_Form_Element_Hidden('schoolId');
$submitElement = new Zend_Form_Element_Submit('submit');
$submitElement->setLabel("Next");
$this->addElements(array(
$yearElement,
$schoolIdElement,
$submitElement
));
}
}
?>
This is how I done that:
In Controller when form is creating, pass data from request:
$some_selected_data = $this->_getParam('param_from_request'); // you need to validate this
$form = new Application_Form_SchoolSelection( array('some_data' => $some_selected_data) );
Then, in Form Class get that value like this:
$data = $this->getAttrib('some_data'); // the key value of array above
and just ask
if($data) {
// get value from DB and
//SET VALUE TO Zend_Form_Element
}
Obviously, you need to repopulate the options of your Select field.
In your processYearSelectionAction, on the validation failure part just grab the schoolId you stored in the hidden field and use it the same way as you did in your processSchoolSelectionAction to populate your field options.

Drupal 6: Modifying uid of a submitted node

I have a situation where I want a set of users (employees) to be able to create a node, but to replace the uid (user ID) with that of the users profile currently displayed.
In other words, I have a block that that calls a form for a content type. If an employee (uid = 20) goes to a clients page (uid =105), and fills out the form, I want the uid associated with the form to be the client's(105), not the employee's.
I'm using arg(1) to grab the Client's uid - here is what I have..
<?php
function addSR_form_service_request_node_form_alter(&$form, $form_state) {
if (arg(0) == 'user' && is_numeric(arg(1))) {
$form['#submit'][] = 'addSR_submit_function';
}
}
function addSR_submit_function($form, $form_state) {
$account = user_load(arg(1));
$form_state['values']['uid'] = $account->uid;
$form_state['values']['name'] = $account->name;
}
?>
The form is loading in the block, but when submitted, is still showing the employee uid. I don't want to use hook_form_alter because I don't want to modify the actual form, because clients can fill out the form directly, in this case, I don't want to modify the form at all.
I'm also ashamed that I'm putting this in a block, but I couldn't think of a way to put this in a module, so any suggestions on that would also be appreciated...
To create your form in a block, you could use the formblock module. Especially if you are not used to use the Drupal API. Then all that's left if to add your own submit handler to the form. This is a piece of code that is run, when the form is submitted. You only want to do this on clients pages so you would do that using the hook_form_alter function.
/**
* Hooks are placed in your module and are named modulename_hookname().
* So if a made a module that I called pony (the folder would then be called
* pony and it would need a pony.info and pony.module file I would create this function
*/
function pony_form_service_request_node_form_alter(&$form, $form_state) {
// Only affect the form, if it is submitted on the client/id url
if (arg(0) == 'client' && is_numeric(arg(1))) {
$form['#submit'][] = 'pony_my_own_submit_function';
}
}
function pony_my_own_submit_function($form, &$form_state) {
$account = user_load(arg(1));
$form_state['values']['uid'] = $account->uid;
$form_state['values']['name'] = $account->name;
}
The idea behind this code, is to only alter the form when the condition is met - that it is submitted on a client page. I guessed that the arg(0) would be client so if it's something else you would need to change that of cause. We only need to add a submit function, since what we want is to change the values if the form has passed validation.
Then if that is the case our 2nd function is run, which does that actual alteration of the values.
PHP blocks are bad. You can put them in a module.
function hook_block($op, $delta = 0) {
// Fill in $op = 'list';
if ($op == 'view' && $delta = 'whatever') {
$account = user_load(arg(1));
$node = array('uid' => $account->uid, 'name' => $account->name, 'type' => 'service_request', 'language' => '', '_service_request_client' => $account->uid);
$output = drupal_get_form('service_request_node_form', $node);
// Return properly formatted array.
}
}
Additionally, you want a form_alter just to enforce the values. It's ugly but it works.
function hook_form_service_request_node_form_alter(&$form, $form_state) {
if (isset($form_state['node']['_service_request_client'])) {
$form['buttons']['submit']['#submit'] = array('yourmodule_node_form_submit', 'node_form_submit');
}
}
function yourmodule_node_form_submit($form, &$form_state) {
$account = user_load($form_state['node']['_service_request_cilent'])l
$form_state['values']['uid'] = $account->uid;
$form_state['values']['name'] = $account->name;
}