I have a simple form which contains a button to open another form in a pop up modal, the form looks like this
Now as you can see above prebids input plus button, when the user clicks the plus button it opens the modal which contains a form like this below.
Now I want to submit the forms in the following an order
First submit: base form (norma way)
Second submit: form inside a pop up (via ajax)
Here is my store function to submit the forms in a page controller
public function store(Request $request)
{
$page = Page::create([
'title' => $request->get('title'),
'articles' => $request->get('articles'),
'status' => $request->get('status'),
]);
// dd($request);
$page->save();
$bidder = Bidder::create('page_id' -> $page->id);
// save bidders informtion to the database using ajax
if($request->ajax())
{
$rules = array(
'params_name.*' => 'required',
'params_value.*' => 'required',
'bidders_name.*' => 'required',
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json([
'error' => $error->errors()->all()
]);
}
$params_name = $request->params_name;
$params_value =$request->params_value;
$bidders_name =$request->bidders_name;
for($count = 0; $count < count($params_name); $count++)
{
$data = array(
'params_name' => $params_name[$count],
'params_value' => $params_value[$count],
'bidders_name' => $bidders_name[$count],
);
$insert_data[] = $data;
}
bidder_parameters::insert($insert_data);
return response()->json([
'success' => 'Data Added successfully.'
]);
}
return redirect("/pages")->with("sucess", "data saved");
}
And here is ajax for submitting form inside a pop up
$("#paramsForms").on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '/pages',
type: "POST",
data: $(this).serialize(),
dataType: 'json',
beforeSend:function() {
$("#save").attr('disabled', 'disabled');
},
success:function (data) {
console.log(data);
alert('Data successfull saved');
},
error:function (error) {
console.log(error)
console.log('Data not saved');
}
})
})
Now when I click submit I get the following error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into `pages` (`title`, `articles`, `status`, `updated_at`, `created_at`) values (?, ?, ?, 2019-11-06 11:29:31, 2019-11-06 11:29:31))"
Note: checking dd($request) for both forms in a store function, I get the following
+request: ParameterBag {#44
#parameters: array:4 [
"_token" => "Wgozk9jnyUnJkL35vPhso9sUr7lbMD8cSgMVuN2s"
"bidders_name" => array:1 [
0 => "Biden"
]
"params_name" => array:1 [
0 => "democratic"
]
"params_value" => array:1 [
0 => "10"
]
]
}
Note: The problem is when I click submit on pop modal it try to send the base form at first
What do I need to change to get what I want?
Note: The problem is when I click submit on pop modal it try to send the base form at first
It means laravel is treating your both form as one and when u try to submit the pop up form it submited the base form. Please make sure you both form are separated.
There might possible that u have not close one of the form tag and the save changes button of pop up form is acting as the base form submit button.
Related
I'm following Symfony cookbook on dynamic form fields creation.
Basically, in my case, I have a Product, a ProductVersion and a Quantity field in my form.
On new forms, ProductVersion is hidden (only with a class attribute, It's still an EntityType).
On Product change (via select menu), I make an AJAX request to see if some ProductVersion exists for this product. If so, I populate the ProductVersion with available versions and show it to the user.
It's working fine with new forms. But when editing the same form, I have an InvalidArgumentException response on my AJAX request that tells me that the Quantity field is null :
Expected argument of type "int", "null" given at property path
"quantity".
I understand that indeed, I don't provide the quantity on my form submission through the AJAX request but that's the purpose of this method isn't it ? To only submit the field that makes a dynamic field change.
How can I do to avoid this Exception ?
Here is the ItemType :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('product', EntityType::class, [
'label' => 'item.product',
'class' => Product::class,
'placeholder' => 'item.product',
]);
$formModifier = function (FormInterface $form, Product $product = null) {
if (null !== $product) {
$productVersions = $product->getVersions();
if (count($productVersions) > 0) {
$form->add('productVersion', EntityType::class, [
'class' => 'App\Entity\ProductVersion',
'placeholder' => 'item.product_version',
'choices' => $productVersions,
'label' => 'item.product_version'
]);
} else {
$form->add('productVersion', EntityType::class, [
'class' => 'App\Entity\ProductVersion',
'placeholder' => 'item.product_version',
'choices' => [],
'label' => 'item.product_version',
'disabled' => true,
'row_attr' => [
//'class' => 'd-none'
]
]);
}
} else {
$form->add('productVersion', EntityType::class, [
'class' => 'App\Entity\ProductVersion',
'placeholder' => 'item.product_version',
'choices' => [],
'label' => 'item.product_version',
'disabled' => true,
'row_attr' => [
//'class' => 'd-none'
]
]);
}
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$form = $event->getForm();
$data = $event->getData();
$options = $event->getForm()->getConfig()->getOptions();
//add custom product version according product selected
$formModifier($event->getForm(), $data->getProduct());
$form
->add('quantity', IntegerType::class, [
'label' => 'item.quantity',
]);
if ($data->getId()) {
$form
->add('save', SubmitType::class, [
'label' => $options['submit_btn_label'],
]);
} else {
$form
->add('save', SubmitType::class, [
'label' => $options['submit_btn_label'],
]);
}
}
);
$builder->get('product')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$product = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $product);
}
);
}
And here is the Javascript part :
$(document).ready(function () {
var $product = $('#item_product');
// When product gets selected ...
$product.on('change', function () {
console.log("product has changed")
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected product value.
var data = {};
data[$product.attr('name')] = $product.val();
// Submit data via AJAX to the form's action path.
console.log(data);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: data,
success: function (html) {
// Replace current position field ...
$('#item_productVersion').closest('.form-group').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#item_productVersion').closest('.form-group')
);
// Position field now displays the appropriate positions.
}
});
});
})
As #Jakumi suggested, adding an empty_data option to the quantity field solved the problem. Nevertheless, It gives an error on the quantity on the form received via the AJAX request and that's normal.
I found that this is not a "clean" method (you have to tweak form fields, you load the entire page on each AJAX request, etc..) so I decided to create a special route dedicated to form submissions that are meant to add/remove/edit fields.
This route creates a new form with preset fields (in my case the product selected by the user).
Then I can populate the other field (in my case the 'ProductVersion') with a regular PRE_SET_DATA Form Event.
This way :
- I don't have to worry about any other required field
- I can serialize the entire form in my AJAX request (no need to find the field, everything is done in the form builder)
- The AJAX request only output the form (I guess this improves performance a bit)
The form builder doesn't change (you still need to listen to PRE_SET_DATA and POST_SUBMIT. If you don't listen to the POST_SUBMIT, the form will not know about the choices you added dynamically and It will give you an error).
Here is the JS part :
$product.on('change', function() {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// serialize the entire form
var data = $form.serializeArray();
// Submit data via AJAX to the form's action path.
console.log(data);
$.ajax({
url : '/project/item/partial-edit', //custom route
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#item_productVersion').closest('.form-group').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#item_productVersion').closest('.form-group')
);
}
});
});
Here is the special route :
/**
* #Route("/item/partial-edit", name="edit_item_partial", requirements={"project"="\d+","item"="\d+"})
*/
public function edit_item_partial(Request $request)
{
$item = new Item();
$formOption = $request->get('option') ?? array(
'submit_btn_label' => 'update'
);
$form = $this->createForm(ItemType::class, $item, $formOption);
$form->handleRequest($request);
if ($form->isSubmitted()){
//if form was submitted, create a new form with the $item that has now a Product given
$newForm = $this->createForm(ItemType::class, $item, $formOption);
//here is the custom view only rendering the form
return $this->render('item/new_form-only.html.twig', [
'form' => $newForm->createView(),
]);
}
else {
return new Response('No form was submitted');
}
}
I'm working on a Laravel PHP site, and am getting an error when trying to add a user to a cell in a table
The error says:
An error has occurred adding your contact. If the problem persists, please contact us.
and is displayed in a red 'ribbon' that pops up just below the browser address bar for a few seconds when trying to select a new user from the drop down.
I have seen a couple of similar questions on SO, but can't see how any of the answers apply to what's going on here...
In the HTML, the table column whose cell value I am trying to update is done via a form that pops up in a dialog box when pressing the 'Edit' icon in the cell:
<div class="provTaxContacts__row">
<form [formGroup]="newContactForm" class="provTaxContacts__col provTaxContacts__new-contact">
<label>Add new contact</label>
<div class="provTaxContacts__new-contact-fields">
<input class="provTaxContacts__new-contact-field provTaxContacts__name" [class.error]="newContactFormErrors.contactFirstName" placeholder="First name" type="text" autocomplete="given-name" formControlName="contactFirstName" />
<input class="provTaxContacts__new-contact-field provTaxContacts__name" [class.error]="newContactFormErrors.contactLastName" placeholder="Last name" type="text" autocomplete="family-name" formControlName="contactLastName" />
<input class="provTaxContacts__new-contact-field provTaxContacts__email" [class.error]="newContactFormErrors.contactEmail" placeholder="Email address" type="email" autocomplete="email" formControlName="contactEmail" />
<button class="btn btn-primary provTaxContacts__new-contact-button" type="button" (click)="onNewContactAdd(taxpayer.accountId)">Add contact</button>
<div *ngIf="addContactLoading" class="spinner-loading"></div>
</div>
</form>
</div>
The onNewContactAdd() function that's called when pressing the 'Add Contact' button is defined in a Typescript file called tax-reminder.ts, and as well as handling what happens to the browser on the front-end, it also calls the function addUserToAccount() from user.service.ts. It is what's displaying the error in the browser, and is defined with:
onNewContactAdd(accountId: number) {
const firstName = this.newContactForm.get('contactFirstName').value;
const lastName = this.newContactForm.get('contactLastName').value;
const email = this.newContactForm.get('contactEmail').value;
// Reset error states
this.resetContactFormErrors();
// Check for form errors
if (!firstName || Validate.isEmpty(firstName) || !Validate.lettersAndSpaces(firstName)) {
this.newContactFormErrors.contactFirstName = true;
} else {
this.newContactFormErrors.contactFirstName = false;
}
if (!lastName || Validate.isEmpty(lastName) || !Validate.lettersAndSpaces(lastName)) {
this.newContactFormErrors.contactLastName = true;
} else {
this.newContactFormErrors.contactLastName = false;
}
if (Validate.isEmpty(email) || !Validate.emailRegex.test(email)) {
this.newContactFormErrors.contactEmail = true;
} else {
this.newContactFormErrors.contactEmail = false;
}
// If there are any errors at this stage, Don't add
if (this.newContactFormErrors.contactFirstName || this.newContactFormErrors.contactLastName || this.newContactFormErrors.contactEmail) {
return
}
// Reset errors, just in case there were previous erros that we now know have been resolved
this.resetContactFormErrors();
this.addContactLoading = true;
// If all is valid, send a request to create the new contact
this.userService.addUserToAccount([{firstName, lastName, email, role: 'FULL'}], 'FULL', accountId)
.subscribe(
(response: any) => {
this.addContactLoading = false;
// Reset the add contact form so that the user can add more
this.newContactForm.patchValue({
contactFirstName: '',
contactLastName: '',
contactEmail: '',
});
// If the new contact's email address is already in the on-page list do nothing
if (_.find(this.contacts[accountId], {email})) {
return;
} else {
// If the request is succcessful, add the new contact to the list of contacts
this.contacts[accountId].push({
accountId,
email,
firstName,
groupTag: 'FULL',
lastName,
provTaxManager: 0,
provTaxPaymentsContact: 0,
userId: response.userId,
//transactionContactId,
});
}
},
error => {
console.log("Error: " + error);
const message = new Message();
message.type = MessageType.ERROR;
message.message = 'An error has occurred adding your contact. If the problem persists please contact us.';
this.messagingService.emitMessage(message);
}
)
}
In the browser console, I can see the following output in the Network-> Preview tab:
array:9 [
"userId" => 9561
"title" => null
"firstName" => "Shane"
"lastName" => "Williams"
"workPhone" => null
"mobilePhone" => null
"email" => "shane#williams.com"
"userTypeId" => 3
"login" => array:3 [
"loginId" => 9449
"loginName" => "shane#williams.com"
"userId" => 9561
]
]
Which shows that the details I entered into the form have been collected, and a new user ID has been assigned.
That output is coming from a dd() I have in the addAccountUser() PHP function:
public function addAccountUser( AddAccountUsersRequest $request )
{
$users = $request->input('users');
$type = $request->input('type');
$accountId = $request->input('accountId');
$userType = $type == 'taxfirm-agent' ? UserType::where('userTypeTag', 'AGENT')->first() : UserType::where('userTypeTag', 'DIRECT')->first();
$messages = array();
$hasWarningMessages = false;
try
{
DB::beginTransaction();
foreach ($users as $userRaw)
{
$details = array(
'firstName' => $userRaw['firstName'],
'lastName' => $userRaw['lastName'],
'email' => $userRaw['email'],
'password' => uniqid(),
'userTypeId' => $userType->userTypeId,
'accountId' => (!empty($accountId)) ? $accountId : null
);
$propertyValues = array();
// Adding tax agent
if ($type == 'taxfirm-agent') {
$group = $userRaw['role'];
$rv = $this->addTaxfirmAgent($details, $group);
}
else if($type == 'taxfirm-direct') {
$rv = $this->addTaxfirmDirectContact($details);
}
else {
$group = $userRaw['role'];
$rv = $this->addTaxpayerDirectContact($details, $group);
}
DB::commit();
dd($rv['user']->toArray());
if ($rv['status'] !== 'SUCCESS') {
if (!isset($messages[$rv['status']])) {
$messages[$rv['status']] = array(
'message' => StatusMessage::getMessage($rv['status']),
'data' => [],
//dd($messages);
);
}
$messages[$rv['status']]['data'][] = [$userRaw['email'], ucfirst($userRaw['firstName']), ucfirst($userRaw['lastName'])];
//dd($messages); // success is true at this point, users are null
if (!$hasWarningMessages)
{
$hasWarningMessages = true;
}
}
}
}
catch(\Exception $e)
{
DB::rollback();
return response()->json(array(
'success' => false,
'exceptionCode' => $e->getCode(),
'exceptionMessage' => $e->getMessage().' - '.$e->getFile().' - '.$e->getLine(),
'userId' => $userId // Try returning the userId too...
), 400);
}
$outputMsg = array();
foreach ($messages as $value) {
$outputMsg[] = $value;
}
//dd($users);
return response()->json(array(
'success' => true,
'hasWarningMessages' => $hasWarningMessages,
'result' => $outputMsg,
//'users' => $rv['user']->user, /*ERF(18/09/2018 # 1630) Change to userId */
'userId' => $rv['user']->userId,
));
}
I don't fully understand how the JavaScript, PHP & HTTP are all interacting here, or why the PHP debug appears to be showing the new contact created successfully, and yet I still get the error in the browser.
Can anyone point me in the right direction here? Why is the contact seemingly created, and yet I get the error, as well as the contact not being displayed in the drop down box as I am expecting?
Edit
So, I think that the issue I'm having here is not to do with the PHP itself- as that function seems to be returning the correct information (the console output given when I added the line dd($rv['user']->toArray()) at the end of the function showed all of the details for the user I had just added correctly), but rather to do with the Angular that should be updating the front end, to display the new user in the drop down.
That function is defined as follows:
this.userService.addUserToAccount([{firstName, lastName, email, role: 'FULL'}], 'FULL', accountId)
.subscribe(
(response: any) => {
this.addContactLoading = false;
// Reset the add contact form so that the user can add more
this.newContactForm.patchValue({
contactFirstName: '',
contactLastName: '',
contactEmail: '',
});
// If the new contact's email address is already in the on-page list do nothing
if (_.find(this.contacts[accountId], {email})) {
return;
} else {
// If the request is succcessful, add the new contact to the list of contacts
this.contacts[accountId].push({
accountId,
email,
firstName,
groupTag: 'FULL',
lastName,
provTaxManager: 0,
provTaxPaymentsContact: 0,
userId: response.userId,
//transactionContactId,
});
}
},
error => {
console.log("Error: " + error);
const message = new Message();
message.type = MessageType.ERROR;
message.message = 'An error has occurred adding your contact. If the problem persists please contact us.';
this.messagingService.emitMessage(message);
}
)
I think I need to add a call to reload this page element at the end of the else statement in this function... How would I do that?
Edit
So, it seems that although the contact appears to be created, the HTTP response I'm getting is actually the error- as I can see the An error has occurred adding your contact. If the problem persists please contact us. message in the browser... Why is it that the HTTP response is failing? How can I resolve this?
I added a console.log() to display the error in the console, and it's showing the following output:
unparsable response
Error: SyntaxError: Unexpected token < in JSON at position 0
I don't understand where this error is coming from... any ideas?
Before all
I have model for image as simple as
return [
'id' => 'ID',
'parent_id' => 'Parent ID',
'photo' => 'Photo', <= just for filename
];
the case is
Create Parent model then save then redirect to form for uploading images related to its parent.
all uploading function work proprerly but no with delete function
This is my upload image form
echo FileInput::widget([
'model' => $photo,
'attribute' => 'photo',
'options'=>[
'accept'=>'image/*',
'multiple'=>true
],
'pluginOptions' => [
'uploadUrl' => Url::to(['/controller/upload', 'id'=> $parent->id]),
'initialPreview'=>$pre-initViews-data,
'initialPreviewAsData'=>true,
'initialCaption'=>"Foto Tersangka",
'initialPreviewConfig' => $pre-initConfigs-data,
'overwriteInitial'=>true,
//'deleteUrl'=> Url::to(['/controller/deletephoto']), <= case 2
'showPreview' => true,
'showRemove' => false,
'showUpload' => false,
'maxFileSize'=>2800
],
'pluginEvents' => [
'fileuploaded'=>"function(event, data, previewId, index){
console.log(data);
}",
]
]);
And here my controller side
$imageFile = UploadedFile::getInstance($model, 'photo');
$directory = Yii::$app->basePath. '/images/';
if ($imageFile) {
$fileName = Yii::$app->security->generateRandomString(). '.' . $imageFile->extension;
$filePath = $directory . $fileName;
if ($imageFile->saveAs($filePath) && $model->save(false)) {
$path = '/images/temp/' . $fileName;
Image::thumbnail($directory.$fileName, 120, 120)
->save(Yii::$app->basePath.$path, ['quality' => 80]);
$response = [];
$reponse['initialPreview'] = \Yii::$app->request->BaseUrl.'/images/'.$fileName;
$reponse['initialPreviewConfig']=[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
];
echo json_encode($reponse);
}
}
And will produce JSON data like this :
{
"initialPreview": "\/web\/images\/Kl1IJOabLs5ENzzgkuW8ln_TILcDumy9.png",
"initialPreviewConfig": {
"caption": "",
"width": "90px",
"key": 38,
"url": "\/web\/index.php?r=controller%2Fdeletephoto",
"extra": {
"id": 38
}
}
}
The issue
I try different way like :
case 1 :
at form widget withoud pluginOptions => deleteUrl'=> Url::to(['/controller/deletephoto']),
upload process success, response from controller initialPreview overwriting initial as expected, but initialPreviewConfig seems doesnt fit, so delete button doesnt work/ doesnt give any process when clicked.
case 2 :
at form widget with pluginOptions => deleteUrl'=>
Url::to(['/controller/deletephoto']) , upload process as expected, but when i click delete button post action didnt parse key as below
Query string
r : controller/deletephoto
Form data
key : {empty key}
Finally
Ive spend huge amount of hours, Please review my code, is there something wrong?
a Big thanks for your help.
UPDATE ISSUE RESOLVED
after long hours finally i got the way..
replace
$response = [];
$reponse['initialPreview'] = \Yii::$app->request->BaseUrl.'/images/'.$fileName;
$reponse['initialPreviewConfig']=[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
];
echo json_encode($reponse);
with
return Json::encode([
'initialPreview' => \Yii::$app->request->BaseUrl.'/images/'.$fileName,
'initialPreviewConfig' => [
[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
],
],
]);
dont know why this happen,
I have a view in which I have a detailview and a gridview. In my grid view there are check-boxes against all the columns. The detail view contains the model id. Now the case is simple, I want to select any column from the grid view and then on click of the a link button I want to send the ajax call, which includes the value of selected column and the model id, to my controller. Below is my view
<?= GridView::widget([
'dataProvider' => $dataProvider,
/*'filterModel' => $searchModel,*/
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['meter_id']];
}],
'Meter_Serial_Number',
'Issued_To',
'Store',
],
]); ?>
Set PDF
Now the javascript and the ajax call
<?php
$url = Url::toRoute(['/ogpheader/viewsetpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {
$('#myid').on('click',function() {
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
// alert(strValue);
$.ajax({
url: '$url',
type: 'POST',
data: {
data: strValue,// also tired with {strValue:strValue id:id} but it did not worked for me as well
},
success: function(data) {
alert(data);
},
});
})
});
JS;
$this->registerJs($script, static::POS_END);
?>
Action Controller
public function actionViewsetpdf($id)
{
$model = $this->findModel($id);
print_r($_POST);
$data = "";
if(Yii::$app->request->isAjax)
{
$data = json_decode($_POST['data']);
print_r($data);
}
else{
echo 'no data';
}
exit();
}
The response i always got is Array ( ) no data. I have also looked into Passing two parameters in yii2 ajax request using jquery to a controller and Yii2 extra parameter ajax in controller but both seems to be helpful in my case.
Note:
As per my understanding the id is a get and strValue is post. So I am confused in both of them. May be I am wrong.
Update 1
Image quality is not that good
The response in Xhr is
array(1) {
["data"]=>
array(1) {
["data"]=>
string(26) "99 , 100 , 101 , 102 , 103"
}
}
Any help would be highly appreciated.
Prevent the default click event
$('#myid').on('click',function(e) {
e.preventDefault();
After user clicks on submit form, I need to call Zend validation of that form without refreshing whole page. I also use zend_Layout in my website. I have seen a lot of tutorials here, but still cant make it working.
Index Controller:
class IndexController extends Zend_Controller_Action {
public function init() {
}
public function indexAction() {
$this->view->static_data = "eg. ABCDEFG";
$this->view->form = new Application_Form_Test();
}
public function ajaxAction() {
// probably some code to hande ajax
}
}
View for index/index:
...
<?php
echo date('m/d/Y h:i:s a', time());
echo $this->static_data;
?>
<hr />
<?php echo $this->form ?>
...
Form:
class Application_Form_Test extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAttrib('class', 'form1');
$this->addElement('text', 'email', array(
'label' => 'Your email address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
)
));
$this->addElement('text', 'name', array(
'label' => 'Your name:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(3, 20))
)
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Send',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
}
So how can i validate form without refreshing rest of that page and see Zend Error Messages in case that form is not valid.
You can post the form to your Ajax action where you will instantiate the form and inject data from the request.
$form = new Form();
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
//save data
....
}
}
$this->view->form = $form;
You have two options:
Render the form in the view and respond with HTML. Using JavaScript replace current form with HTML returned by the Ajax request.
Get error messages using Zend_Form::getMessages() and respond with JSON.
$this-view->messages = $form->getMessages();