I've got a login form which takes 2 alternate forms dependent on how a user taps a segmented control .... either as a register form with email, password, and repeat password; or as a login form with just email and password.
When a user fills out the register or login fields and taps the register/login button ... I log the user in using code along the lines of ...
#IBAction func loginRegisterTapped(sender: AnyObject) {
//check whether the sender tag is registerTag (in which case a new user is registering or alternately returning user logging in
//do various checks and if all good submit the form
}
Ive recently copied over a validation library (SwiftValidator) to my project, and configured it to also validate fields when the login/register button is tapped ie i insert the validation code above my own code in the loginRegisterTapped ibaction method. My code after integrating SwiftValidator essentially becomes
#IBAction func loginRegisterTapped(sender: AnyObject) {
//validation
self.clearErrors()
validator.validate(self)
//check whether the sender tag is registerTag (in which case a new user is registering or alternately returning user logging in
//do various checks and if all good submit the form
}
The SwiftValidator library ends us calling 2 delegate methods (in my LoginViewController) on validation success or failure as follows
// SwiftValidator library Delegate methods
func validationSuccessful() {
// submit the form
}
func validationFailed(errors:[UITextField:ValidationError]) {
// turn the fields to red
for (field, error) in validator.errors {
field.layer.borderColor = UIColor.redColor().CGColor
field.layer.borderWidth = 1.0
error.errorLabel?.text = error.errorMessage // works if you added labels
error.errorLabel?.hidden = false
}
}
Given validation is successful, how can i get code to return to my #IBAction func loginRegisterTapped(sender: AnyObject) method and continue with my own form submission code (... I need a reference to the sender to check it's tag to determine whether the button was tapped as a "Register" button or a "Login" button) rather than conducting the form submission as suggested by the SwiftValidator library within it's validationSuccessful delegate method where i dont have access to the sender var. ie what options do i have here or what would be considered best practice? ... I thought of customizing the validationSuccessful method to return perhaps a bool to the calling function but doubt if that's the best way?
IMHO, I'd do the successful form submission in the validationSuccessful() method, not in your own action method. I'd avoid using tags to differentiate the login and register buttons, and instead have each one call a separate action method. You're not saving any time, code, or logical clarity by handling them both with the same handler.
Related
I am write a form with some fields, when all have valid then i am enable the submit button, do a service call on onSubmit() method.My issue is when i click on the submit button twice it do service call twice. Is there any directive for check form submit.
When you click on the submit button twice it will call the service two times just use one variable 'submit' boolean by default false.
reference: https://angular.io/guide/forms#submit-the-form-with-ngsubmit
onSubmit() {
if(this.submit) {
return;
}
this.submit = true;
this.serviceCall(); // got error set submit to false.
}
Need a suggestion from people more intelligent than me. I have a modal which has 2 things, essentially, 3 radio buttons (Email, PDF, None)and a Yes and NO submit button.
On press of radio button I flag hidden variables appropriately to know if the user pressed email or pdf in my controller. Than user presses Yes for saving (happy path), and it will call a controller.
This controller will save the changes and redirect to a different page. Now I wanna add to this controller and make it download a pdf. I am doing this by calling my DownloadPDF action.
public ActionResult Main(string id)
//code for doing all the save and other stuff
{
if (viewModel.Email)
{
SendTestingEmail(viewModel.ConsumerEncryptedID);
}
else if(viewModel.PDF)
{
DownloadWelcomePDF()
}
return RedirectToAction("ConsumerIndex", "Consumer")
}
public ActionResult DownloadWelcomePDF(string id)
{
var htmlWelcomeEmail = db.getHtmlBody(id.DecryptID());
var converter = new ConvertToPDF();
var file = converter.ConvertHTMLStringToPDF(htmlWelcomeEmail.EmailBody);
var fileStreamResult = new FileStreamResult(file, "application/pdf") { FileDownloadName = string.Format("Welcome{0}{1}_{2}.pdf", htmlWelcomeEmail.ConsumerFirstName, htmlWelcomeEmail.ConsumerLastName, DateTime.Now.ToString("yyyyMMdd")) };
return fileStreamResult;
}
Now since this will also return pdf content I cannot do both these 2 things (redirecting to a different page and downloading ) at the same time.
Is there any suggestion, I have been searching internet for a long time.
It is essentially download and redirect but download needs to happen only on certain condition (press of radio) and the page should always redirect nonetheless.
You can break this into two steps.
First on submit you do a check in javascript to see if the user wants to download the PDF. If he wants, then call the download action and then call the main method from JS.
Or you can render the customerIndex page first and pass a flag (something like downloadPDFForId). Based on this flag in the JS in CustomerIndex you can download the file.
The first approach would be a cleaner one.
I have a very simple form created with createFormBuilder providing one simple text field only (there is no entity attached to the form).
When the form is submitted I do some logic and then unset form and formData as suggested in many posts to this topic if you want the form to be reset after submitting.
There is some additional action by simple ajax-requests that mainly initiates some UI stuff - not touching the form itself nor reloading the page.
Everything works fine except that the form apparently just doesn't want to be reset - meaning: Whenever the page reload button in the browser is pressed the standard browser dialog appears that asks if you want to submit the form again. And when you do the last value typed in BEFORE the last render call is submitted.
The template kw.html.twig is straight forward - mainly some UI stuff the form rendering and a bit jquery for handling ajax. Nothing special there.
I can't figure out why this is happening - I just want a clean form on any request. Which I thought I get when unsetting thing like in the sample code below.
/**
* #Route("/kw", name="show_kw")
*/
public function showKwAction(Request $request)
{
if($request->isXmlHttpRequest()) {
if( $request->getMethod() == 'POST' ) {
// do some logic...
return $this->json(array('kw_success' => true));
}
}
$kwData = array();
$kwForm = $this->createFormBuilder($kwData)
->add('kd', TextType::class)
->getForm();
if( $request->isMethod('POST') ) {
$kwForm->handleRequest($request);
$formData = $kwForm->getData();
// do some logic with formData...
unset($kwData);
unset($kwForm);
$kwData = array();
$kwForm = $this->createFormBuilder($kwData)
->add('kd', TextType::class)
->getForm();
}
$templateData = array(
'kwForm' => $kwForm->createView()
);
return $this->render(':backend:kw.html.twig', $templateData);
}
Any help is highly appreciated.
EDIT: Using Symfony 3.1
It's exactly what Alsatian said in the comment. Browser is trying to repeat last request.
However I think that instead of destroying this form you can simply redirect to the same route with $this->redirectToRoute once you processed data, of course if it's not a problem.
Also I see you check at least twice if method is post. If it's not colliding with the rest of your application logic you can specify #Method("POST") in annotation so you don't have to check it directly in code anymore.
Best Regards,
R.
Is there an easy way to check an email address is valid using Ajax? I'm using the sfValidatortEmail widget currently and this only shows an error message on submitting the form.
Thanks
I'm assuming you know how to write ajax requests. In the action you'd have something like
if ($request->isXmlHttpRequest()) {
// handle ajax check
try{
$validator = new sfValidatorEmail();
$validator->clean($request->getParameter('email'));
// good to go
} catch(sfValidatorError $e){
// invalid email
$this->getResponse()->setStatusCode(400);
}
} else {
// handle normal post
}
You'd need to add some Javascript/Jquery to fire an Ajax request to check the email, possibly linked to when the user clicks out of the email input box (blur function). This would be separate from your form class (assuming that the form has other elements too), but you could use the same action to handle the request if you wish:
if ($request->isXmlHttpRequest()) {
// handle ajax check
} else {
// handle normal post
}
i'm trying to join two independent forms (login and register) in the
same page.
My idea is (just looking at the signin form):
Create an action that shows both forms (partials):
public function executeLoginAndRegister(sfWebRequest $request){
$this->form_signin = $this->getUser()->getAttribute('form_signin');
}
Each partial calls to its action:
form action="php?> echo url_for('#sf_guard_signin') ?>" method="post">
In the actions i write this code
public function executeSignin($request)
{
//...
$this->form = new $MyFormclass();
if ($this->form->isValid())
{
//...
}else{
// save the form to show the error messages.
$this->getUser()->setAttribute('form_signin', $this->form);
return $this->forward('sfGuardAuth', 'loginAndRegister');
}
}
It works, but, for example, if i execute LoginAndRegister and submit
incorrectly the signin form and I go to another page and then return to
LoginAndRegister, i will find the submiting error messages...
If i execute LoginAndRegister and submit incorrectly the signin form and
open another browser tab, i will find the submiting error messages in
the signin form of the second tab...
Any idea? any better approach?
I would just use sfDoctrineApplyPlugin if i were you :)
I have it, just writing in the if "request->isMethod('post')":
public function executeLoginAndRegister(sfWebRequest $request){
if($request->isMethod('post')){
$this->form_signin = $this->getUser()->getAttribute('form_signin');
}
}
Anyway if my approach has any big error or is not safety i would
thank anyone who tell me.
Javi