How to attach to User create multiple checkboxes during laravel authentication - database

Good afternoon everyone!
In my project I have to create a new user which will be a restaurant directly in the user's registration.
Once registered, I gave the possibility to associate more types of restaurant to the logged in user.
I made already migrations and relations everything is working.
This is what i wrote to permit the logged user(restaurant) to add more typologies.
public function typologyAdd() {
$typologies = Typology::all();
return view('pages.typology-add',compact('typologies'));
}
public function typologyStore(Request $request) {
$data = $request -> all();
$user = Auth::user();
$typologies = Typology::findOrFail($data['typologies']);
$user -> typologies() -> sync($typologies);
return redirect() -> route('home');
}
So this is working only once i register the user.
i want to put this logic when i'm in registration page.
I was trying to modify the RegisterController but i don't know how to do that:
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'indirizzo' => ['required' ,'string','max:255'],
'piva' => ['required','string','min:11','max:11','digits:11','unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'indirizzo' => $data['indirizzo'],
'piva' => $data['piva'],
'password' => Hash::make($data['password']),
]);
}
and to put checkboxes inside the Register.blade.php
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row">
<label for="indirizzo" class="col-md-4 col-form-label text-md-right">{{ __('indirizzo') }}</label>
<div class="col-md-6">
<input id="indirizzo" type="text" class="form-control" name="indirizzo" value="{{ old('indirizzo') }}" maxlength="255" required>
#error('indirizzo')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="piva" minlenght="11" maxlength="11" class="col-md-4 col-form-label text-md-right">{{ __('piva') }}</label>
<div class="col-md-6">
<input id="piva" type="text" class="form-control #error('piva') is-invalid #enderror" name="piva" value="{{ old('piva') }}" required>
#error('piva')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
I hope someone will give me some ideas on how to do it, thanks to those who will read and answer

In the RegisterController.php you can get the newly created user by doing the below.
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'indirizzo' => $data['indirizzo'],
'piva' => $data['piva'],
'password' => Hash::make($data['password']),
]);
// Do actions on $user and finally return $user
return $user;
}
Add new validations rules if you need any & also if you are doing relation data entry i would suggest to do a SQL transaction based insert. Commit data if no SQL error is thrown. Else rollback the changes to prevent issues.

Related

Getting the id of the form from table as reference to the next form in Laravel

I am very new to Laravel. I am currently doing a Laravel project where a person can submit a proposal. The Laravel version I'm using is Laravel Framework 8. I divided the proposal form into 7 pages. I also have 7 tables in the database. So the data of each page will be saved into each of the tables. 1 page = 1 table. This means I also have 7 models. In conclusion, I have 7 views, 7 controllers, 7 models, and 7 tables (if this is not a good practice please tell me)
Here is an example of my code
Route
web.php
Route::get('/form/details', [App\Http\Controllers\Lect\Form\Step1Controller::class, 'createStepOne'])->name('form.create.step.one');
Route::post('/form/details', [App\Http\Controllers\Lect\Form\Step1Controller::class, 'postCreateStepOne'])->name('form.create.step.one.post');
Route::get('/form/learning-outcomes', [App\Http\Controllers\Lect\Form\Step2Controller::class, 'createStepTwo'])->name('form.create.step.two');
Route::post('/form/learning-outcomes', [App\Http\Controllers\Lect\Form\Step2Controller::class, 'postCreateStepTwo'])->name('form.create.step.two.post');
...
Model
Step1.php
class Step1 extends Model {
use HasFactory;
public $table = 'forms';
protected $fillable = [
'title',
'code',
'creditvalue',
'mqflevel',
'affectedbatch',
'kulliyyah',
'department',
'synopsis',
'classification',
'prerequisite',
];
}
Step2.php
class Step2 extends Model {
use HasFactory;
public $table = 'proposal_learning_outcome';
public $timestamps = false;
protected $fillable = [
'proposal_id',
'lo_id',
'outcomes',
'bloom_c',
'bloom_a',
'bloom_p',
'ki',
'po',
];
}
Controller
Step1Controller.php
class Step1Controller extends Controller {
public function createStepOne(Request $request) {
return view('form.step1');
}
public function postCreateStepOne(Request $request) {
$validatedData = $request->validate([
'title' => 'required',
'code' => 'required|unique:forms',
'creditvalue' => 'required|numeric',
'mqflevel' => 'required|numeric',
'affectedbatch' => 'required',
'kulliyyah' => 'required',
'department' => 'required',
'synopsis' => 'required',
'classification' => 'required',
'prerequisite' => 'required',
]);
$step1 = new Step1;
$step1->title=$request->input('title');
$step1->code=$request->input('code');
$step1->creditvalue=$request->input('creditvalue');
$step1->mqflevel=$request->input('mqflevel');
$step1->affectedbatch=$request->input('affectedbatch');
$step1->kulliyyah=$request->input('kulliyyah');
$step1->department=$request->input('department');
$step1->synopsis=$request->input('synopsis');
$step1->classification=$request->input('classification');
$step1->prerequisite=$request->input('prerequisite');
$step1->created_by=Auth::user()->username;
$result = $step1->save();
return redirect()->route('form.create.step.two');
}
}
Step2Controller.php
class Step2Controller extends Controller {
public function createStepTwo(Request $request) {
return view('form.step2');
}
public function postCreateStepTwo(Request $request) {
$validatedData = $request->validate([
'proposal_id' => 'required',
'lo_id' => 'required',
'outcomes' => 'required',
'bloom_c' => 'required',
'bloom_a' => 'required',
'bloom_p' => 'required',
'ki' => 'required',
'po' => 'required',
]);
foreach($request->lo_id as $key=>$lo_id) {
$data = new Step2();
$data->proposal_id=$request->input('proposal_id');
$data->lo_id=$lo_id;
$data->outcomes=$request->outcomes[$key];
$data->bloom_c=$request->bloom_c[$key];
$data->bloom_a=$request->bloom_a[$key];
$data->bloom_p=$request->bloom_p[$key];
$data->ki=$request->ki[$key];
$data->po=$request->po[$key];
$data->save();
}
return redirect()->route('form.create.step.three');
}
}
View
step1.blade.php
<form action="{{ route('form.create.step.one.post') }}" method="POST">
#csrf
<div class="card">
Step 1: Basic Info
</div>
<div class="card-body">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-group">
<label for="title">Course Title</label>
<input type="text" name="title" class="form-control text-lg" id="title" placeholder="">
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="code">Course Code</label>
<input type="text" name="code" class="form-control text-lg" id="code" placeholder="">
</div>
<div class="form-group">
<label for="creditvalue">Credit Value</label>
<input type="number" name="creditvalue" class="form-control text-lg" id="creditvalue" placeholder="">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="mqflevel">MQF Level</label>
<input type="number" name="mqflevel" class="form-control text-lg" id="mqflevel" placeholder="">
</div>
<div class="form-group">
<label for="affectedbatch">Affected Batch</label>
<input type="text" name="affectedbatch" class="form-control text-lg" id="affectedbatch" placeholder="">
</div>
</div>
</div>
<div class="form-group">
<label for="kulliyyah">Centre of Studies</label>
<select type="text" class="form-control text-lg" name="kulliyyah" id="kulliyyah">
<option value="Kulliyyah of Information and Communication Technology">Kulliyyah of Information and Communication Technology</option>
<option value="Kulliyyah of Education">Kulliyyah of Education</option>
<option value="Kulliyyah of Engineering">Kulliyyah of Engineering</option>
<option value="Kulliyyah of Architecture and Environmental Design">Kulliyyah of Architecture and Environmental Design</option>
</select>
</div>
<div class="form-group">
<label for="department">Department/Unit</label>
<select type="text" class="form-control text-lg" name="department" id="department">
<option value="Department of Computer Science">Department of Computer Science</option>
<option value="Department of Information System">Department of Information System</option>
</select>
</div>
<div class="form-group">
<label for="synopsis">Course Synopsis</label>
<textarea type="text" class="form-control text-lg" name="synopsis" rows="5" id="synopsis" placeholder=""></textarea>
</div>
<div class="form-group">
<label for="classification">Course Classification within the Curriculum</label>
<input type="text" class="form-control text-lg" name="classification" id="classification" placeholder="eg: CSC 1305">
</div>
<div class="form-group">
<label for="prerequisite">Prerequisite(s) (if any)</label>
<input type="text" class="form-control text-lg" name="prerequisite" id="prerequisite" placeholder="">
</div>
</div>
<div class="card-footer text-right">
<button type="submit" class="btn btn-primary">Next</button>
</div>
</div>
</form>
step2.blade.php
<form action="{{ route('form.create.step.two.post') }}" method="POST">
#csrf
<div class="card">
Step 2: Course Learning Outcomes</div>
<div class="card-body">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-group">
<label for="proposal_id">Proposal ID</label>
<input type="text" class="form-control text-lg" name="proposal_id" id="proposal_id" placeholder="">
</div>
<div class="table-responsive">
<form method="post" id="dynamic_form">
<span id="result"></span>
<table class="table table-bordered" id="user_table">
<thead>
<tr class="table-active">
<th rowspan="2">No.</th>
<th rowspan="2" class="w-50">Outcomes</th>
<th colspan="3" class="w-25">Bloom's Taxonomy</th>
<th rowspan="2">Soft skills (KI)</th>
<th rowspan="2">Programme Outcomes (PO)</th>
<th rowspan="2">Add</th>
</tr>
<tr class="table-active">
<th>C</th>
<th>A</th>
<th>P</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-control text-lg" name="lo_id[]"/></td>
<td><textarea class="form-control text-lg" name="outcomes[]"></textarea></td>
<td><input class="form-control text-lg" name="bloom_c[]"/></td>
<td><input class="form-control text-lg" name="bloom_a[]"/></td>
<td><input class="form-control text-lg" name="bloom_p[]"/></td>
<td><input class="form-control text-lg" name="ki[]"/></td>
<td><input class="form-control text-lg" name="po[]"/></td>
<td>Remove</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col-md-6 text-left">
Previous
</div>
<div class="col-md-6 text-right">
<button type="submit" class="btn btn-primary ">Next</button>
</div>
</div>
</div>
</div>
</form>
and the other 5 steps are basically like that.
My current problem is how can I get the proposal_id of the first form (step1) as a reference to the next 6 forms. The proposal_id is used as a foreign key for other tables. The proposal_id is auto-incremented in the table.
The reason I divided them into many tables is that some parts of the form are in table format as shown in step2.blade.php. The image below a reference.
Form example
For now, as you can see in the code, my current solution is to manually input the proposal_id in each form (which is not practical because they would not know the proposal_id in the first place). My current code has no issue. It can be saved into the database as normal.
How can I solve this issue? Or is there another way to fill up this form? Thank you in advance.
You have two solution, the first I see is to pass the proposal_id as a parameter of your route (see below).
Route::get('/form/learning-outcomes{proposal_id}', [App\Http\Controllers\Lect\Form\Step2Controller::class, 'createStepTwo'])->name('form.create.step.two');
The second is to save it in your session variable and you can acess it throught your form
session()->put('proposal_id', $proposal_id)
To get it in your second form use :
session()->get('proposal_id')
Update
Make sure to add this line in your migration file:
$table->id('proposal_id')
where the proposal_id is your primary key autoincrement. By default if you don't put anything as id parameter, it will be id in your column table.
$table->id()//COLUMN TABLE WILL CONTAINT id as name
$table->id('proposal_id')//COLMUN TABLE WILL CONTAINT proposal_id as name
The answer was helpful but not actually what I asked (sorry if my question was not clear). I found the answer to my question.
I wanted to get the proposal_id from the first form. I called the lastest added row in the table like this:
$proposal_id = DB::table('forms')
->select('proposal_id')
->orderBy('proposal_id', 'desc')
->limit(1)
->value('proposal_id');
I added this code in the Step1Controller after
$result = $step1->save();
And then I save it into session like crazy4dev suggested:
$request->session()->put('proposal_id', $proposal_id);
return redirect()->route('form.create.step.two', compact('proposal_id'));
I can access the proposal_id in the Step2Controller with:
$proposal_id = $request->session()->get('proposal_id');

Credentials method failing on laravel

I am trying to make a switcher in my website (made in laravel), i have solved a lot of problems and at now, i am getting error at the function
protected function credentials(Request $request)
{
return $request->only('email');
}
My paths are like: localhost/es/password/email
I attach the code, thank you.
email.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Reset Password') }}</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<form method="POST" action="{{ route( 'password.email', app()->getLocale()) }}">
#csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Send Password Reset Link') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
web.php
Route::redirect('/', '/en');
Route::group(['prefix' => '{language}',
'where' => ['language' => '[a-zA-Z]{2}']],
function(){
Route::get('/', 'HomeController#index')->name('home');
Route::get('/home', 'HomeController#index')->name('home');
Auth::routes(['verify' => true]);
Route::get('/projects', 'projectsController#create')->name('projects');
Route::post('/createProject', 'projectsController#store');
Route::post('/modifyProject/{id}', 'projectsController#update');
Route::get('/projects/{id}/delete', 'projectsController#destroy');
Auth::routes();
Route::get('/logout', '\App\Http\Controllers\Auth\LoginController#logout');
});
If you need something more of my app, say to this post and i will paste into in.
Regards
I have seemed that if i change the credentials functions to:
protected function credentials(Request $request)
{
//dd($request);
return $request->only('email', '#defaultLocale');
}
the response of
$response = $this->broker()->sendResetLink(
$this->credentials($request)
);
is passwords.throttle, and should be passwords.sent

Recaptcha cant get response in angular after changing page

I have a problem with my angular application. I have a register page on my site. Normally when I get straight to the register page it works fine, after submitting the form is sent and user is registered. Problem appears when I for example load register page then go to login page and then again to register. In this case the form is not sent to server.
I tried to figure it out and even to repair by refreshing page after clicking register link but it didn't help.
I debug my application a little and found that it's recaptcha causing my problem. I use angular-recaptcha version 2.2.5; Tried to log the output of vcRecaptchaService.getResponse() but nothing showed in console.
Here is some code, where the problem may lay:
Request of form
$scope.registerRequest = (form) => {
$scope.$broadcast('show-errors-check-validity');
if (!form.$valid) {
return;
}
$scope.isLoading = true;
$scope.formData.reCaptcha = vcRecaptchaService.getResponse();
apiRequest.post('user/register', $scope.formData).success((response) => {
$scope.isLoading = false;
$scope.registered = true;
$scope.formData = {};
});
};
Routes:
app.config(['$routeProvider', ($routeProvider) => {
$routeProvider
.when('/auth/login', {
controller: 'authLogin',
label: 'Logowanie',
templateUrl: 'app/components/authLoginView.html',
access: ['UNAUTH']
})
.when('/auth/register/', {
controller: 'authRegister',
label: 'Rejestracja',
templateUrl: 'app/components/authRegisterView.html',
access: ['UNAUTH']
})
.when('/auth/register/confirm', {
controller: 'authRegister',
label: 'Potwierdzenie rejestracji',
templateUrl: 'app/components/authRegisterView.html',
access: ['UNAUTH']
})
.when('/auth/register/resend', {
controller: 'authRegister',
label: 'Rejestracja',
templateUrl: 'app/components/authRegisterView.html',
access: ['UNAUTH']
})
}]);
And some HTML:
<div ng-if="section == 'register'" class="container employer-container">
<form name="registerForm" class="form-horizontal col-sm-6 col-sm-offset-3" loader is-loading="isLoading">
<h4 class="employer-h4">Rejestracja</h4>
<p class="bg-success text-success col-xs-12" ng-show="registered">
Użytkownik został zarejestrowany. Na podany adres e-mail wysłaliśmy dalsze instrukcje.
</p>
<div ng-hide="registered">
<div class="form-group" show-errors>
<label for="email" class="col-md-3 control-label">E-mail:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="email" placeholder="E-mail"
ng-model="formData.email" name="username"
ng-required="true">
</div>
</div>
<div class="form-group" show-errors>
<label for="password" class="col-md-3 control-label">Hasło:</label>
<div class="col-md-9">
<input type="password" class="form-control" id="password" placeholder="Hasło"
ng-model="formData.password" name="password" ng-minlength="5"
ng-required="true" equals="{{ formData.confirmPassword }}">
</div>
</div>
<div class="form-group" show-errors>
<label for="confirmPassword" class="col-md-3 control-label">Powtórz hasło:</label>
<div class="col-md-9">
<input type="password" class="form-control" id="confirmPassword" placeholder="Powtórz hasło"
ng-model="formData.confirmPassword" name="confirmPassword" ng-minlength="5"
ng-required="true" equals="{{ formData.password }}">
</div>
</div>
<div class="form-group" show-errors>
<label class="col-md-3 control-label" for="userType">Rodzaj konta:</label>
<div class="col-md-9">
<div class="btn-group" dropdown>
<button type="button" class="btn btn-default dropdown-toggle form-control"
id="userType" name="userType" dropdown-toggle ng-model="formData.userType"
ng-required="true">
{{ userTypes[formData.userType] || 'rodzaj konta' }} <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="(key, userType) in userTypes">
{{ ::userType }}
</li>
</ul>
</div>
</div>
</div>
<div class="form-group" show-errors>
<div class="col-md-3"></div>
<div class="col-md-9">
<input class="form-control" type="checkbox" id="acceptTerms" ng-model="formData.acceptedTerms" name="acceptTerms" ng-required="true">
<label class="control-label" style="text-align: left;" for="acceptTerms">Zgadzam się z  Regulaminem</label>
</div>
</div>
<div class="form-group" show-errors>
<div class="col-md-3"></div>
<div class="col-md-9">
<input class="form-control" type="checkbox" id="acceptTerms2" ng-model="formData.acceptedTerms2" name="acceptTerms2" ng-required="true">
<label class="control-label" style="text-align: left;" for="acceptTerms2">Wyrażam zgodę na przetwarzanie moich danych w celu realizacji usług w ramach Serwisu i akceptuję Politykę Prywatności..</label>
</div>
</div>
<div class="form-group" show-errors>
<div class="col-md-3"></div>
<div class="col-md-9">
<input class="form-control" type="checkbox" id="acceptTerms3" ng-model="formData.acceptedTerms3" name="acceptTerms3" ng-required="true">
<label class="control-label" style="text-align: left;" for="acceptTerms3">Wyrażam zgodę na przetwarzanie moich danych w celach marketingowych.</label>
</div>
</div>
<div class="form-group">
<div class="col-md-9 col-md-offset-3">
<div vc-recaptcha key="'key'"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-3">
Zapomniane hasło |
Logowanie
</div>
<div class="col-md-3 text-right">
<button type="submit" class="btn btn-info" ng-click="registerRequest(registerForm)">Zarejestruj</button>
</div>
</div>
</div>
</form>
</div>
Problem could be seen here: http://pze2.biuro.netivo.pl/
Answering to one of questions about ['UNAUTH'] in my routes. It is for allowing only users who are not logged in to enter this page.
Thanks to Vinny I managed to solve the problem.
The problem lies as he said in reCaptcha.getResponse() not getting right widget.
For those who will have same problem I put the solution in my code:
Request:
$scope.registerRequest = (form) => {
$scope.$broadcast('show-errors-check-validity');
if (!form.$valid) {
return;
}
$scope.isLoading = true;
apiRequest.post('user/register', $scope.formData).success((response) => {
$scope.isLoading = false;
$scope.registered = true;
$scope.formData = {};
});
};
HTML:
<div ng-if="section == 'register'" class="container employer-container">
<form name="registerForm" class="form-horizontal col-sm-6 col-sm-offset-3" loader is-loading="isLoading">
<h4 class="employer-h4">Rejestracja</h4>
<p class="bg-success text-success col-xs-12" ng-show="registered">
Użytkownik został zarejestrowany. Na podany adres e-mail wysłaliśmy dalsze instrukcje.
</p>
<div ng-hide="registered">
...
<div class="form-group">
<div class="col-md-9 col-md-offset-3">
<div vc-recaptcha ng-model="formData.reCaptcha" key="'key'"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-3">
Zapomniane hasło |
Logowanie
</div>
<div class="col-md-3 text-right">
<button type="submit" class="btn btn-info" ng-click="registerRequest(registerForm)">Zarejestruj</button>
</div>
</div>
</div>
</form>
</div>

POST methood not working getting 500 internal server error in angularjs

I am trying to create a user with the help of sending data using POST method. I am getting this 500 internal sever error. Actually the scenario is when the user is created some of its attributes store in USER table and three attributes store in PROFILES table. I tested this using Advanced Rest Client it works fine over there but when I apply the same exact method in angular I get this 500 error. I am attaching some screen shots to give you the real picture. The API is written in YII framework
My Controller
$scope.createuser = function (username, password, email, superuser, status, firstname, lastname, picture) {
$scope.formData = {'username': username, 'password': password, 'email': email, 'superuser': superuser, 'status': status, 'profile[firstname]': firstname, 'profile[lastame]': lastname, 'profile[picture]': picture};
console.log($scope.formData);
$http({
method: 'POST',
url: 'http://xx.dev/users/create',
data: $.param($scope.formData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function (data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
console.log('okay');
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
My form
<h1>Create User Manage User
Manage Profile Fields
List User</h1>
<div class="form">
<form name="createUser" novalidate>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div id="user-form_es_" class="alert alert-block alert-danger" style="display:none"><p>Please fix the following input errors:</p><ul><li>dummy</li></ul></div><div class="col-md-6"> <!--add this line in order to give this form a reasonable look -->
<div class="row">
<div class="form-group">
<div>
<input type="text" ng-model="username" class="input-20 form-control">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label" for="User_password">password</label>
<div>
<input type="password" ng-model="password" class="input-60 form-control">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label required" for="User_email">E-mail <span class="required">*</span></label>
<div>
<input type="email" ng-model="email" class="input-60 form-control">
<p id="User_email_em_" style="display:none" class="help-block"></p>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label required" for="User_superuser">Superuser <span class="required">*</span></label>
<div>
<select class="form-control" ng-model="superuser" id="User_superuser">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label required" for="User_status">Status <span class="required">*</span></label>
<div>
<select class="form-control" ng-model="status" id="User_status" required>
<option value="0">Not active</option>
<option value="1">Active</option>
<option value="-1">Banned</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label required" for="Profile_firstname">First Name <span class="required">*</span></label>
<div>
<input type="text" ng-model="firstname" id="Profile_firstname" class="input-60 form-control">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label required" for="Profile_picture">Picture <span class="required">*</span></label>
<div>
<input type="text" ng-model="picture" id="Profile_picture" class="input-60 form-control">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label required" for="Profile_lastname">Last Name <span class="required">*</span></label>
<div>
<input type="text" ng-model="lastname" id="Profile_lastname" class="input-60 form-control" ng-placeholder="lastname" required>
</div>
</div>
</div>
<div class="gap-small"></div> <!-- add the gap-->
<div class="row buttons">
<button class="btn btn-default" type="submit" name="yt0" ng-click="createuser(username , password , email , superuser, status , firstname , lastname , picture)">Create</button> </div>
</div>
<!--eneded here -->
</form>
</div><!-- form -->
API
public function actionCreate() {
switch ($_GET['model']) {
// Get an instance of the respective model
case 'create':
$model = new User;
$profile = new Profile;
break;
default:
$this->_sendResponse(501, sprintf('Mode <b>create</b> is not implemented for model <b>%s</b>', $_GET['model']));
Yii::app()->end();
}
// Try to assign POST values to attributes
foreach ($_POST as $var => $value) {
// if($var=='profile'){
// //var_dump($value);
// }
// Does the model have this attribute? If not raise an error
if ($model->hasAttribute($var) || $var=='profile')
$model->$var = $value;
else{
//var_dump ($var);
$this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']));
}
}
// Try to save the model
if ($model->save()){
$profile->user_id = $model->id;
$profile->firstname= $_POST['profile']['firstname'];
$profile->lastname= $_POST['profile']['lastname'];
$profile->picture= $_POST['profile']['picture'];
$profile->validate();
$profile->save();
$this->_sendResponse(200, CJSON::encode($model));
}
else {
// Errors occurred
$msg = "<h1>Error</h1>";
$msg .= sprintf("Couldn't create model <b>%s</b>", $_GET['model']);
$msg .= "<ul>";
foreach ($model->errors as $attribute => $attr_errors) {
$msg .= "<li>Attribute: $attribute</li>";
$msg .= "<ul>";
foreach ($attr_errors as $attr_error)
$msg .= "<li>$attr_error</li>";
$msg .= "</ul>";
}
$msg .= "</ul>";
$this->_sendResponse(500, $msg);
}
}
Try using CJSON class in your controller such as:use yii\helpers\Json;

How to reset data on modal window Open?

I have interesting situation Everytime when i open modal window i am reseting the value for below field, but if you select value 2 , 3 times and close modal with 'x' some time value retained in the select field. I am not sure why its happening any idea ?
main.html
<form name="addChallengeForm" id="addChallengeForm" novalidate ng-controller="challengesCtrl" class="border-box-sizing">
<div class="modalForm" disable-control-point="CHALLENGES_EDIT">
<div class="row" ng-show="editMode">
<div class="form-group col-md-12 fieldHeight">
<label for="originatingGroup" class="required col-md-4">Challenge Id:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="challangeId"
ng-model="challengesDTO.riskAssessmentChallengeKey" name="challangeId" readonly="readonly">
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="originatingGroup" class="required col-md-4">Originating group:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="originatingGroup"
k-option-label="'Select'" ng-model-options="{updateOn: 'blur'}"
ng-model="challengesDTO.originatingGrpLkupCode"
k-data-source="challengeGroupOptions"
id="originatingGroup" required>
</select>
<p class="text-danger" ng-show="addChallengeForm.originatingGroup.$touched && addChallengeForm.originatingGroup.$error.required">Originating group is required</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="challangeCreatedBy" class="col-md-4">Challenge created by:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="challangeCreatedBy"
ng-model="challengesDTO.initByWorker" name="challangeCreatedBy">
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="challangeDes" class="required col-md-4">Description of challenge:</label>
<div class="col-md-8">
<textarea rows="4" class="form-control"
name="challangeDes" id="challangeDes"
ng-model="challengesDTO.challengeDescription" required
placeholder="Description of challenge" ng-model-options="{updateOn: 'blur'}">
</textarea>
<p class="text-danger" ng-show="addChallengeForm.challangeDes.$touched && addChallengeForm.challangeDes.$error.required">Description of challenge is required</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="themesList" class="required col-md-4">Themes:</label>
<div class="col-md-8">
<select class="multiselect" kendo-multi-select="themes"
k-options="challengThemesOptions" data-text-field="'text'"
data-value-field="'id'" name="themesList"
ng-model="challengesDTO.themesKyList" required
k-data-source="challengThemesDataSource"
id="themesList"></select>
<p class="text-danger" ng-show="addChallengeForm.themesList.$touched && addChallengeForm.themesList.$error.required">Theme(s) is required</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="ownerOrPreparer" class="col-md-4">RCSA Preparer
Responding to Challenge:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="ownerOrPreparer"
ng-model="challengesDTO.challengeResponseWrk"
name="ownerOrPreparer" readonly="readonly" >
</div>
</div>
</div>
<div class="row" ng-show="editMode">
<div class="form-group col-md-12">
<label for="responseComment" class="col-md-4">RCSA Preparer Response:</label>
<div class="col-md-8">
<textarea rows="4" class="form-control"
name="responseComment" id="responseComment"
ng-model="challengesDTO.challengeResponseComment"
placeholder="RCSA Owner/Preparer Response">
</textarea>
</div>
</div>
</div>
<div class="row" ng-show="editMode">
<div class="form-group col-md-12 fieldHeight">
<label for="outcomeResolution" class="col-md-4">Outcome/Resolution:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="outcomeResolution"
k-option-label="'Select'" ng-change="mandatoryEscalation()"
ng-model="challengesDTO.challengeDesLkupCode"
k-data-source="challengOutComeOptions"
id="outcomeResolution" >
</select>
</div>
</div>
</div>
<div class="row" ng-if="editMode && showEscalation" disable-control-point="CHALLENGES_EDIT">
<div class="form-group col-md-12 fieldHeight">
<label for="requireEscalation" class="required col-md-4">Did the challenge
require escalation to be resolved?:</label>
<div class="col-md-8">
<select kendo-drop-down-list k-data-text-field="'text'"
k-option-label="'Select'" k-data-value-field="'id'"
k-options="escalationDataSource" name="requireEscalation"
ng-model="challengesDTO.esclRqrFlag" required
id="requireEscalation" ng-model-options="{updateOn: 'blur'}"></select>
<p class="text-danger" ng-show="addChallengeForm.requireEscalation.$touched && addChallengeForm.requireEscalation.$error.required">Challenge escalation is required</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addChallengeForm.$invalid" ng-click="submit()" require-control-point="CHALLENGES_ADD,CHALLENGES_EDIT">Save</button>
</div>
</form>
main.js
$scope.challengesDTO = {};
$scope.riskAssessmentDTO={
firstName: '',
lastName: '',
emailId: '' ,
nbkId: ''
};
$scope.$on('kendoRendered', function() {
rcsaAssessmentFactory.getThemeOptions().then(function(res){
$scope.challengThemesOptions.dataSource = new kendo.data.ObservableArray({data: res.data});
});
});
$scope.$on('addChallenge', function (s,id,opCheckList,checklistSessionKey){
$scope.addChallengeForm.originatingGroup.$setUntouched();
$scope.addChallengeForm.challangeDes.$setUntouched();
$scope.addChallengeForm.themesList.$setUntouched();
$scope.editMode = false;
$scope.clearFields = clearForm();
if($rootScope.user && $rootScope.user.customUserDetails){
$scope.challengesDTO.initByWorker= $rootScope.user.customUserDetails.workFullName;
}
rcsaAssessmentFactory.getAssessmentPreparerInfo(id).then(function(response){
$scope.riskAssessmentPreparer= response.data;
$scope.challengesDTO.challengeResponseWrkKey = $scope.riskAssessmentPreparer.rcsaPreparerWorkerKey;
$scope.challengesDTO.challengeResponseWrk = $scope.riskAssessmentPreparer.rcsaPreparerWorker;
});
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.challengesDTO.addChlngToChklst=opCheckList;
$scope.challengesDTO.riskAssessmentChecklistSessionKey=checklistSessionKey;
$scope.viewChallengeWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveChallenge($scope.challengesDTO,id).then(function(){
$scope.viewChallengeWin.close();
$scope.$emit('refreshChallengeGrid');
$scope.addChallengeForm.$setPristine();
$scope.clearFields = clearForm();
});
};
});
var clearForm = function(){
$timeout(function () {
$scope.challengesDTO = {
themesKyList: null
};
});
$scope.challengeGroupOptions = kendoCustomDataSource.getDropDownDataSource('RA_ASES_CHLNG_GRP');
$scope.challengThemesDataSource = kendoCustomDataSource.getDropDownDataSource('RA_CHLNG_THEME');
$scope.challengOutComeOptions = kendoCustomDataSource.getDropDownDataSource('RA_CHLNG_OUTCOME');
$scope.riskAssessmentDTO={
firstName: '',
lastName: '',
emailId: '' ,
nbkId: ''
};
};

Resources