Scenario:
I have a form for each subject and each subject have three or four questions and the user have to answer those question then save the data on the database
The problem:
How to bind the data with the form so the form refilled with the data that inputted before by the user.
I have tried a lot and search a lot to find a solution but I didn't find anything useful.
Code:
Controller:
public function saveData(Request $request, $user_id, $subject_id)
{
$all_data = $request->input('row');
foreach ($all_data as $data) {
$question_id = $data['question_id'];
$check_data = ['user_id' => $user_id, 'question_id' => $question_id, 'subject_id' => $subject_id];
$exist_data = RatingDatum::where($check_data)->get()->first();
if (is_null($exist_data)) {
RatingDatum::create($data);
} else {
$save = RatingDatum::findorfail($exist_data->id);
$save->update($data);
}
}
flash()->success('Data has been submitted.');
return 'done';
}
View :
<div class="row">
{!! Form::model(['method' => 'PATCH','action'=>['RatingDataController#saveData'],$organisation->id,$organisation->sector->id]) !!}
<div class=" col-md-9">
<h3> {{$subject_name->subject}}</h3>
#foreach($question as $index=>$question)
<div class="plan bg-plan">
<h5>{{$question->question}}</h5>
<hr>
<!-- create sector form -->
#foreach($answers as $answer)
<div class="radio">
<label>
{!! Form::radio('row['.$index.'][answer_id]', $answer->id,true)!!}
{{$answer->answer}}
</label>
</div>
#endforeach
<div class="form-group">
{!! Form::label('comment','Comment :') !!}
{!! Form::textarea('row['.$index.'][comment]' ,null,['class'=>'form-control', 'rows' => 4]) !!}
</div>
</div>
#endforeach
</div>
{!! Form::submit('Submit Data', ['class' => 'btn btn-success submit right']) !!}
{!! Form::close() !!}
</div>
Related
i just have made a new app in laravel. i am trying to update my blog posts with tags. here is my form.
{{ Form::model($blog, array('route' => array('admin.blog.update', $blog->slug), 'method' => 'PUT', 'files' => true)) }} <!-- text input -->
<div class="form-group">
{!! Form::label('title', 'Title') !!}
{!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Title']) !!}
</div>
<div class="form-group">
{!! Form::label('description', 'Please Type Here Content') !!}
{!! Form::textarea('content', null, ['class'=>'ckeditor', 'id'=>'my-editor']) !!}
</div>
<div class="form-group">
<label>Category</label>
<select name="tag[]" class="form-control select2" multiple="multiple" data-placeholder="Select Categories"
style="width: 100%;">
#forelse($tags as $tag)
<option>{{ $tag->name }}</option>
#empty
#endforelse
</select>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
{!! Form::label('published_at', 'Publish On') !!}
{!! Form::input('date', 'published_at', date('Y-m-d'), ['class'=>'form-control']) !!}
</div>
</div>
</div>
<div class="form-group">
{!! Form::label('image', 'Choose Image') !!}
{!! Form::file('image') !!}
</div>
#push('scripts')
<script src="//cdn.ckeditor.com/4.6.2/standard/ckeditor.js"></script>
<script>
var options = {
filebrowserImageBrowseUrl: '{{ url('filemanager')}}?type=Images',
filebrowserImageUploadUrl: '{{ url('upload')}}?type=Images&_token={{csrf_token()}}',
filebrowserBrowseUrl: '{{ url('filemanager')}}?type=Files',
filebrowserUploadUrl: '{{ url('upload')}}?type=Files&_token={{csrf_token()}}'
};
CKEDITOR.replace('my-editor', options);
</script>
<script>
$(function () {
//Initialize Select2 Elements
$('.select2').select2()
//Timepicker
$('.timepicker').timepicker({
showInputs: false
})
})
</script>
#endpush
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
{!! Form::submit('Submit', array( 'class'=>'btn btn-info' )) !!}
{!! Form::close() !!}
here is my controller
> public function blogeditupdate($blog, Request $request){
> $blog = Blog::where('slug', $blog)->firstorfail();$blog = new Blog;
> $blog->title = $request->title;
> $blog->content = $request->content;
> $blog->slug = str_slug($blog->title, '-');
> $blog->user_id = Auth::user()->id;
> $blog->published_at = Carbon::now();
> if($request->hasFile('image')) {
> $file = Input::file('image');
> //getting timestamp
> $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
> $name = $timestamp. '-' .$file->getClientOriginalName();
> $file->move(public_path().'/images/blog/', $name);
> $blog->image = $name;
> $thumb = Image::make(public_path().'/images/blog/' . $name)->resize(640,420)->save(public_path().'/images/blog/thumb/' .
> $name, 90);
> }
> $blog_id = $blog->id;
> $tags = $request['tag'];
> if (isset($tags)) {
> $blog->tags()->sync($tags); //If one or more tags is selected associate blog to tagblog
> }
> else {
> $blog->tags()->detach(); //If no tags is selected remove exisiting role associated to a blogs
> }
> return redirect()->route('admin.blog.index')->with('status', 'Edit Success');
> }
here is my error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'blog_id' cannot be null (SQL: insert into blog_tagblog (blog_id, created_at, tagblog_id, updated_at) values (, 2017-09-10 15:17:11, ghanta, 2017-09-10 15:17:11)) ◀"
i am missing something but i don't know what i am doing wrong.please help me!!
At the end of the very first line in your controller, you have this:
$blog = new Blog;
This means that $blog will not have an id, and when you attempt to set the relationship, the blog_id field will be null, which violates your integrity constraints.
If this line is a mistake, delete it.
If not, you need to call $blog->save() before you attempt to sync your tags.
I have 2 models with Many-to-Many Relation when I create new Device and check multiple Checkboxes I want to save multiple voices_id with Device_id into the Pivot Table device_voice
Device Controller ( I am facing this error Undefined variable: selectedVoice in Edit function )
public function create()
{
$this->authorize("create", Device::class);
$voice_list = Voice::all();
return view('devices.create')
->with('voice_list', $voice_list);
}
public function store(CreateDeviceRequest $request)
{
$this->authorize("create", Device::class);
$input = $request->all();
$voices_checkbox = $input['voice'];
$device = $this->deviceRepository->create($input);
//Device Id and Selected voices is Saved Successfully
$device ->voices()->sync($voices_checkbox);
Flash::success('Device saved successfully.');
return redirect(route('devices.index'));
}
public function edit($id)
{
$device = $this->deviceRepository->findWithoutFail($id);
$this->authorize("update", $device);
$voice_list = Voice::all();
// Here I am getting Device's checked voices, but sinces I am sharing the same Fields Blade with Create and Edit I get this error
//Undefined variable: selectedVoice
$selectedVoice = $device->voices->pluck("id")->toArray();
if (empty($device)) {
Flash::error('Device not found');
return redirect(route('devices.index'));
}
return view('devices.edit')
->with('device', $device)
->with('voice_list', $voice_list)
->with('selectedVoice', $selectedVoice);
}
This is My Fields for Both Create and Edit Views
<!-- Device Number Field -->
<div class="form-group col-sm-6">
{!! Form::label('device_number', 'Device Number:') !!}
{!! Form::text('device_number', null) !!}
</div>
<!-- Batch Field -->
<div class="form-group col-sm-6">
{!! Form::label('device_name', 'Device Name:') !!}
{!! Form::text('device_name', null) !!}
</div>
<!-- Batch Field -->
<div class="form-group col-sm-6">
{!! Form::label('voices_id', 'Voices:') !!}
#foreach ($voice_list as $voice)
{!! Form::checkbox('voice[]', $voice->id, in_array($voice->id, $selectedVoice)) !!}
{!! Form::label('voice', $voice->name) !!}
#endforeach
</div>
<!-- Version Field -->
<div class="form-group col-sm-6">
{!! Form::label('version', 'Version:') !!}
{!! Form::text('version', null) !!}
</div>
Thanks!
Use the sync() method:
$device->voices()->sync($request->voices);
I'm having a problem for the first time when i submit a form.
When i submit the form it doesn't go to post route and i don't know why.
my post route is that:
Route::post('/app/add-new-db', function()
{
$rules = array(
'name' => 'required|min:4',
'file' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect our user back to the form with the errors from the validator
return Redirect::to('app/add-new-db')
->withErrors($validator);
}
else
{
$name = Input::get('name');
$fname = pathinfo(Input::file('file')->getClientOriginalName(), PATHINFO_FILENAME);
$fext = Input::file('file')->getClientOriginalExtension();
echo $fname.$fext;
//Input::file('file')->move(base_path() . '/public/dbs/', $fname.$fext);
/*
DB::connection('mysql')->insert('insert into databases (name, logotipo) values (?, ?)',
[$name, $fname.$fext]);
*/
//return Redirect::to('app/settings/');
}
});
And my html:
<div class="mdl-cell mdl-cell--12-col content">
{!! Form::open(['url'=>'app/add-new-db', 'files'=>true]) !!}
<div class="mdl-grid no-verticall">
<div class="mdl-cell mdl-cell--12-col">
<h4>Adicionar Base de Dados</h4>
<div class="divider"></div>
</div>
<div class="mdl-cell mdl-cell--6-col">
<div class="form-group">
{!! Form::label('name', 'Nome: ') !!}
{!! Form::text('name', null, ['id'=> 'name', 'class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('image', 'Logotipo:') !!}
{!! Form::file('image', ['class'=>'form-control']) !!}
#if ($errors->has('image'))
<span class="error">{{ $errors->first('image') }}</span>
#endIf
</div>
<div class="form-group">
{!! Form::submit('Adicionar', ['id'=>'add-new-db', 'class'=>'btn btn-default']) !!}
<p class="text-success"><?php echo Session::get('success'); ?></p>
</div>
</div>
</div>
{!! Form::close() !!}
</div>
I'm loading this from from a jquery get:
function addDB()
{
$( "#settings-new-db" ).click(function(e)
{
$.get('/app/add-new-db', function(response)
{
$('.content-settings').html("");
$('.content-settings').html(response);
componentHandler.upgradeDom();
});
e.preventDefault();
});
}
When i try to submit the form i'm getting 302 found in network console from chrome.
I'm doing forms at this way and it is happens for the first time. Anyone can help me?
Thanks
Fix the name attribute for your image upload field. You refer it as image in the form but you are trying to fetch it as file in your controller.
I'm making a school system for my school and I have this problem in which I'm stuck for days. In my app I have users with type admin, teacher and student. The admin creates all the users and all the other information. Now I'm making the teacher panel in which the teacher will be able to add marks for the students and later they will be displayed in the student panel.
So in first place when the teachers get into their account he will be able to pick a class which he teaches and the subjects which he teaches, for that case I have table - class_subjects in which I'm saving the teacher_id, subject_id and class_id from the admin panel. I'm calling this here, in my teacher panel, and it seems to work just fine, because I see the exact classes and subjects I need. After that I need to make a post query with these both picked from the teacher and in return to get all the students from the picked class + the picked subject, that also works exactly how I want it. So what I am returning is a new blade with arrays with information from the table class_subject, from this returned arrays the teacher need to pick information, and here in text field he must add his mark for the student he picks. After that I need to save the picked information in new table called student_marks with fields student_id, subject_id, mark_type_id, mark.
My question is how the save this information (that the teacher picks) in the new table (student_marks)?
I'm posting the controller:
class AccountController extends Controller
{
public function getIndex() {
$user = Auth::user();
$classStudent = ClassSubject::where('teacher_id','=',$user->id)->get()->lists('class_id');
$userSubject = ClassSubject::where('teacher_id','=',$user->id)->get()->lists('subject_id');
return view('educator.account.account',[
'user' => $user,
'userTeacher'=> $classStudent,
'userSubject'=> $userSubject,
]);
}
public function postIndex(Request $request) {
ClassSubject::where(
'subject_id','=',$request->get('userSubject'),
'class_id','=',$request->get('userClass')
);
$user = Auth::user();
$markType = MarkType::lists('type');
$sub = Subject::where('id','=',$request->get('userSubject'))->get()->lists('name');
$stu = User::where('class_id','=',$request->get('userClass'))
->orderBy('first_name', 'asc')->get()->lists('full_name');
return view('educator.account.input', [
'user' => $user,
'studentss'=> $stu,
'markType' => $markType ,
'sub'=> $sub,
}
I know its a bit twisted but I'm really stuck in here and I will be really grateful if someone can finally help me with this. If something is unclear, please ask.
educator.account.account (first blade)
#extends('teacher-app')
#section('teacher-content')
<div class="col-md-6">
{!! Form::open(['method' => 'post', 'class' => 'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('profile_id','Избери клас:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userClass', $userTeacher, null, ['class'=>'form-control']) !!}
</div>
</div>
<br>
<div class="form-group">
{!! Form::label('profile_id','Избери предмет:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userSubject', $userSubject, null, ['class'=>'form-control']) !!}
</div>
</div>
<div align="center">
{!! Form::submit('Избери', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
#stop
</div>
educator.account.input (second blade)
#extends('teacher-app')
#section('teacher-content')
<div class="col-md-8">
{!! Form::open(['method' => 'post', 'class' => 'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('profile_id','Ученик:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('userStu', $studentss, null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Оценка:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-2">
{!! Form::text('mark',null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Тип оценка:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('markType', $markType, null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('profile_id','Предмет:', ['class' => 'control-label col-md-4']) !!}
<div class="col-md-3">
{!! Form::select('stuSub', $sub, null, ['class'=>'form-control']) !!}
</div>
</div>
<br>
<div align="center">
<button type="button" class="btn btn-default">Назад</button>
{!! Form::submit('Запиши', ['class' => 'btn btn-default']) !!}
</div>
{!! Form::close() !!}
</div>
#stop
When they submit the form for the student rating, you'll have a route similar to this to post to:
class AccountController extends Controller {
public function markStudent(Request $request)
{
// get request data
$mark = $request->input('mark');
$subject_id = $request->input('stuSub');
$mark_type = $request->input('markType');
$student_id = $request->input('userStu');
// get the existing record or create a new, empty record
$student_mark = StudentMark::firstOrNew(compact('student_id', 'subject_id'));
// add the updated data to the model
$student_mark->fill(compact('mark_type', 'mark'));
// persist to database
$student_mark->save();
// redirect or do whatever you want after request completion...
}
}
This above code assumes you only want one entry per student, per subject (ie. a unique index on both these columns).
I would also recommend that you validate the data before inserting it, either by doing so before the StudentMark::firstOrNew() or by creating a custom request object with validation.
I have written a code that sends email to selected people using check-box, now I have to add select all and clear all button so that all the check-boxes should get selected/dis-selected.
Here is my code:
My controller:
public function display(){
$data = Input::get('agree');
$count = count ($data);
$this->contact( $data );
return view('clientinfo.display', compact('data','count'));
}
My View:
#extends('app')
#section('content')
<h1>Welcome! Send e-mail to selected people.</h1>
<hr>
{!! Form::open(array('action' => 'ClientsController#display','method' => 'GET'))!!}
#foreach($clients as $client)
{!! Form::checkbox("agree[]", $client->email, null,['id' => $client->email]) !!}
<article>
{{ $client->user_name }}
{{ $client->email }}
</article>
#endforeach
{!! Form::submit('Send Mail',['class' => 'btn btn-primary form-control']) !!}
{!! Form::close() !!}
<br/>
#include('clientinfo.newmember')
#stop
if i add a button in my view naming select-all and clear-all how do i relate them, to select all the members within list?
You could give the checkboxes a class and use jquery.
You also need a checkbox that says "select all" with an ID.
$(function() {
$('#selectAll').click(function() {
if ($(this).prop('checked')) {
$('.your_checkbox_class').prop('checked', true);
} else {
$('.your_checkbox_class').prop('checked', false);
}
});
});
PS: Code is not tested
I have made changes to my code and it worked using JavaScript.
Here is my code:
#extends('app')
#section('content')
<h1>Welcome! Send e-mail to selected people.</h1>
<hr>
{!! Form::open(array('action' => 'ClientsController#display','method' => 'GET','name'=>'f1' , 'id'=>'form_id'))!!}
<br/>
#foreach($clients as $client)
<div class="form-group">
{!! Form::checkbox("agree[]", $client->email, null,['id' => $client->email], ['class' => 'questionCheckBox']), $client->email !!}
<br/>
</div>
#endforeach
<div class="form-group">
{!! Form::submit('Send Mail',['class' => 'btn btn-primary form-control']) !!}
</div>
<div class="form-group">
{!! Form::button('Select All',['class' => 'btn btn-info form-control','onClick'=>'select_all("agree", "1")']) !!}
</div>
<div class="form-group">
{!! Form::button('Clear All',['class' => 'btn btn-danger form-control','onClick'=>'select_all("agree", "0")']) !!}
</div>
{!! Form::close() !!}
#stop
#endsection
And in my master file,I have added a JavaScript:
<script type="text/javascript">
var formblock;
var forminputs;
function prepare() {
formblock= document.getElementById('form_id');
forminputs = formblock.getElementsByTagName('input');
}
function select_all(name, value) {
for (i = 0; i < forminputs.length; i++) {
// regex here to check name attribute
var regex = new RegExp(name, "i");
if (regex.test(forminputs[i].getAttribute('name'))) {
if (value == '1') {
forminputs[i].checked = true;
} else {
forminputs[i].checked = false;
}
}
}
}
if (window.addEventListener) {
window.addEventListener("load", prepare, false);
} else if (window.attachEvent) {
window.attachEvent("onload", prepare)
} else if (document.getElementById) {
window.onload = prepare;
}
</script>
Earlier i was doing this using Jquery, that was not working, then i tried using JavaScript and it worked.
I have tried various ways to add jquery in my code which are given in answers of stackoverflow.com, but nothing worked in laravel. If anyone know how to use jquery in laravel, please leave a comment.