I can't save input to database Vuejs and Laravel - mysql
I added two new input (ass1 and ass2) to a form, created the columns in the database, added it to $fillable in the model, and method in Vue file.
The challenge is that every other input saves to the database but my new inputs are not stored to the database.
If I input directly to the database, the data will show up for edit/update but will not store.
I have checked and checked through the code and can't find any issue, no error message so far.
If you need any other details I will be happy to provide them.
Please help! I'm on a deadline.
P.S. I have very little knowledge of Vuejs, it's a bit confusing.
This is my form.vue content:
<template>
<div>
<form #submit.prevent="proceed" #keydown="assessmentForm.errors.clear($event.target.name)">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="">{{trans('exam.assessment_name')}}</label>
<input class="form-control" type="text" v-model="assessmentForm.name" name="name" :placeholder="trans('exam.assessment_name')">
<show-error :form-name="assessmentForm" prop-name="name"></show-error>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="">{{trans('exam.assessment_description')}}</label>
<input class="form-control" type="text" v-model="assessmentForm.description" name="description" :placeholder="trans('exam.assessment_description')">
<show-error :form-name="assessmentForm" prop-name="description"></show-error>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<h6 class="card-title">{{trans('exam.assessment_type')}}</h6>
<template v-for="(detail,index) in assessmentForm.details">
<div class="row">
<div class="col-12 col-sm-3">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_name')}}
<button type="button" class="btn btn-xs btn-danger m-l-20" :key="`${index}_delete_detail`" v-confirm="{ok: confirmDeleteDetail(index)}" v-tooltip="trans('general.delete')"><i class="fas fa-times"></i></button></label>
<input class="form-control" type="text" v-model="detail.name" :name="getDetailName(index)" :placeholder="trans('exam.assessment_detail_name')">
<show-error :form-name="assessmentForm" :prop-name="getDetailName(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-1">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_code')}}</label>
<input class="form-control" type="text" v-model="detail.code" :name="getDetailCode(index)" :placeholder="trans('exam.assessment_detail_code')">
<show-error :form-name="assessmentForm" :prop-name="getDetailCode(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_max_mark')}}</label>
<input class="form-control" type="number" v-model="detail.max_mark" :name="getDetailMaxMarkName(index)" :placeholder="trans('exam.assessment_detail_max_mark')">
<show-error :form-name="assessmentForm" :prop-name="getDetailMaxMarkName(index)"></show-error>
</div>
</div>
<!-- <div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_pass_percentage')}}</label>
<div class="input-group mb-3">
<input class="form-control" type="number" v-model="detail.pass_percentage" :name="getDetailPassPercentageName(index)" :placeholder="trans('exam.assessment_detail_pass_percentage')">
<div class="input-group-append">
<span class="input-group-text" id="basic-addon1">%</span>
</div>
</div>
<show-error :form-name="assessmentForm" :prop-name="getDetailPassPercentageName(index)"></show-error>
</div>
</div> -->
<div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_ass1')}}</label>
<input class="form-control" type="number" v-model="detail.ass1" :name="getDetailAssessment1(index)" :placeholder="trans('exam.assessment_detail_ass1')">
<show-error :form-name="assessmentForm" :prop-name="getDetailAssessment1(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_ass2')}}</label>
<input class="form-control" type="number" v-model="detail.ass2" :name="getDetailAssessment2(index)" :placeholder="trans('exam.assessment_detail_ass2')">
<show-error :form-name="assessmentForm" :prop-name="getDetailAssessment2(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_description')}}</label>
<autosize-textarea v-model="detail.description" rows="2" :name="getDetailDescriptionName(index)" :placeholder="trans('resource.assessment_detail_description')"></autosize-textarea>
<show-error :form-name="assessmentForm" :prop-name="getDetailDescriptionName(index)"></show-error>
</div>
</div>
</div>
</template>
<div class="form-group">
<button type="button" #click="addRow" class="btn btn-info btn-sm waves-effect waves-light">{{trans('exam.add_new_assessment_detail')}}</button>
</div>
</div>
</div>
<div class="card-footer text-right">
<router-link to="/configuration/exam/assessment" class="btn btn-danger waves-effect waves-light ">{{trans('general.cancel')}}</router-link>
<button type="submit" class="btn btn-info waves-effect waves-light">
<span v-if="id">{{trans('general.update')}}</span>
<span v-else>{{trans('general.save')}}</span>
</button>
</div>
</form>
</div>
</template>
<script>
export default {
components: {},
data() {
return {
assessmentForm: new Form({
name: '',
description: '',
// details: ['name', 'code', 'max_mark', 'ass1', 'ass2', 'description']
details: []
})
};
},
props: ['id'],
mounted() {
if(!helper.hasPermission('access-configuration')){
helper.notAccessibleMsg();
this.$router.push('/dashboard');
}
if(this.id)
this.get();
else {
this.addRow();
}
},
methods: {
hasPermission(permission){
return helper.hasPermission(permission);
},
addRow(){
let new_index = this.assessmentForm.details.push({
name: '',
code: '',
max_mark: '',
ass1: '',
ass2: '',
// pass_percentage: '',
description: ''
})
},
confirmDeleteDetail(index){
return dialog => this.deleteDetail(index);
},
deleteDetail(index){
this.assessmentForm.details.splice(index, 1);
},
getDetailName(index){
return index+'_detail_name';
},
getDetailCode(index){
return index+'_detail_code';
},
getDetailMaxMarkName(index){
return index+'_detail_max_mark';
},
// getDetailPassPercentageName(index){
// return index+'_detail_pass_percentage';
// },
getDetailAssessment1(index){
return index+'_detail_ass1';
},
getDetailAssessment2(index){
return index+'_detail_ass2';
},
getDetailDescriptionName(index){
return index+'_detail_description';
},
proceed(){
if(this.id)
this.update();
else
this.store();
},
store(){
let loader = this.$loading.show();
this.assessmentForm.post('/api/exam/assessment')
.then(response => {
toastr.success(response.message);
this.assessmentForm.details = [];
this.addRow();
this.$emit('completed');
loader.hide();
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
});
},
get(){
let loader = this.$loading.show();
axios.get('/api/exam/assessment/'+this.id)
.then(response => {
this.assessmentForm.name = response.name;
this.assessmentForm.description = response.description;
response.details.forEach(detail => {
this.assessmentForm.details.push({
name: detail.name,
code: detail.code,
max_mark: detail.max_mark,
ass1: detail.ass1,
ass2: detail.ass2,
description: detail.description
// pass_percentage: detail.pass_percentage,
});
});
loader.hide();
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
this.$router.push('/configuration/exam/assessment');
});
},
update(){
let loader = this.$loading.show();
this.assessmentForm.patch('/api/exam/assessment/'+this.id)
.then(response => {
toastr.success(response.message);
loader.hide();
this.$router.push('/configuration/exam/assessment');
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
});
}
}
}
</script>
This is the model (AssessmentDetail.php):
<?php
namespace App\Models\Configuration\Exam;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
class AssessmentDetail extends Model
{
use LogsActivity;
protected $fillable = [
'exam_assessment_id',
'name',
'max_mark',
'ass1',
'ass2',
// 'pass_percentage',
'description',
'options'
];
protected $casts = ['options' => 'array'];
protected $primaryKey = 'id';
protected $table = 'exam_assessment_details';
protected static $logName = 'exam_assessment_detail';
protected static $logFillable = true;
protected static $logOnlyDirty = true;
protected static $ignoreChangedAttributes = ['updated_at'];
public function assessment()
{
return $this->belongsTo('App\Models\Configuration\Exam\Assessment', 'exam_assessment_id');
}
public function getOption(string $option)
{
return array_get($this->options, $option);
}
public function scopeFilterById($q, $id)
{
if (! $id) {
return $q;
}
return $q->where('id', '=', $id);
}
public function scopeFilterByExamAssessmentId($q, $exam_assessment_id)
{
if (! $exam_assessment_id) {
return $q;
}
return $q->where('exam_assessment_id', '=', $exam_assessment_id);
}
public function scopeFilterByName($q, $name, $s = 0)
{
if (! $name) {
return $q;
}
return $s ? $q->where('name', '=', $name) : $q->where('name', 'like', '%'.$name.'%');
}
}
This is my Controller (AssessmentController)
<?php
namespace App\Http\Controllers\Configuration\Exam;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Configuration\Exam\AssessmentRequest;
use App\Repositories\Configuration\Exam\AssessmentRepository;
class AssessmentController extends Controller
{
protected $request;
protected $repo;
/**
* Instantiate a new controller instance.
*
* #return void
*/
public function __construct(
Request $request,
AssessmentRepository $repo
) {
$this->request = $request;
$this->repo = $repo;
$this->middleware('permission:access-configuration');
$this->middleware('academic.session.set');
}
/**
* Used to get all Exam Assessments
* #get ("/api/exam/assessment")
* #return Response
*/
public function index()
{
return $this->ok($this->repo->paginate($this->request->all()));
}
/**
* Used to print all Exam Assessments
* #post ("/api/exam/assessment/print")
* #return Response
*/
public function print()
{
$exam_assessments = $this->repo->print(request('filter'));
return view('print.configuration.exam.assessment', compact('exam_assessments'))->render();
}
/**
* Used to generate pdf all Exam Assessments
* #post ("/api/exam/assessment/pdf")
* #return Response
*/
public function pdf()
{
$exam_assessments = $this->repo->print(request('filter'));
$uuid = Str::uuid();
$pdf = \PDF::loadView('print.configuration.exam.assessment', compact('exam_assessments'))->save('../storage/app/downloads/'.$uuid.'.pdf');
return $uuid;
}
/**
* Used to store Exam Assessment
* #post ("/api/exam/assessment")
* #param ({
* #Parameter("name", type="string", required="true", description="Name of Exam Assessment"),
* #Parameter("description", type="text", required="optional", description="Description of Exam Assessment")
* })
* #return Response
*/
public function store(AssessmentRequest $request)
{
$exam_assessment = $this->repo->create($this->request->all());
// dd('$exam_assessment');
return $this->success(['message' => trans('exam.assessment_added')]);
}
/**
* Used to get Exam Assessment detail
* #get ("/api/exam/assessment/{id}")
* #param ({
* #Parameter("id", type="integer", required="true", description="Id of Exam Assessment"),
* })
* #return Response
*/
public function show($id)
{
return $this->ok($this->repo->findOrFail($id));
}
/**
* Used to update Exam Assessment
* #patch ("/api/exam/assessment/{id}")
* #param ({
* #Parameter("id", type="integer", required="true", description="Id of Exam Assessment"),
* #Parameter("name", type="string", required="true", description="Name of Exam Assessment"),
* #Parameter("description", type="text", required="optional", description="Description of Exam Assessment")
* })
* #return Response
*/
public function update($id, AssessmentRequest $request)
{
$exam_assessment = $this->repo->findOrFail($id);
$exam_assessment = $this->repo->update($exam_assessment, $this->request->all());
return $this->success(['message' => trans('exam.assessment_updated')]);
}
/**
* Used to reorder all Details of assessment
* #frontend ("/api/exam/assessment/{id}/reorder")
* #return Response
*/
public function reorder($id)
{
$exam_assessment = $this->repo->findOrFail($id);
$this->repo->reorder($exam_assessment, $this->request->all());
return $this->success(['message' => trans('exam.assessment_updated')]);
}
/**
* Used to delete Exam Assessment
* #delete ("/api/exam/assessment/{id}")
* #param ({
* #Parameter("id", type="integer", required="true", description="Id of Exam Assessment"),
* })
* #return Response
*/
public function destroy($id)
{
$exam_assessment = $this->repo->deletable($id);
$this->repo->delete($exam_assessment);
return $this->success(['message' => trans('exam.assessment_deleted')]);
}
}
These are the routes for the Assessment from Api.php
Route::get('/exam/assessment/{id}', 'Configuration\Exam\AssessmentController#show');
Route::post('/exam/assessment', 'Configuration\Exam\AssessmentController#store');
Route::patch('/exam/assessment/{id}', 'Configuration\Exam\AssessmentController#update');
Route::delete('/exam/assessment/{id}', 'Configuration\Exam\AssessmentController#destroy');
Thank you all for your comments.
I finally found the solution.
Apparently, in my controller(AssessmentController) my construct method is getting the input from AssessmentRepository (App\Repository).
public function __construct(
Request $request,
AssessmentRepository $repo
) {
$this->request = $request;
$this->repo = $repo;
$this->middleware('permission:access-configuration');
$this->middleware('academic.session.set');
}
Then $repo is called in my store, update, show, reorder and other methods.
I've never seen or used App\Repositories before.
You learn every day!
Related
Why is the input not sent to the request?
I add tag input into my form with name=fullname, but I got an error; it says that "Field 'fullname' doesn't have a default value." Is there something wrong with my code? I have adding attribute name in my tag input, but it still doesn't work {!! Form::open(['route' => 'users.store']) !!} <div class="row"> <div class="col-25"> <label>Unit Name</label> </div> <div class="col-75"> {!! Form::select('division', $divisions, null, ['class' => 'form-control']) !!} </div> </div> <div class="row"> <div class="col-25"> <label>Full Name</label> </div> <div class="col-75"> <input type="text" name="fullname" aria-label="fullname" autocomplete="off"> </div> </div> <div class="row"> <div class="col-25"> <label>Username</label> </div> <div class="col-75"> <input type="text" name="username" aria-label="username"" autocomplete="off"> </div> </div> <div class="row"> <div class="col-25"> <label>Password</label> </div> <div class="col-75"> <input type="password" name="password" aria-label="password" autocomplete="off"> </div> </div> <div class="row"> <input type="submit" value="Submit"> </div> {!! Form::close() !!} This is the error This is create and store controller public function create() { return view('user_super_admin.create') ->with('divisions', $this->divisions); } /** * Store a newly created User in storage. * * #param CreateUserRequest $request * * #return Response */ public function store(CreateUserRequest $request) { $input = $request->all(); $user = $this->userRepository->create($input); Flash::success('User saved successfully.'); return redirect(route('users.index')); } CreateUserRequest public function rules() { return User::$rules; } User Model class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * #var array */ protected $fillable = [ 'username', 'password', 'group_id', 'division_id', ]; /** * The attributes that should be hidden for arrays. * * #var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * #var array */ protected $casts = [ 'username' => 'string', 'password' => 'string', 'group_id' => 'integer', 'division_id' => 'integer', 'email_verified_at' => 'datetime', ]; public function group() { return $this->belongsTo("App\Models\Group"); } public function division() { return $this->belongsTo("App\Models\Division"); } } User Repository /** * #var array */ protected $fieldSearchable = [ 'fullname', 'username', 'password', 'role_id', 'division_id', 'remember_token' ]; /** * Configure the Model **/ public function model() { return User::class; }
Angular 6 reactive forms. FormArray of select
I followed Angular Reative Form guide that explains how to add a FormArray of Adrresses to a FormGroup. Now I want to have a hero that can have different powers, selecting them from a select, or better from a dynamic array of select. Passing from the example of Angular Docs to my desired functionality I can't make it to run. This is my hero-form.ts #Component({ selector: 'app-hero-form', templateUrl: './hero-form.component.html', styleUrls: ['./hero-form.component.css'] }) export class HeroFormComponent implements OnInit, OnChanges { heroForm: FormGroup; nameChangeLog: string[] = []; hero: Hero = new Hero(); allPowers: Power[] = []; constructor(private fb: FormBuilder, private powerService: PowerService) { this.createForm(); this.logNameChange(); } ngOnInit() { this.powerService.getAll().subscribe(powers => this.allPowers = powers); } createForm() { this.heroForm = this.fb.group({ name: ['', Validators.required], powers: this.fb.array([]), }); } ngOnChanges() { this.rebuildForm(); } rebuildForm() { this.heroForm.reset({ name: this.hero.name }); this.setPowersControl(this.hero.powers); } setPowersControl(powers: Power[]) { const powersFGs = powers.map(pow => this.fb.group(pow)); const powersFormArray = this.fb.array(powersFGs); this.heroForm.setControl('powers', powersFormArray); } get powers(): FormArray { const pows = this.heroForm.get('powers') as FormArray; return pows; } addPowerChoice() { this.powers.push(this.fb.control(new Power())); // this.powers.push(this.fb.group(new Power(), Validators.required)); } onSubmit() { this.hero = this.prepareSaveHero(); console.log('SAVING HERO', this.hero); // this.heroService.updateHero(this.hero).subscribe(/* error handling */); this.rebuildForm(); } prepareSaveHero(): Hero { const formModel = this.heroForm.value; // deep copy of form model lairs const powersDeepCopy: Power[] = formModel.powers.map( (pow: Power) => Object.assign({}, pow) ); // return new `Hero` object containing a combination of original hero value(s) // and deep copies of changed form model values const saveHero: Hero = { id: this.hero.id, name: formModel.name as string, // addresses: formModel.secretLairs // <-- bad! powers: powersDeepCopy }; return saveHero; } revert() { this.rebuildForm(); } logNameChange() { const nameControl = this.heroForm.get('name'); nameControl.valueChanges.forEach( (value: string) => this.nameChangeLog.push(value) ); } } This is my hero-form.html <form [formGroup]="heroForm" (ngSubmit)="onSubmit()"> <div style="margin-bottom: 1em"> <button type="submit" [disabled]="heroForm.pristine" class="btn btn-success">Save </button> <button type="button" (click)="revert()" [disabled]="heroForm.pristine" class="btn btn-danger">Revert</button> </div> <!-- Hero Detail Controls --> <div class="form-group"> <label class="center-block">Name: <input class="form-control" formControlName="name"> </label> </div> <div formArrayName="powers" class="well well-lg"> <div *ngFor="let pow of powers.controls; let i=index" [formControlName]="i"> <!-- The repeated power template --> <h4>Potere #{{i + 1}}</h4> <div style="margin-left: 1em;"> <div class="form-group"> <label class="center-block">Power: <select class="form-control"> <option *ngFor="let pow of allPowers" [value]="pow">{{pow.name}}</option> </select> </label> </div> </div> <br> <!-- End of the repeated address template --> </div> <button (click)="addPowerChoice()" type="button">Add a Power</button> </div> </form> <p>heroForm value: {{ heroForm.value | json}}</p> <h4>Name change log</h4> <div *ngFor="let name of nameChangeLog">{{name}}</div> This is power-service that is only returning stubbed data #Injectable({ providedIn: 'root' }) export class PowerService { constructor() { } getAll(): Observable<Power[]> { return of(this.getProds()); } getProds(): Power[] { const powers = []; for (let i = 0; i < 10; i++) { const pow = new Power(); pow.id = i+''; pow.name = 'Power ' + i; powers.push(pow); } return powers; } } And these are my data models export class Hero { id: number; name: string; powers: Power[]; } export class Power { id: string = ''; name: string = ''; } Here I have make a stackblitz example but it's not working
I've solved I have moved formControlName from div onto select as suggested by Lucas Klaassen, and changed [value] to [ngValue] onto option <form [formGroup]="heroForm" (ngSubmit)="onSubmit()"> <div style="margin-bottom: 1em"> <button type="submit" [disabled]="heroForm.pristine" class="btn btn-success">Save </button> <button type="button" (click)="revert()" [disabled]="heroForm.pristine" class="btn btn-danger">Revert </button> </div> <!-- Hero Detail Controls --> <div class="form-group"> <label class="center-block">Name: <input class="form-control" formControlName="name"> </label> </div> <div formArrayName="powers" class="well well-lg"> <div *ngFor="let pow of powers.controls; let i=index"> <!-- The repeated power template --> <h4>Potere #{{i + 1}}</h4> <div style="margin-left: 1em;"> <div class="form-group"> <label class="center-block">Power: <select class="form-control" [formControlName]="i"> <option *ngFor="let pow of allPowers" [ngValue]="pow">{{pow.name}}</option> </select> </label> </div> </div> <br> <!-- End of the repeated address template --> </div> <button (click)="addPowerChoice()" type="button">Add a Power</button> </div> </form> <p>heroForm value: {{ heroForm.value | json}}</p> <h4>Name change log</h4> <div *ngFor="let name of nameChangeLog">{{name}}</div> Then I have changed onSubmit() adding a Hero's constructor call as follow onSubmit() { this.hero = this.prepareSaveHero(); console.log('SAVING HERO', this.hero); // this.heroService.updateHero(this.hero).subscribe(/* error handling */); this.hero = new Hero(); this.rebuildForm(); } Then I have added a custom constructor to Hero class export class Hero { id: number; name: string; powers: Power[]; constructor() { this.id = 0; this.name = ''; this.powers = []; } } Now it's working and correctly rebuilding form after submit
how to insert data in database using cakephp
i have a table name stores and i have controller name is StoresController.php and model name is Stores.php and have a add.ctp file inside Stores folder but i an unable to insert data from form.here is my add.ctp file <div class="row form-main"> <div class="panel panel-default"> <div class="panel-body"> <?php echo $this->Form->create('Store', array('class'=>"contact- form")); ?> <div class="form-group"> <div class="col-sm-6"> <?php echo $this->Form->input('name',array('required'=>false,'class'=>"form- control", 'placeholder'=>"Enter Name","label"=>false)); ?> </div> <div class="col-sm-6"> <?php echo $this->Form- >input('address1',array('required'=>false,'class'=>"form-control", 'placeholder'=>"Enter Address1","label"=>false)); ?> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" name="submit" value="Submit" class="btn btn-success"> <button type="submit" class="btn btn-info">Cancel</button> </div> </div> <?php echo $this->Form->end(); ?> here is my StoresController.php <?php App::uses('AppController', 'Controller'); class StoresController extends AppController { var $uses = array(); var $component = array("Common"); public $paginate = array(); public function add(){ $this->layout = 'user_layout'; $user_id = $this->UserAuth->getUserId(); $owner_id = $this->Common->getOwnerId($user_id); if ($this->request->is('post')) { $this->Store->create(); if ($this->Store->save($this->request->data)) { $this->Flash->success(__('User has been Added')); return $this->redirect(array('action' => 'add')); } $this->Flash->error(__('Unable to add your post.')); } } } ?> and i am getting error Call to a member function create() on a non-object in controller
you should be using: $this->Form->create('Store'); public function add(){ $this->layout = 'user_layout'; $user_id = $this->UserAuth->getUserId(); $owner_id = $this->Common->getOwnerId($user_id); if ($this->request->is('post')) { $this->Store->create('Store'); if ($this->Store->save($this->request->data)) { $this->Flash->success(__('User has been Added')); return $this->redirect(array('action' => 'add')); } $this->Flash->error(__('Unable to add your post.')); } }
Yes, I solved the problem. There was a minor problem. I forgot the following line in the controller: var $uses = array('Store');
how can I disable a button in angular 2 without using a form group
I just need to enable the button if all the forms is filled and disable it if not **here is my code : ** <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <form [formGroup]="OvertimeForm" (ngSubmit)="createOvertime()"> <div class="form-group"> <label class="control-label" for="employee" >Employee:</label> <select2 [data]="employee" [options]="options" [width]="570" [value]="employee_value" (valueChanged)="changed($event)" required> </select2> </div> <div class="form-group"> <div class="row"> <div class="col-md-6"> <label>Start Time:</label> <timepicker [(ngModel)]="start_time" [showMeridian]="ismeridian" formControlName="start_time" ></timepicker> <button type="button" class="btn btn-info" (click)="toggleMode()">12H / 24H</button> </div> <div class="col-md-6"> <label>End Time:</label> <timepicker [(ngModel)]="end_time" [showMeridian]="ismeridian" formControlName="end_time" ></timepicker> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-12"> <label>Reason</label> <textarea class="form-control" name="remarks" id="remarks" rows="3" placeholder="Reason ..." formControlName="remarks" required></textarea> </div> </div> </div> <button type="submit" class="btn btn-primary pull-right" [disabled]="!OvertimeForm.valid">Add</button> </form> but [disabled]="!OvertimeForm.valid" is not working I use different package like time picker and select 2, they have their own function in getting their values this is the code in my component this.OvertimeForm = _fb.group({ 'start_time': [this.ot.start_time, [Validators.required]], 'end_time': [this.ot.end_time, [Validators.required]], 'remarks': [this.ot.remarks, [Validators.required]], 'created_by': [this.ot.created_by, [Validators.required]] }); } ngOnInit() { this.get_employee(); this.get_UserId(); } get_UserId(){ this._auth_service.getUser(). subscribe( data => { let user = data; // fetched this.user_id = user.id; this.OvertimeForm.value.created_by = this.user_id; }, err => console.error(err) ); } get_employee(){ let employees = this._common_service.getEmployees(). subscribe( data => { this.emp = Array.from(data); // fetched record this.employee = this.emp; this.employee_value = []; this.options = { multiple: true } this.current = this.employee_value; }, err => console.error(err) ); } changed(data: any) { this.current = data.value; this.OvertimeForm.value.employee_id = this.current; this.OvertimeForm.value.start_time = moment(this.start_time).format("HH:mm:ss"); this.OvertimeForm.value.end_time = moment(this.end_time).format("HH:mm:ss"); // this.OvertimeForm.valid = true; // console.log(this.OvertimeForm.valid); } remarks(event:any){ let a = event; console.log(a); } createOvertime(){ let ot = this.OvertimeForm.value; console.log(ot); this._OTservice .createOT(ot) .subscribe( data => { this.poststore = Array.from(data); this.success_title = "Success"; this.success_message = "A new user record was successfully added."; setTimeout(() => { this.close(); }, 1000); }, err => this.catchError(err) ); } private catchError(error: any){ let response_body = error._body; let response_status = error.status; if( response_status == 500 ){ this.error_title = 'Error 500'; this.error_message = 'The given data failed to pass validation.'; } else if( response_status == 200 ) { this.error_title = ''; this.error_message = ''; } } //time picker public toggleMode():void { this.ismeridian = !this.ismeridian; }
try this, <button type="submit" [disabled]="!ngForm.valid">Submit</button>
Replace form tag line with : <form #OvertimeForm=ngForm novalidate (ngSubmit)="createOvertime()">
Use: [attr.disabled]="!OvertimeForm.valid"
use novalidate in your form tag. please find below code for reference. OvertimeForm.html <form [formGroup]="myNgForm" novalidate (ngSubmit)="saveAsConfirm(myNgForm)"> ////other elements <button type="submit" class="btn btn-success" [disabled]="!myNgForm.valid">Save</button> </form> hope this will help you.
MVC5 Mqsql Issue
After Update of Model from database in Entity Framework. Json Data not populate into textbox. when i use DeveloperTool i found a error "There is already an open DataReader associated with this Connection which must be closed first."[Error 505] Help me for resolve this problem.am using MySql in my project. When i use only one table in Model then i didn't get any error but when i update model then my project not working. If i add all the tables in Model then I face same problem. Here is my code Controller:- // GET: Chains public ActionResult Index() { ViewData["chain_name"] = new SelectList(db.chains, "code", "name"); return View(db.chains.ToList()); } //Action Function callby javascript [HttpPost] public ActionResult Action(string code) { var query = from c in db.chains where c.code == code select c; return Json(query);//Return Json Result } View:- #using (#Html.BeginForm()) { #Html.AntiForgeryToken() <div class="form-horizontal"> <hr /> <div class="form-group"> <label class="col-sm-2 control-label"> Select Chain </label> <div class="col-md-3"> #Html.DropDownList("ddlchainname", (SelectList)ViewData["chain_name"], new { onchange = "Action(this.value);", #class = "form-control" }) </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"> Chain Name </label> <div class="col-md-3"> #Html.TextBox("ChainName", null, new { #class = "form-control" }) </div> <label class="col-sm-2 control-label"> Username </label> <div class="col-md-3"> #Html.TextBox("username", null, new { #class = "form-control" }) </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"> Chain Code </label> <div class="col-md-3"> #Html.TextBox("ChainCode", null, new { #class = "form-control" }) </div> </div> </div> } <script type="text/javascript"> function Action(code) { $.ajax({ url: '#Url.Action("Action", "Chains")', type: "POST", data: { "code": code }, "success": function (data) { if (data != null) { var vdata = data; $("#ChainName").val(vdata[0].name); $("#ChainCode").val(vdata[0].code); $("#username").val(vdata[0].username); } } }); }
Try this approach: using (var db = new ChainEntities()) { ViewData["chain_name"] = new SelectList(db.chains, "code", "name"); return View(db.chains.ToList()); } This way you open the connection only once then dispose when done. Sane for action: [HttpPost] public ActionResult Action(string code) { using (var db = new ChainEntities()) { var query = from c in db.chains where c.code == code select c; return Json(query);//Return Json Result } }