How to insert many forms in db using Datatables - codeigniter

I tried to submit many forms with datatables. User has to choose the number ot input rows, in which he can submit some information - it's something like Phpmyadmin when you insert rows in db. Names of the input rows are the same. I use loop to show many rows. But in this way with nested foreach, when I submit info in two rows, in database there are 8 rows. How to do that?
Here's my view:
echo form_open('admin/add_questions/');
?>
<table id='example'>
<thead>
<tr><th>Question</th><th>Code</th><th>Group</th><th>Is_reverse</th></tr>
</thead>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
<tbody>
<?php for($i=0; $i<=20; $i++) {
?>
<tr>
<td>
<input type="text" name="question[]" id="add_question_table" />
</td><td>
<input type="text" name="code[]" id="add_question_table" />
</td><td>
<input type="text" name="group[]" id="add_question_table" />
</td><td>
<input type="text" name="is_reverse[]" id="add_question_table" />
</td></tr>
<?php
}
?>
</tbody>
</table>
My Model is:
<?php
class Admin_model extends CI_model {
public function __construct() {
parent:: __construct();
$this->load->database();
$this->load->library('session');
}
public function add_questions() {
$date = new DateTime("now");
foreach($this->input->post('question') as $v) {
foreach($this->input->post('code') as $f) {
foreach($this->input->post('group') as $val) {
$data = array(
'question'=>$v ,
'code'=>$f,
'survey_id'=>$this->uri->segment(3),
'group_id'=>$val,
'created_at'=>$date->format('Y-m-d H:i:s')
);
$this->db->insert('survey_questions',$data);
}
}
}
What's the way to do it? :)

Hi from my perspective its best to pass $_POST as a parameter to your add_questions() model method. You may try the following approach :)
//controller code
$this->admin_model->add_questions($_POST);
//model code
function add_questions($data=array())
{
if(count($data) > 0)
{
$date = new DateTime("now");
for($i=0;$i<count($data['question']);$i++){
$insert = array();
$insert['question'] = $data['question'][$i];
$insert['code'] = $data['code'][$i];
$insert['survey_id'] = $data['survey_id'][$i];
$insert['group_id'] = $data['group_id'][$i];
$insert['created_at'] = $date->format('Y-m-d H:i:s');
$this->db->insert('survey_questions',$insert);
}
}
}

Related

How to check if checkbox is checked for each row

If one row is checked if($isset->has('test')) returns all rows.
I only want to save the marked rows.
My view file:
<tbody>
#foreach($match->homeTeam->players as $player)
<tr>
<th scope="row">{{$player->id}}</th>
<td class = "col-md-6" name = "player[]" value = "{{$player->id}}">{{$player->name}} {{$player->surname}}</td>
<td align="center" class= "col-md-2"><input class="form-check-input" type="checkbox" name="test" value="{{$player->id}}"></td>
<td class = "col-md-2"><input name="minutes[]" class="form-control"></td>
<td class = "col-md-2"><input name="goals[]" class="form-control"></td>
</tr>
#endforeach
</tbody>
Controller:
public function storeMatchFacts(Match $match, Request $request, Match_fact $match_fact, Player $player)
{
$home_team_players=$match->homeTeam->players;
if($isset->has('test')) {
foreach ( $home_team_players as $k => $p ) {
$data[] = [
'match_id' => $match->id,
'player_id' => $player->id,
'minutes' => $request['minutes'][$k],
'goals' => $request['goals'][$k]
];
}
dd($data);
} else {
dd('error');
}

is there any way I could get 3 copies of invoice in codeigniter?

I am trying to get 3 copies of invoice printed in codeigniter. I have done a method to get pdf of my invoice. Is there any way to get 3 copies of invoice printed in normal html? I have tried it in by getting normal html by clicking on 'view' and pdf version of it when I click on 'view in pdf'
My View:
<?php include('admin_header.php');?>
<html>
<head>
<title></title>
</head>
<body>
<div class="container box">
<br />
<h3 align="center">Invoice List</h3><br />
<br />
<?php
if(isset($customer_data))
{
?>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<tr>
<th>Invoice ID</th>
<th>Customer Name</th>
<th>Customer Phone Number</th>
<th>Customer Billing Address</th>
<th>Customer Shipping Address</th>
<th>Computer Serial Number</th>
<th>Computer Manufacturer</th>
<th>Computer Model</th>
<th>Computer Configuration</th>
<th>Monthly Hire Rate</th>
<th>Total Hire Rate</th>
<th>View</th>
<th>View in PDF</th>
</tr>
<?php
foreach($customer_data->result() as $row)
{
echo '
<tr>
<td>'.$row->invoice_id.'</td>
<td>'.$row->cus_name.'</td>
<td>'.$row->cus_phone.'</td>
<td>'.$row->cus_badr.'</td>
<td>'.$row->cus_sadr.'</td>
<td>'.$row->com_sno.'</td>
<td>'.$row->com_make.'</td>
<td>'.$row->com_model.'</td>
<td>'.$row->com_config.'</td>
<td>'.$row->mohr.'</td>
<td>'.$row->tohr.'</td>
<td>View</td>
<td>View in PDF</td>
</tr>
';
}
}
?>
</table>
</div>
<?php
{
if(isset($customer_details))
{
echo $customer_details;
}
}
?>
</div>
</body>
</html>
My Controller:
<?php
class HtmltoPDF extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('htmltopdf_model');
$this->load->library('pdf');
}
public function index()
{
$this->load->helper('form');
$data['customer_data']=$this->htmltopdf_model->fetch();
$this->load->view('admin/htmltopdf',$data);
}
public function details()
{
if($this->uri->segment(3))
{
$invoice_id=$this->uri->segment(3);
$data['customer_details']=$this->htmltopdf_model->fetch_single_details($invoice_id);
$this->load->view('admin/htmltopdf',$data);
}
}
public function pdfdetails()
{
if($this->uri->segment(3))
{
$invoice_id=$this->uri->segment(3);
$html_content='<h3 align="center">Invoice List</h3>';
$html_content .= $this->htmltopdf_model->fetch_single_details($invoice_id);
$this->pdf->loadHtml($html_content);
$this->pdf->render();
$this->pdf->stream("".$invoice_id."pdf", array("Attachment"=>0));
}
}
}
My Model:
<?php
class Htmltopdf_model extends CI_Model
{
public function fetch()
{
$this->db->order_by('invoice_id','DESC');
return $this->db->get('invoice');
}
public function fetch_single_details($invoice_id)
{
$this->db->where('invoice_id',$invoice_id);
$data=$this->db->get('invoice');
$output='<table width="100%" cellspacing="5" cellpadding="5">';
foreach ($data->result() as $row)
{
$output .='
<tr>
<td width="100%">
<p><b>Name : </b>'.$row->cus_name.'</p>
<p><b>Phone: </b>'.$row->cus_phone.'</p>
<p><b>Address: </b>'.$row->cus_sadr.'</p>
</td>
</tr>
';
}
$output .='
<tr>
<td colspan="2" align="center">Back</td>
</tr>
';
$output .='</table>';
return $output;
}
}
?>
For PDF Generation
$invoice_id=$this->uri->segment(3);
$html_content='<h3 align="center">Invoice List</h3>';
$html_content .= $this->htmltopdf_model->fetch_single_details($invoice_id);
// 3 pages of same content means three times $html_content concatenated
$this->pdf->loadHtml($html_content.$html_content.$html_content);
For HTML View
if($this->uri->segment(3))
{
$invoice_id=$this->uri->segment(3);
$data['customer_details']=$this->htmltopdf_model->fetch_single_details($invoice_id);
// Load the view 3 times
$this->load->view('admin/htmltopdf',$data);
$this->load->view('admin/htmltopdf',$data);
$this->load->view('admin/htmltopdf',$data);
}
Alternatively you can use a "for{ } loop" to iterate the page content three times.

How to access model function in view or blade file

I want to get interest amount which is multiple of amount and interest rate in a table "loan". I want to call the value from a table and used for display loan information.
I have tried using mutators in which case gives same error as mentioned below
Loan.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $fillable = ['amount', 'interest', 'status', 'member_id', 'loan_type_id', 'interest_type_id', 'loan_payment_type_id'];
public function getInterestAmountAttribute()
{
return $this->amount * $this->interest;
}
public function member()
{
return $this->belongsTo(Member::class, 'member_id', 'id');
}
}
loan.blade.php
<table class="table table-stripped">
<thead>
<tr>
<th>Loan Id</th>
<th>Amount</th>
<th>Interest</th>
<th>Interest Amount</th>
<th>Interest Type</th>
<th>Loan Type</th>
<th>Status</th>
<th>Payment Type</th>
<th>Member</th>
<th>Action</th>
</tr>
#foreach($loanData as $key=>$loan)
<tr>
<td>{{++$key}}</td>
<td>{{$loan->amount}}</td>
<td>{{$loan->interest}}</td>
<td>{{ $loan->interest_amount}}</td>
<td>{{$loan->interesttype->interest_type}}</td>
<td>{{$loan->loantype->loan_type}}</td>
<td align="center">
<span class="bg bg-primary" style="border-radius: 10px;padding:2px 5px">{{$loan->status}}</span>
<form action="{{route('update-loan-status')}}" method="post">
{{csrf_field()}}
<input type="hidden" name="criteria" value="{{$loan->id}}"/>
#if($loan->status== 1)
<button class="btn btn-success btn-xs" name="paid"><i class="fa fa-check"></i></button>
#endif
#if($loan->status== 0)
<button class="btn btn-danger btn-xs" name="unpaid"><i class="fa fa-close"></i></button>
#endif
</form>
</td>
<td>{{$loan->paymentmethod->method}}</td>
<td>{{$loan->member->name}}</td>
<td>
Delete
Edit
</td>
</tr>
#endforeach
</thead>
</table>
{{$loanData->links()}}
This gives the following error:
Method Illuminate\Database\Eloquent\Collection::links does not exist.
when I remove brackets
<td>{{$loan->getInterest}}</td>
the error is
App\Loan::getInterest must return a relationship instance.
LoanController.php
<?php
namespace App\Http\Controllers\Backend;
use App\Http\Controllers\Controller;
use App\Loan;
use App\Interest;
use App\LoanPaymentMethod;
use App\Member;
use App\Loantype;
use DB;
class LoanController extends Controller
{
protected $_backendPath = 'backend.';
protected $_pagePath = 'backend.pages.';
protected $_data = [];
public function index()
{
$loanData = Loan::orderBy('id', 'desc')->get();
$loanData = Loan::paginate(10);
$loanData = Loan::all();
$memberData = Member::all();
$loantypeData = Loantype::all();
$paymentmethodData = LoanPaymentMethod::all();
$interestData = Interest::all();
$this->_data['loanData'] = $loanData;
//$results = Loan::with('member')->get();
//$dat->loan = Loan::with('member')->get();
//$loan = Member::find($memberData)->loan;
return view($this->_pagePath . 'loan.loan', $this->_data);
//$userData = DB::table('members')->get();
//return view('home',compact('userData'));
}
}
Define your function as accessor in your Loan.php :
public function getGetInterestAttribute()
{
return $this->amount * $this->interest;
}
Now you can access it , like this :
<td>{{ $loan->get_interest }}</td>
The right way to call an Accessor,
public function getModifiedInterestAttribute() // first get then ModifiedInterest then Attribute
{
return $this->amount * $this->interest;
}
Then you can call the Accessor like below,
<td>{{$loan->modified_interest }}</td>
You can see this for more details : https://laravel.com/docs/5.8/eloquent-mutators#defining-an-accessor
You should append that variable in model data Like
class Loan extends Model
{
protected $appends = ['interest'];
}
Your accessor should like
public function getInterest()
{
return $this->amount * $this->interest;
}
Access in blade file as you use above
<td>{{$loan->interest}}</td>

Soft delete on table

I just started using soft delete and I am not really sure how to do it, I am just following someone example and is still unsure how to do a proper soft delete. All I want is to delete the personal_info table but I keep on getting a no error message which make me at lost since I don't know what I am doing wrong, can someone help me? Thanks a lot
home.blade.php
<table class="table table-bordered">
<tr>
<th><strong><big>Name: </big></strong></th>
<th><strong><big>Action </big></strong></th>
</tr>
<td>
<tr>
#foreach($data as $value)
<tr>
<th>{{$value->Name}}</th>
<th><form action="{{ url('/home/'.$value->id.'/delete') }}" method="post">
<button>Delete</button>
</form></th>
</tr>
#endforeach
</tr>
</tr>
</table>
Controller:
public function delete($id = 0){
if ($id > 0){
personal_info::destroy($id);
}
return redirect("/home");
}
or should I do it this way?
public function delete($id){
$data = personal_info::find($id)->delete();
return redirect("/home");
}
personal_info model:
use Illuminate\Database\Eloquent\Model;
use Eloquent;
use SoftDeletes;
class personal_info extends Eloquent
{
protected $fillable = array('Name');
protected $table = 'personal_infos';
protected $primaryKey = 'id';
protected $dates = ['deleted_at'];
public function user_info1s() {
return $this->hasMany('App\user_info1','user_id');
}
Route: (not sure should I use DELETE instead)
Route::get('/home/{id}/delete', 'HomeController#delete');
There is no need to use delete on the method. try to change your function to this
public function delete($id){
personal_info::findOrFail($id)->delete();
return back();
}
Edit
The Route method and Form method must be the same.
Change
Route::get('/home/{id}/delete', 'HomeController#delete');
To
Route::post('/home/{id}/delete', 'HomeController#delete');
Controller Method
use Carbon\Carbon;
public function delete($id)
{
personal_info::find($id)->update([
'deleted_at' => Carbon::now()
]);
return redirect()->back();
}
home.blade.php
<table class="table table-bordered">
<tr>
<th><strong><big>Name: </big></strong></th>
<th><strong><big>Action </big></strong></th>
</tr>
<td>
<tr>
// Example of adjusting your query to support soft deletes
#php
$data = Some\Model::whereNotNull('deleted_at')->get();
#endphp
#foreach($data as $value)
<tr>
<th>{{$value->Name}}</th>
<th><form action="{{ url('/home/'.$value->id.'/delete') }}" method="post">
<button>Delete</button>
</form></th>
</tr>
#endforeach
</tr>
</tr>
</table>

Codeigniter Get Nested Hierarchical Data from Database

How can i get Hierarchical Data from db in Codeigniter. I read this :
http://www.sitepoint.com/hierarchical-data-database/
And i do good that but i cant optimize this tutorial with my model, controler and views
Default Category
|----- Sub category
| ----One more category
|----- Somthing else
I try but dont show sub category:
My model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$this->data[$row->id] = $row;
//echo str_repeat(' ',$level).$row['title']."\n";
}
return $this->data;
}
Controller :
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
Views:
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th> <?php echo str_repeat('|----', 0+1). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
And output is :
----Default
----Default
----Test Category 1
----Seccond Test Category 1
----Another Test Category 1
When i do this in model all work fine but when i try that to call in controler and loop in view i have result like above example:
This work onlu in model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
echo str_repeat('|-----',$level).$row->title."\n";
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
And like output i have :
Default
|----Test Category 1
|----Seccond Test Category 1
|----Another Test Category 1
Any one have solution or example thanks.
Try storing the level value for each category.
In your model:
public function fetchChildren($parent, $level){
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$row->level = $level;
$this->data[] = $row;
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
In your controller:
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
In your view
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th><?php echo str_repeat('|----', $row->level). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>

Resources