Silverstripe - Form with custom template shows wrong validation errors - validation

I have the following custom form
$list = DataObject::get('AreaOfExpertise');
foreach ($list as $l) {
$source[$l->ID] = $l->Name;
}
$fields = new FieldSet(
new TextField('Customer'),
new TextField('ProjectName'),
new DateField('WinDate'),
new TextareaField('Details'),
new OptionsetField('AreaOfExpertiseID', 'Area Of Expertise', $source),
new TextField('ProjectValueLength'),
new TextField('DeliverTimeframe'),
new TextField('ProjectTeam'),
new TextField('Contact')
);
$actions = new FieldSet(
new FormAction('doSubmit', 'Submit')
);
$requiredFields = array(
'Customer',
'ProjectName',
'WinDate',
'Details',
'AreaOfExpertiseID',
'ProjectValueLength',
'DeliverTimeframe',
'ProjectTeam',
'Contact',
);
$validator = new RequiredFields($requiredFields);
$form = new Form($this, 'SubmissionForm', $fields, $actions, $validator);
$form->setTemplate('Forms/NewWinForm');
return $form;
and my template for this form is
<form $FormAttributes>
<% if Message %>
<p id="{$FormName}_error" class="message $MessageType">$Message</p>
<% else %>
<p id="{$FormName}_error" class="message $MessageType" style="display: none"></p>
<% end_if %>
<fieldset id="formContainer" class="clearfix NewWinForm">
<div id="Customer" class="row field text">
<label class="left" for="{$FormName}_Customer">Customer</label>
<div class="middleColumn">$dataFieldByName(Customer)</div>
</div>
<div id="ProjectName" class="row field text">
<label class="left" for="{$FormName}_ProjectName">Project name</label>
<div class="middleColumn">$dataFieldByName(ProjectName)</div>
</div>
<div id="WinDate" class="row field text">
<label class="left" for="{$FormName}_WinDate">Win date</label>
<div class="middleColumn">$dataFieldByName(WinDate)</div>
</div>
<div id="AreaOfExpertiseID" class="row field text">
<label class="left" for="{$FormName}_AreaOfExpertiseID">Area of expertise</label>
<div class="middleColumn">$dataFieldByName(AreaOfExpertiseID)</div>
</div>
<div id="Details" class="row field textarea">
<label class="left" for="{$FormName}_Details">Project details</label>
<div class="middleColumn">$dataFieldByName(Details)</div>
</div>
<div id="ProjectValueLength" class="row field text">
<label class="left" for="{$FormName}_ProjectValueLength">Project value/length</label>
<div class="middleColumn">$dataFieldByName(ProjectValueLength)</div>
</div>
<div id="DeliverTimeframe" class="row field text">
<label class="left" for="{$FormName}_DeliverTimeframe">Delivery timeframe</label>
<div class="middleColumn">$dataFieldByName(DeliverTimeframe)</div>
</div>
<div id="ProjectTeam" class="row field text">
<label class="left" for="{$FormName}_ProjectTeam">Project team</label>
<div class="middleColumn">$dataFieldByName(ProjectTeam)</div>
</div>
<div id="Contact" class="row field text">
<label class="left" for="{$FormName}_Contact">Contact</label>
<div class="middleColumn">$dataFieldByName(Contact)</div>
</div>
</fieldset>
<div class="Actions">
<% if Actions %>
<% control Actions %>$Field<% end_control %>
<% end_if %>
</div>
</form>
When I submit the form, instead of "Please fill out "Customer", it is required." message I get "Please fill out "this", it is required."
This is happening for all fields apart from Details field!
Can someone please tell me what I am doing wrong? It's killing me...

Ok, after some digging in sapphire/javascript/Validator.js, I found that the first class of the wrapper div must be field so I replaced this
<div id="Customer" class="row field text"> with <div id="Customer" class="field text row"> and everything works just fine.

This should be done by creating a form class and implementing the "forTemplate()" function. See SilverStripe Forms.
Also, instead of creating the "AreaOfExpertise" source array the way you have, there's a convenience method, toDropDownMap(), that does this for you.
$source = $list->toDropDownMap('ID', 'Name');
Hope this helps.

Related

Laravel form submit unsuccessful returns blank page instead of redirect home

I have a laravel form to create a new product entry in a database on submit, am supposed to be redirected back but I get a completely blank page without any errors. There is no new entry in my database when I check. The form is made up of various text fields, an image URL, and a multi-selected Image URL
please this is my blade template
<form method="POST" action="{{ route('products.store') }}" enctype="multipart/form-data">
<h4 class="card-title">Create Product</h4><br><br>
#csrf
<div class="row">
<div class="col">
<div class="row mbr-1">
<label for="example-text-input" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-6">
<input name="name" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input"
class="col-sm-2 col-form-label">Category</label>
<div class="col-sm-6">
<input name="name" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Price</label>
<div class="col-sm-6">
<input name="catchy_title" class="form-control" type="number"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Status</label>
<div class="col-sm-6">
<input name="status" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Product
Description</label>
<div class="col-sm-8">
<textarea id="elm1" name="long_description" placeholder="Please enter a vivid description of the product"></textarea>
</div>
</div>
<!-- end row -->
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Tags</label>
<div class="col-sm-6">
<input name="tags" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Estimated
Delivery
Time</label>
<div class="col-sm-6">
<input name="estimated_delivery_time" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Available
Quantity</label>
<div class="col-sm-6">
<input name="available_quantity" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Colors</label>
<div class="col-sm-6">
<input name="colors" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Supplier's
Name</label>
<div class="col-sm-6">
<input name="supplier_name" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Supplier's
Contact</label>
<div class="col-sm-6">
<input name="supplier_contact" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Video Url /
Link</label>
<div class="col-sm-6">
<input name="video_description" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Primarry
Image</label>
<div class="col-sm-6">
<input name="primary_image" accept="image/*" class="form-control"
type="file" id="image">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label"> Primary Image
Preview</label>
<div class="col-sm-6">
<img id="showImage" class="" width="300px"
src="{{ !empty($Product->image) ? url('upload/products/' . $product->image) : url('upload/no_image.jpg') }}"
alt="Hero image">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Add Other
Images</label>
<div class="col-sm-6">
<input name="multi_image[]" accept="image/*" class="form-control"
type="file" id="image" multiple="">
</div>
</div>
<!-- end row -->
</div>
</div>
<input type="submit" class="btn btn-info waves-effect waves-light"
value="Create Product">
</form>
and this is my store function
public function store(Request $request)
{
if ($request->file('image')) {
$image = $request->file('image');
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension(); // 3434343443.jpg
Image::make($image)->resize(523,605)->save('upload/home_about/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
$this->validate($request, [
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'tags' => $request -> tags,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'other_images' => $save_url,
]);
$notification = array(
'message' => 'Product created successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Please what am I doing wrong?
thank you for taking some time to review
you are validating the request but not saving it to database.
after the validation and before the return you should do like this to save in database.
$item=new YOUR_MODEL_NAME:
$item->name => $request->name,
$item->category => $request->category,
$item->price => $request->price,
$item->description => $request->description,
$item->status => $request -> status,
$item->tags => $request -> tags,
$item->estimated_delivery_time => $request->estimated_delivery_time,
$item->available_quantity => $request->available_quantity,
$item->colors => $request->colors,
$item->supplier_name => $request->supplier_name,
$item->supplier_phone => $request->supplier_phone,
$item->video_description => $request->video_description,
$item->primary_image => $save_url,
$item->other_images => $save_url,
$item->save();
$this->validate($request, [
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'tags' => $request -> tags,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'other_images' => $save_url,
]);
In the snippet above you're performing the validation, but I don't see a request to persist the data to your database in your store() function.
It's recommended to utilize the functionality provided by the framework when checking for request input presence. These functions usually provide quality-of-life aspects such as checking for multiple input presence and conditional callbacks as well.
https://laravel.com/docs/9.x/requests#determining-if-input-is-present
if ($request->has('name')) {
//
}
You should also be calling the validate() method on $request, not $this.
First, I'd like to recommend that you utilize a Form Request
https://laravel.com/docs/9.x/validation#form-request-validation
Second, use the validated data and mass assignment when storing the new model. If the validated data structure is not 1:1 with the table schema, you could always assign the values manually but this will result in a bloated controller. One possible solution is to utilize a DTO (Data Transfer Object) and provide the validated() array to the DTO when using mass assignment.
// Without DTO
Model::create($modelStoreRequest->validated());
// With DTO
$DTO = new MyDTO($modelStore$request->validated())->toArray();
Model::create($DTO);
Note that if the incoming request fields do not pass the given validation rules Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and request input will automatically be flashed to the session.
Try to be specific, pass route where you want to redirect like below:
return redirect()->route('route-name-here')->with($notification);

Getting error when click in my second post for the single page

When I am trying to open first post in single page, it's opening and when trying to open my second post in single page it;s showing "Trying to get property 'title' of non-object"
Here is code
FrontendController
public function singlePost($slug)
{
$post= Post::where('slug', $slug)->first();
return view('single')->with('post', $post)
->with('title', $post->title)
->with('settings', Setting::first())
->with('categories', Category::take(4)->get());
}
single.blade.php
in that I am using same frontend controller for same page
#extends('layouts.frontend')
#section('content')
<div id="product-post">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="heading-section">
<img src="{{$post->featured}}" alt="" />
</div>
</div>
</div>
<div id="single-blog" class="page-section first-section">
<div class="container">
<div class="row">
<div class="product-item col-md-12">
<div class="row">
<div class="col-md-8">
<div class="product-content">
<div class="product-title">
<h3>{{$post->title}}</h3>
<span class="subtitle">4 comments</span>
</div>
<p>
{!! $post->content!!}
</p>
</div>
<div class="leave-form">
<form action="#" method="post" class="leave-comment">
<div class="row">
<div class="name col-md-4">
<input type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="email col-md-4">
<input type="text" name="email" id="email" placeholder="Email" />
</div>
<div class="subject col-md-4">
<input type="text" name="subject" id="subject" placeholder="Subject" />
</div>
</div>
<div class="row">
<div class="text col-md-12">
<textarea name="text" placeholder="Comment"></textarea>
</div>
</div>
<div class="send">
<button type="submit">Send</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
You have to check whether the value is coming from table or not before getting exact column value. In that case if your table return empty result you can redirect it to 404 page.
Please refer the code below :
public function singlePost($slug)
{
$post= Post::where('slug', $slug)->first();
if($post) {
return view('single')->with('post', $post)
->with('title', $post->title)
->with('settings', Setting::first())
->with('categories', Category::take(4)->get());
} else {
// You can redirect to 404 page
}
}

How to get Ckeditor textarea value in laravel

i am using Ckeditor for blog posting in my project when i submit the form nothing i am get in controller can any one suggest me solution for that.
my view is looking like
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Post</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('store-post') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="category_id" class="col-md-2 control-label">Select Categories</label>
<div class="col-md-8">
<select class="form-control" id="category_id" name="category_id">
#foreach($categories as $category)
<option value="{{$category->url_name}}">
{{$category->category_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Post Title</label>
<div class="col-md-8">
<input id="post_title" type="text" class="form-control" name="post_title" value="{{ old('post_title') }}">
</div>
</div>
<div class="form-group">
<label for="post_content" class="col-md-2 control-label">Post Description</label>
<div class="col-md-8">
<textarea id="post_content" rows="10" cols="60" class="span8" placeholder="Image Title Goes Here" name="post_content"></textarea>
</div>
</div>
<div class="form-group">
<label for="p_url" class="col-md-2 control-label">Post Url</label>
<div class="col-md-8">
<input id="p_url" type="text" class="form-control" name="p_url" value="{{ old('p_url') }}">
</div>
</div>
<div class="form-group">
<label for="p_title" class="col-md-2 control-label">Meta Title</label>
<div class="col-md-8">
<input id="p_title" type="text" class="form-control" name="p_title" value="{{ old('p_title') }}">
</div>
</div>
<div class="form-group">
<label for="p_keyword" class="col-md-2 control-label">Meta Keyword</label>
<div class="col-md-8">
<input id="p_keyword" type="text" class="form-control" name="p_keyword" value="{{ old('p_keyword') }}">
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Meta Description</label>
<div class="col-md-8">
<textarea class="form-control" id="p_mdesc" name="p_mdesc" rows="3">
</textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-2">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</div>
<!--Error start-->
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!--error ends-->
</form>
</div>
</div>
</div>
</div>
</div>
my controller code is
public function store(Request $request){
/*$this->validate($request, [
'category_id' => 'required',
'post_title' => 'required',
//'post_content' => 'required',
'p_url' => 'required',
'p_title' => 'required',
'p_keyword' => 'required',
'p_mdesc' => 'required',
]);*/
$post=new Post;
echo $post_content=$request->input('post_content');
}
in previous project ie designed in CI i just use
$tc=$this->input->post('tc'); in controller for getting the Ckeditor value but in laravel i am not sure how to get it done.
Your view contain 2 name attribute for the post_content field (textarea). Please check.
You can do it like this -
{!! Form::textarea('tc', $tc,array('required', 'class'=>'form-control', placeholder'=>'Your message')) !!}
and then you will have to initialise it
$(document).ready(function () {
CKEDITOR.replace( 'tc' );
});
The documentation has clear examples.
In your Blade you should add ckeditor like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="../ckeditor.js"></script>
</head>
<body>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1' );
</script>
</form>
</body>
</html>
So the javascript code triggers a replace of a textarea to the editor
Now for the retrieving data part
<script>
var data = CKEDITOR.instances.editor1.getData();
// Your code to save "data", usually through Ajax.
</script>
You need to create an endpoint if you want to send this data indeed trough Ajax. Don't forget to add a CSRF token
As mentioned by #user3888958,
<textarea name="tc" id="post_content" rows="10" cols="60"
class="span8" placeholder="Image Title Goes Here" name="post_content">
the textarea has two name attribute.
You could access the textarea content using the name attribute, remove any one name attribute and pass that in as a parameter to the request
$request->input('tc'); // OR
$request->input('post_content');
and to access the value of
<textarea class="form-control" id="p_mdesc" name="p_mdesc" rows="3">
</textarea>
you could access it using the name
$request->input('p_mdesc');

How can loop through different text fields which have same class name

MY HTML
<div class='participants'>
<div class="participant_period" data-view="scorecards/participant_edit" data-model_id="348292" data-model_name="scorecard_participants" data-view-data.model="{"type":"model","key":"model:scorecard_participants:348292","model":"scorecard_participants","id":"348292"}" data-model-name="scorecard_participants" data-model-id="348292"><div class="content-item content-full content-results content-box-score">
<span class="profile-image"><img src="//d3f4b3d8pglafo.cloudfront.net/system/teams/images/348292/thumb/profile" /></span>
<span class="profile-name">Web-driver Baseball Team1</span>
<div class='row'>
<div class='col col-control'>
<div class='final-header'>Score</div>
<div class='period-score'>
<input name=final_score type="text" size="5" placeholder="-" value="" />
</div>
</div>
</div>
</div>
</div>
<div class="participant_period" data-view="scorecards/participant_edit" data-model_id="347821" data-model_name="scorecard_participants" data-view-data.model="{"type":"model","key":"model:scorecard_participants:347821","model":"scorecard_participants","id":"347821"}" data-model-name="scorecard_participants" data-model-id="347821"><div class="content-item content-full content-results content-box-score">
<span class="profile-image"><img src="//d3f4b3d8pglafo.cloudfront.net/system/teams/images/347821/thumb/102px-RedSoxPrimary_HangingSocks.svg.png" /></span>
<span class="profile-name">Boston Red Sox</span>
<div class='row'>
<div class='col col-control'>
<div class='final-header'>Score</div>
<div class='period-score'>
<input name=final_score type="text" size="5" placeholder="-" value="" />
</div>
</div>
</div>
</div>
</div>
I want to fill up the tex fields " input name=final_score " with random data with loop
can anyone suggest me how can i do it
my Watir code is like below
def edit_score_fields
field = #browser.text_field(:name => 'final_score')
data = rand(1...2)
s = #browser.text_fields(:class => "period-score").size
0.upto(s) { |i| #browser.text_field(:name => 'final_score', :index => '#{i}'.to_i).set(data) }
end
Try something like:
#browser.inputs(:name => 'final_score').each do |field|
field.send_keys data
end

AJAX within a modal inserting a form in CodeIgniter

Been struggling with this for about 4 hours, I'm attempting to have a modal drop down (Twitter bootstrap modal) that contains a form to create a Company. This is built in CodeIgniter.
I'm having issues with input type="submit" and input type="button".
I only have 1 required field, which is Company Name. If I use input type="button", the validation will fire correctly inside of the modal, however the form will only INSERT just the company name, along with company_id, user_id, active, and cdate.
Now if I use input type="submit", all the data inserts fine. However, the validation breaks and I get a "Page cannot be found" after clicking "Create Company", the data is still inserting though.
Any ideas? Thanks! New to AJAX...
My AJAX function:
$(document).ready(function(){
$('#create_btn').live('click', function(){
//we'll want to move to page specific files later
var name = $('#name').val();
$.ajax({
url: CI_ROOT + "members/proposals/add_client",
type: 'post',
data: {'name': name },
complete: function(r){
var response_obj = jQuery.parseJSON(r.responseText);
if (response_obj.status == 'SUCCESS')
{
window.location = CI_ROOT + response_obj.data.redirect;
}
else
{
$('#error_message2').html(response_obj.data.err_msg);
}
},
});
});
});
My controller function which handles the insert:
function add_client()
{
$this->form_validation->set_rules('name', 'Company Name', 'trim|required|xss_clean');
load_model('client_model', 'clients');
load_model('industry_model');
$user_id = get_user_id();
$company_id = get_company_id();
if (!$user_id || !$company_id) redirect('home');
if ($_POST)
{
if ($this->form_validation->run() == TRUE)
{
$fields = $this->input->post(null , TRUE);
$fields['user_id'] = $user_id;
$fields['company_id'] = $company_id;
$fields['active'] = 1;
$fields['cdate'] = time();
$insert = $this->clients->insert($fields);
if ($insert)
{
$this->message->set('alert alert-success', '<h4>Company has been added</h4>');
header('location:'.$_SERVER['HTTP_REFERER']);
}
else
{
$this->message->set('alert alert-error', '<h4>There was an issue adding this Company, please try again</h4>');
}
}
else
{
$err_msg = validation_errors('<div class="alert alert-error">', '</div>');
$retval = array('err_msg'=>$err_msg);
$this->ajax_output($retval, false);
}
}
$this->data['industries'] = array(0=>'Select Industry...') + $this->industry_model->dropdown('industry');
$this->insertMethodJS();
$this->template->write_view('content',$this->base_path.'/'.build_view_path(__METHOD__), $this->data);
$this->template->render();
}
And finally, my view:
<div class="modal hide fade" id="milestone" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="width: 600px !important;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Add a Company</h3>
</div>
<div class="modal-body">
<?php echo form_open_multipart(base_url().'members/proposals/add_client', array('class' => '', 'id' => 'client_form'));?>
<div id="error_message2"></div>
<div class="row-fluid">
<div class="span5">
<input type="hidden" name="cdate" id="cdate" value="" />
<div class="control-group">
<label class="control-label">Company Name: <span style="color: red;">*</span></label>
<div class="controls">
<input type="text" id="name" name="name" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Company Abbreviation:<span style="color: red;">*</span></label>
<div class="controls">
<input type="text" id="abbreviation" name="abbreviation" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Company Image: </label>
<div class="controls">
<input type="file" name="client_image" size="20" />
</div>
</div>
</div>
<div class="span5">
<div class="control-group">
<label class="control-label">Website:</label>
<div class="controls">
<input type="text" id="website" name="website" value=""/>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span5" style="margin-top: 25px;">
<div class="control-group">
<div class="controls">
<p><strong>Client</strong></p>
</div>
</div>
<div class="control-group">
<label class="control-label">Address 1:</label>
<div class="controls">
<input type="text" id="address1" name="address1" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Address 2:</label>
<div class="controls">
<input type="text" id="address2" name="address2" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">City:</label>
<div class="controls">
<input type="text" name="city" id="city" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">State:</label>
<div class="controls">
<?= form_dropdown('state', usa_state_list(), set_value('state'), 'id=state'); ?>
</div>
</div>
<div class="control-group">
<label class="control-label">Zip:</label>
<div class="controls">
<input type="text" id="zip" name="zip" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Country:</label>
<div class="controls">
<?= form_dropdown('country', country_list(), set_value('country'), 'id=country'); ?>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button type="submit" class="btn btn-primary" id="create_btn">Create Company</button>
</div>
</form>
</div>
So again, to summarize. With input type="button", my validation works great within the modal and only the Company Name is inserting into the database along with company_id, user_id, active, and cdate.
Now, with input type="submit", all data inserts great, however validation fails and I get a redirect to a page cannot be found.
Again, thanks!
The issue is with your ajax function call.
You need to prevent the form from firing (and thus submitting via post to the url in action):
Change:
$('#create_btn').live('click', function(){
To:
$('#create_btn').live('click', function(e){
e.preventDefault();
This should fix the issue. If it doesn't, let me know and I'll do more digging. I would also recommend switching live to on so that you future-proof yourself. on handles the same stuff as live, bind, etc. in a single function with more efficiency.
Edit: To explain what's going on (and why you must use e.preventDefault();), it is because <input type="submit"> will actually submit the form to the url specified in the <form> tag's action attribute. Thus, what's happening with your code is that your javascript is running as soon as you click the button, and then the native browser submit event is occurring immediately afterwards.

Resources