How to create custom html form with redirect back with success message in silverstripe? - silverstripe-4

I am new in SilverStripe. I want to create a custom HTML form in SilverStripe.
<form class="form-inline" $HelloForm.FormAttributes>
<p id="{$HelloForm.FormName}_success" class="message" style="">$HelloForm.Message</p>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div>
<div class="checkbox">
</div>
$HelloForm.fields
<input type="hidden" value="{$AbsoluteLink}" name="redirectURL" class="action" id="{$HelloForm.FormName}_action_doSayHello"/>
And in my controller
public function HelloForm()
{
$form = Form::create(
$this,
'HelloForm'
);
$actions = new FieldList(
FormAction::create('doSayHello', 'Submit')->setAttribute('class', 'btn btn-success')
);
$form = new Form($this, 'HelloForm',$actions);
return $form;
}
public function doSayHello($data,$form)
{
$form->sessionMessage('thanks for contact us','good');
return $this->redirectBack();
//i am not getting success message after submit
}
Can I get a success message after submitting in this case?
When I use standard SilverStripe form it's working but when using custom HTML form like above I am stuck

You could submit the form via ajax, which would have many advantages.
The page does not have to refresh itself
You can animate the form after submitting, by sliding up or some kind of similar animation.
You can handle form states like success or error
Some example code (in jQuery):
let form = $('.form-inline');
$(form).ajaxSubmit({
success: function() {
$(form).slideUp();
$('#form-state').text("Successfully submitted form.");
}
})

Related

Form POST data handling with WordPress

I have hard time figuring out how to recieve form data. This is how my form looks like:
<form action="register" method="POST">
<input type="hidden" name="action" value="process_form">
<input type="email" placeholder="Enter email" name="email">
<input type="password" placeholder="Enter password" name="password">
</form>
How can I access the data of my form?
You should change your form action to something like this:
action="<?= esc_url(admin_url('admin-post.php')) ?>"
And add a hidden input in your form like this:
<input type="hidden" name="action" value="add_foobar">
And then in your backend class add an action like this:
namespace Class\Namespace;
class ClassName {
public function init() {
add_action( 'admin_post_add_foobar', [$this, 'handleForm'] );
}
public function handleForm() {
// your logic here
// use $_POST to retrieve post data
}
....
Make sure to include your class in your functions.php of your theme, like this:
(new \Class\Namespace\ClassName)->init();
To read form data, then in your handleForm method just use $_POST.
For more examples have a look at this page.
After the form has been submitted, you can access it on the page it loads with the PHP $_POST variable.
eg.
$email = $_POST['email'];
Remember to validate and sanitise this variable as it will be what the user has entered.

Form action called before ajax request

I'm trying to validate some data using javascript, so after created this form:
<form asp-controller="User" asp-action="UpdateUser" asp-antiforgery="true" id="userInformations">
<div class="form-group">
<label class="col-lg-6 control-label">#Localizer["OldPassword"] (*)</label>
<div class="col-lg-12">
<input class="form-control" required id="oldPassword"
asp-for="#Model.ExistingPassword" type="password" />
</div>
<div class="form-group">
<label class="col-lg-6 control-label">#Localizer["NewPassword"] (*)</label>
<div class="col-lg-12">
<input class="form-control" required id="newPassword"
asp-for="#Model.Password" type="password" />
</div>
</div>
<button type="submit" class="btn btn-primary">Store</button>
</form>
I binded a javascript function that intercept the submit:
$('#userInformations').on('submit', function (event) {
event.preventDefault();
//validate some fields
//execute ajax request
$.ajax({
url: $(this).attr('action'),
type: "POST",
data: $(this).serialize(),
success: function (result) {
alert(true);
console.log(result)
},
error: function (data) {
console.log(data);
}
});
});
Now when I press the submit button, the method UpdateUser in the UserController is called first of the javascript function, and I don't understand why happen this because I used preventDefault.
How can I prevent to call the asp net action binded to the form?
The effect you want is to use javascript to validate some data , and implement the action call through ajax when you press the submit button?
I use the code you provided and it works.
Try the following two ways:
1.Add the following piece of code above your javascript
<script src="~/lib/jquery/dist/jquery.js"></script>
2.Or directly write your javascript in #section Scripts { }
If you want JavaScript first than you have to remove asp-Controller and action from form, than you can validate form by JavaScript and send data through Ajax call to Controller/action.

bind to an input on form

What i'm trying to do, is get the value of an input on my form and affect it to a variable on my Typescript class, here is my template :
<form [ngFormModel]="form" (ngSubmit)="save()">
<fieldset>
<legend>
Action
</legend>
<div class="form-group">
<label for="label">Label</label>
<input ngControl="label" type="text" class="form-control">
</div>
For example here i want to get the value of the input called label when the user save the form and simply affect it like this :
export class ActionFormComponent {
form: ControlGroup;
_label: any;
constructor() {
}
print() {
this_label = this.form.label;
console.log(this._label);
}
}
ngModel does what you want:
<input ngControl="label" type="text" class="form-control" [(ngModel)]="label">

How to upload an image using Sonata Media Bundle

I am working on a project using symfony.I want to use Sonata Media bundle,in order to upload image.
Unfortunately I don't knwo how to use it or how to start.
I havethis form :
<form action="" method="POST" class="filePhotoForm form-inline" role="form">
<div class="form-group">
<input type="button" class="btn btn-start-order browse" value="Browse">
<input type="text" class="form-control file-name" readonly="readonly" placeholder="No file selected">
<input type="file" name="filePhoto" id="filePhoto" class="hidden file-upload">
</div><br/><br/>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And the code in controller:
public function changePictureAction(Request $request)
{
return $this->render('MedAppBundle:Profile:change_picture.html.twig');
}
Can you help with the basics of uploading?
Thank you!
i have made a custom function for that
protected function saveImageMediaBundle($file,$context = 'default')
{
$mediaManager = $this->get('sonata.media.manager.media');
$media = new Media();
$media->setContext($context);
$media->setProviderName('sonata.media.provider.image');
$media->setBinaryContent($file);
$mediaManager->save($media);
return $media;
}
and get file by this
$file = $request->files->get('newsImage',null);
$media = $this->saveImageMediaBundle($file,'news');

Form validation in meteorjs

I am doing simple validation of inputs in meteorjs, after first tour it works, and every next time it doesn't work (until I reload the page) – it means error messages are not displayed.
//main.js//
Template.addMealForm.events({
'click #submitNewMeal': function (ev) {
ev.preventDefault();
var query = {
name: $("#name").val().trim(),
price: $("#price").val(),
calories: $("#calories").val(),
category: $("#category").val()
};
areInputsValid(query);
}
});
var areInputsValid = function (query) {
if ((query.name.length === 0) || (query.price.length === 0) || (query.calories.length === 0)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("All fields are required");
}
else if ((isNaN(query.price) === true) || (isNaN(query.calories) === true)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("To Price and Calories fields please enter a number");
}
else {
console.log('it works');
$('.dn').hide();
}
};
//main.html//
<template name="addMealForm">
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control input_form" id="name" placeholder="Name of the meal">
</div>
<div class="form-group">
<label for="price">Price</label>
<input class="form-control input_form" id="price" placeholder="Price">
</div>
<div class="form-group">
<label for="calories">Calories</label>
<input class="form-control input_form" id="calories" placeholder="Calories">
</div>
<div id="warningLabel" class="form-group has-error dn">
<label class="control-label warningLabel"></label>
</div>
<button id="submitNewMeal" type="submit" class="btn btn-rimary">Add</button>
</form>
</template>
The problem is that you are calling $('.dn').hide() in the success case. Because #warningLabel has a class of dn it will not be displayed again on subsequent errors.
One solution is to add $('.dn').show() to the top of areInputsValid.
You already have Tracker as part of Meteor, so I put a little tutorial and JSfiddle together on how to use it to implement a typical form validation scenario.
http://bit.ly/meteor-form-validation-video
http://bit.ly/meteor-form-validation-fiddle

Resources