There's so many question about this but because I'm a newbie, I don't get it at all. so I've successfully saving multiple data into my db. I have 2 tables, TicketPrice as a list of price that visitor would choose, then I will save the selected data into Payment table. This is what I've done in my controller:
$idcategory = $request->id_category;
$price = $request->price;
$qty = $request->qty;
$data = [];
$i = 0;
foreach($idcategory as $key => $value) {
if ($qty[$i] > 0) {
for ($k=0; $k < $qty[$i] ; $k++) {
$data[] = [
"id_category" => $value,
"name" => $request->nama[$key],
"price" => $request->price[$key],
"qty" => $request->qty[$key],
];
}
}
$i++;
}
Payment::insert($data);
$latest = News::orderBy('date', 'DESC')->take(3)->get();
return view('form.conference-regist',compact('latest'))->with('data',$data);
and this is when I try to foreach the selected data (it's multiselect) in my blade after saving it on Payment table:
<?php foreach ($data as $key): ?>
<div class="row">
<div class="col-lg-12 col-md-12 col-xs-12">
<div class="form-group">
<label for="exampleInputEmail1">Price</label>
<input type="text" class="form-control" id="price" aria-describedby="emailHelp" name="price" value="{{$key->price}}">
</div>
</div>
</div>
<?php endforeach; ?>
I wonder if it necessary to put hasMany or belongsTo into the models? Or is there any easier way to solved it?
Well you can try this to get the inserted data back and to pass it to view
$data2 = Payment::insert($data);
$data2 = $data2->fresh(); //this will re-retrieve the inserted data back from table.
$latest = News::orderBy('date', 'DESC')->take(3)->get();
return view('form.conference-regist',compact('latest'))->with('data',$data2);
Related
i'm trying to send an array from my laravel view to my controller, but i'm only receiving one part os the data, this is what i have:
<form
method="POST"
action="{{ url('/forms/reports') }}"
>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#foreach ($results as $result)
<input value="{{ $result->code }}" name="code">
<input value="{{$result->name}}" name="name">
<input value="{{$result->user}}" name="user">
<input value="{{$result->number}}" name="number">
#endforeach
<div class="col-xs-9">
</div>
<div class="col-xs-3 container-download">
<button type="submit" class="btn btn-download" id="btn-download" >Download</button>
</div>
</form>
But results has this:
array (
0 => '1',
1 => 'Test Name 1',
2 => 'user1',
3 => '1',
), array (
0 => '2',
1 => 'Test Name 2',
2 => 'user2',
3 => '2',
);
And on the table that i have on my view is showing correctly, the two rows of data.
But when i do the post to receive on my controller the full results array, i only get the second row, when i print it like this:
public function generateExcel(Request $request)
{
$code = $request->input('code');
$name = $request->input('name');
$user = $request->input('user');
$number = $request->input('number');
$users = [$code, $name, $user, $number];
Log::debug($users);
}
And my Log shows me this:
[2020-12-30 12:43:58] local.DEBUG: array (
0 => '2',
1 => 'Test Name 2',
2 => 'user2',
3 => '2',
)
And i don't know if i should push the values first or i'm making another mistake. Can anyone help me with this?
That is happening because you are not sending an array. You will need to do something like this.
#foreach ($results as $result)
<input value="{{ $result->code }}" name="code[]">
<input value="{{$result->name}}" name="name[]">
<input value="{{$result->user}}" name="user[]">
<input value="{{$result->number}}" name="number[]">
#endforeach
I want to insert data from my form into mysql bu I am getting errors. How do I solve this problem.
#foreach($assignments as $item)
<input type="text" name="class[]" value="{{$item->class}}" id="">
<input type="text" name="year[]" value="{{$item->year}}" id="">
<input type="text" name="subject_id[]" value="{{$item->subject_id}}" id="">
<label for="" class="ml-3 mt-2 mb-1">Score</label>
<input type="text" name="score[]" id="" style="width: 20rem;" class="form-control ml-3">
</div>
$class = $request->get("class");
$year = $request->get("year");
$subject_id = $request->get("subject_id");
foreach ($request->get('score') as $key => $value){
SubmitScores::create([
'class' => $key[$class],
'year' => $key[$year],
'subject_id' => $key[$subject_id]
]);
}
#endforeach
The error am getting is:
Trying to access array offset on value of type int
These are backwards:
$key[$class]
$key[$year]
$key[$subject_id]
Those should be $variable[$key]. $key is an integer index, like 0, 1, 2, and $class, $year and $subject_id ($variable) are arrays. So:
foreach ($request->get('score') as $key => $value){
SubmitScores::create([
'class' => $class[$key],
'year' => $year[$key],
'subject_id' => $subject_id[$key]
]);
}
I have a multi-select option and i want to save all record in database, now it's saving only the last one, how can I do that? I need to save multi-select from tags with comma (,) between. .
Here is my controller and what I tried
$news = News::create([
'locale' => Session::get('admin_locale'),
'title' => $request['title'],
'slug' => Slugify::slugify($request['title']),
'news_class' => $request['news_class'],
'description' => $request['description'],
'tag' => $request['tag'],
'tags' => $request->input['tags'],
'category' => 'news',
'category_id' => $request['category_id'],
'metatitle' => $request['title'],
'metadescription' => substr(strip_tags($request['description']), 0, 160),
'image' => $image,
]);
Here is my view:
<div class="row d-flex justify-content-center mt-100 col-md-12 g-mb-30" >
<div class="col-md-12" >
<label class="g-mb-10">Tags</label>
<select id="choices-multiple-remove-button" placeholder="Select" multiple title="Category Talent" name="tags">
#foreach($news as $tag)
<option value="{{ $tag->tag }}">{{ $tag->tag }}</option>
#endforeach
</select> </div>
</div>
To pass multiple values you probably want to rename your input to be an array:
<select ... name="tags[]">
Then on the server side you should receive them as an array under the input tags:
$tags = $request->input('tags', []);
You can join the array elements with implode to get a string representation:
$tags = implode(',', $tags);
PHP Manual - Function Reference - Text Processing - Strings - Functions - implode
$news = News::create([
...
'tags' => implode(',', $request->input('tags', [])),
...
]);
I'm new to cakephp 2x. I have multiple drop down in my form. All the drop downs are using same list data, from one table called -> Students. Now what I want is ,when the user select first student in first drop down ,then that student should be minus from the next four drop down or disabled in next four drop downs.So that the user wouldn't be able to add the same student repeately. Plz Help! Thanks! in advance.
//Here is my controller add file:
public function add(){
if ($this->request->is('post')) {
$this->Group->create()
if ($this->Group->save($this->request->data)) {
$this->Session->setFlash(__('The group has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The group could not be saved. Please, try again.'));
}
}
$this->loadModel('Student');
$student1s = $this->Student->find('list');
//pr ($student1s);
$this->set(compact('student1s'));
}
// Here is my add.ctp
< div class="Groups form">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h1><?php echo __('Add Students'); ?></h1>
</div>
</div>
</div>
<div class="row">
<?php echo $this->Form->create('Groups', array('role' => 'form')); ?>
<div class="col-md-5 col-md-offset-3">
<div class="form-group">
<?php echo $this->Form->input('0.name', array('type'=>'select','options'=>$student1s,'empty' => 'Please choose a student','class'=>'form-control'));?>
</div>
<div class="form-group" >
<?php echo $this->Form->input('1.name', array('type'=>'select',"options"=>$student1s,'empty' => 'Please choose a student','class'=>'form-control',));?>
</div>
<div class="form-group">
<?php echo $this->Form->input('2.name', array('type'=>'select',"options"=>$student1s,'empty' => 'Please choose a student','class'=>'form-control'));?>
</div>
<div class="form-group">
<?php echo $this->Form->input('3.name', array('type'=>'select',"options"=>$student1s,'empty' => 'Please choose a student','class'=>'form-control'));?>
</div>
<div class="form-group">
<?php echo $this->Form->input('4.name', array('type'=>'select',"options"=>$student1s,'empty' => 'Please choose a student','class'=>'form-control'));?>
</div>
<div class="form-group">
<?php echo $this->Form->submit(__('Submit'), array('class' => 'btn btn-primary')); ?>
</div>
<?php echo $this->Form->end() ?>
</div><!-- end col md 12 -->
</div><!-- end row -->
</div>
find solution for my problem to avoid duplication of data,This link helps -> Validating multiple fields with the same name. All i have to do is put this code ->array('validate' => 'true')<- in this line
if ($this->Group->save($this->request->data),array('validate' => 'true')) {
and all done no need to disable the selected list value.
I have two forms, one to edit room details and the other to edit Extras. Within the forms I pull in a file upload and pass in the id. For some reason one requires a url and the id does not get passed in. Both have the same code. Can see why they are differnt.
Room form
<div class="boxgrid grid_8">
<?php echo $this->element('attachments',array('control'=>'upgrades','id'=>$this->data['AddOn']['id'],'att'=>$this->data['Attachment'])); ?>
</div>
Room upload
Form->create('Room', array('type' => 'file'));?>
<legend><?php __('Upload Room Images'); ?></legend>
<?php
echo $this->Form->input('id');
?>
<input type="hidden" name="data[Attachment][0][model]" value="Room" id="Attachment0Model" />
<input type="hidden" name="data[Attachment][0][group]" value="attachment" id="Attachment0Group" />
<div class="input file required"><input type="file" name="data[Attachment][0][file]" class="" id="Attachment0File" /></div>
<div class="submit"><button>Upload</button></div>
<div>Upload files</div>
Extras Form
<div class="boxgrid grid_8">
<?php echo $this->element('attachments',array('control'=>'upgrades','id'=>$this->data['AddOn']['id'],'att'=>$this->data['Attachment'])); ?>
</div>
Extras Upload
Form->create('Upgrade', array('type' => 'file','url'=>'/admin/upgrades/addfiles','id'=>'AddOnAdminAddfilesForm'));?>
<legend><?php __('Upload Addon Images'); ?></legend>
<?php
echo $this->Form->input('id');
?>
<input type="hidden" name="data[Attachment][0][model]" value="AddOn" id="Attachment0Model" />
<input type="hidden" name="data[Attachment][0][group]" value="attachment" id="Attachment0Group" />
<div class="input file required"><input type="file" name="data[Attachment][0][file]" class="" id="Attachment0File" /></div>
<div class="submit"><button>Upload</button></div>
<div>Upload files</div>
Javascript on each form:
<script type="text/javascript">
$(document).ready(function() {
$("div#uploader").resloader();
$("div#uploader").load('<?=BASE_URL?>/admin/upgrades/addfiles/<?=$this->data['AddOn']['id']?>',null,function(){}).fadeIn();
Upgrades Contoller
function admin_addfiles($id = null) {
$this->layout = null;
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid Add On', true));
$this->redirect(array('controller' => 'upgrades', 'action' => 'index'));
}
if (!empty($this->data)) {
$this->layout = null;
//if(empty($this->data['AddOn']['id'])){unset($this->data['AddOn']);}
// restructure data for uploader plugin // NEED TO GET RID OF THIS ? MOVE IT
$tmp_file = $this->data['Attachment'][0]['file'];
$tmp_file['extension'] = array_reverse(explode('.', $tmp_file['name']));
$tmp_file['extension'] = $tmp_file['extension'][0];
$tmp_file['title'] = strtolower(substr($tmp_file['name'],0,(0-strlen('.'.$tmp_file['extension']))));
$this->data['Attachment'][0]['alternative'] = ucwords(str_replace('_',' ', $tmp_file['title']));
if ($this->AddOn->saveAll($this->data, array('validate' => 'first'))) {
$id = $this->AddOn->Attachment->getLastInsertID();
$att = $this->AddOn->Attachment->query("SELECT * from attachments WHERE id = ".$id);
$this->set('attachment',$att[0]['attachments']);
} else {
$tmp_file['name'] = 'INVALID FILE TYPE';
}
//debug($this->data);
$this->set('file', $tmp_file);
$this->RequestHandler->renderAs($this, 'ajax');
$this->render('../elements/ajax');
}
if (empty($this->data)) {
$this->data = $this->AddOn->read(null, $id);
}
}
}
Your problem is with the $this->data. Check how it is filled in your controller.
Both views are NOT the same, the main difference is in the create form.
Form->create('Room', array('type' => 'file'));?>
Form->create('Upgrade', array('type' => 'file','url'=>'/admin/upgrades/addfiles','id'=>'AddOnAdminAddfilesForm'));?>
As you can see, one has the first parameter 'Room' and the other one is 'Upgrade', this IS important since you call the id like this
echo $this->Form->input('id');
Cake expects that for the first case you have something like, $this->data['Room']['id'] and the second one $this->data['Upgrade']['id']
If you pass from the controller your id variable like this
$this->set('id',$id);
then in the view you can do somthing like this
<?php
echo $this->Form->input('id', array('value'=>$id, 'type'=>'hidden'));
?>
Hope this solves your answer, if not, please post the $this->data value of each and the part of the controller where you assign $this->data