Need help, I want to sum one column in codeigniter4 but I get this error:
Error: object of class CodeIgniter\Database\MySQLi\Builder could not be converted to string
This is my model:
public function tot_crew_wni_arr() {
return $this->db->table('tbl_est_arr')->selectSum('crew_wni_arr');
}
at controller
$data = array(
'tot_crew_wni_arr' => $this->Model_home->tot_crew_wni_arr(),
);
return view('layout/v_wrapper', $data);
This is my view:
<h3><?= $tot_crew_wni_arr ?></h3>
Your model function should look something like this:
public function tot_crew_wni_arr() {
$db = \Config\Database::connect();
$builder = $db->table('tbl_est_arr');
return $builder->selectSum('crew_wni_arr')->get();
}
Related
I'm making an export data to excel based on employee_id filter, month and year of absence:
.
when the filter is submitted the data appears in the table below:
I have managed to get the data, but when the Download Excel button is clicked, the contents are just empty Excel, like this:
the data does not enter the excel.
My Controller:
public function rekapabsensiExcel(Request $request)
{
$idkaryawan = $request->id_karyawan;
$bulan = $request->query('bulan',Carbon::now()->format('m'));
$tahun = $request->query('tahun',Carbon::now()->format('Y'));
// simpan session
$idkaryawan = $request->session()->get('idkaryawan');
$bulan = $request->session()->get('bulan');
$tahun = $request->session()->get('tahun',);
// dd($idkaryawan,$bulan,$tahun );
if(isset($idkaryawan) && isset($bulan) && isset($tahun))
{
$data = Absensi::where('id_karyawan', $idkaryawan)
->whereMonth('tanggal', $bulan)
->whereYear('tanggal',$tahun)
->get();
// dd($data);
}else{
$data = Absensi::all();
}
return Excel::download(new RekapabsensiExport(['data'=>$data, 'idkaryawan'=>$idkaryawan]),'rekap_absensi_bulanan.xlsx');
}
My RekapAbsensiExport.php:
<?php
namespace App\Exports;
use App\Models\Absensi;
use Maatwebsite\Excel\Concerns\FromCollection;
class RekapabsensiExport implements FromCollection
{
protected $id_karyawan;
// function __construct($id_karyawan) {
// $this->id_karyawan = $id_karyawan;
// }
public function headings(): array {
return [
"No. ID","ID Karyawan","NIK","Tanggal","Jam Kerja","Jam Masuk","Jam Pulang",
"Scan Masuk","Scan Pulang","Normal","Riil","Terlambat","Plg Cepat","Absent",
"Lembur","Jml Jam Kerja","pengecualian","Harus C/I","Harus C/O","Departemen",
"Hari Normal","Akhir Pekan","Hari Libur","Jml Kehadiran","Lembur Hari Normal",
"Lembur Akhir Pekan","Lembur Hari Libur"
];
}
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return Absensi::where('id_karyawan',$this->id_karyawan)->get();
}
}
What part did I go wrong? Please help
Currently, you get no response to this statement because $this->id_karyawan is null as you have not properly passed the value through.
return Absensi::where('id_karyawan', $this->id_karyawan)->get();
Above, you are passing an array of values to the Export class. But your commented-out constructor function is only configured to accept a single parameter. If we stick to single parameters, you could do something like this.
return Excel::download(new RekapabsensiExport($data, $idkaryawan),'rekap_absensi_bulanan.xlsx');
Then your export constructor would look like this.
protected $data;
protected $id_karyawan;
function __construct($data, $id_karyawan) {
$this->data = $data;
$this->id_karyawan = $id_karyawan;
}
I am trying to upload the file but when I give import I get the following error Undefined array key "idEvento"
When I handle it by number that I start from scratch I do not get any error and insert into the database
Event Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Eventos extends Model
{
use HasFactory;
protected $fillable = [
'nombre',
'idEvento',
'idSede',
'inicio',
'fin',
'idModalidad',
'cupo',
'valor',
];
}
Import data function
public function importData(Request $request){
$file = $request->file('documento');
$validator = Validator::make(
array(
'file' => $file,
),
array(
'file' => 'file|max:5000|mimes:xlsx,xls',
)
);
if ($validator->fails()) {
return Redirect::to('conferencia/import');
}
$import = new EventosImport();
Excel::import($import, request()->file('documento'));
return view('conferencias.import', ['numRows'=>$import->getRowCount()]);
//return redirect()->to(url('conferencia'));
}
Event import code
<?php
namespace App\Imports;
use App\Models\Eventos;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class EventosImport implements ToModel, WithHeadingRow
{
private $numRows = 0;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
++$this->numRows;
return new Eventos([
'nombre' => $row['nombre'],
'idEvento' => $row['idEvento'],
'idSede' => $row['idSede'],
'inicio' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['inicio']),
'fin' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['fin']),
'idModalidad' => $row['idModalidad'],
'cupo' => $row['cupo'],
'valor' => $row['valor'],
]);
}
public function getRowCount(): int
{
return $this->numRows;
}
}
Image of the excelenter image description here
it´s better than you use your function import in your controller instead of in your model. To read excel use sometimes similary to:
$data = Excel::load($path, function($reader) {})->get();
if(!empty($data) && $data->count()){
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
foreach ($value as $v) {
$insert[] = ['title' => $v['title'], 'description' => $v['description']];
}
}
}
if(!empty($insert)){
Item::insert($insert);
return back()->with('success','Insert Record successfully.');
}
}
why when import excel, my data I added is not saved to the database ?
i import excel with type xlsx
My controller
public function importDataPegawai(Request $request)
{
Excel::import(new ImportPegawai, $request->file('upload-pegawai'));
return redirect('dashboard-admin')->with('success','Berhasil Upload Data Pegawai');
}
My Import
<?php
namespace App\Imports;
use App\Models\PegawaiModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Auth;
use DB;
class ImportPegawai implements ToModel, WithStartRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
foreach ($row as $data){
$data = DB::table('tbl_pegawai')->where('nip', $row[0])->get();
if (empty($data)) {
return new PegawaiModel([
'nip' => $row[0],
'nama_lengkap' => $row[1],
'pangkat' => $row[2],
'gol' => $row[3],
'jabatan' => $row[4],
'unit_kerja' => $row[5]
]);
}
}
}
public function startRow(): int
{
return 3;
}
}
When i dd($data) the result is like this
result dd
i got the data from my excel upload.
What's the problem ? why my data cannot save in the database
This code will return an Collection, which is an object, objects are always not empty.
DB::table('tbl_pegawai')->where('nip', $row[0])->get();
If you switch to first() it will return a model or null, effectively doing what you intended to.
DB::table('tbl_pegawai')->where('nip', $row[0])->first();
I have been in this situation before and figured that it can be caused by different factors. You might want to try the following:
Save the file you're about to upload to Excel 97-2003 Workbook format first.
Make sure the columns you're inserting data into is included in protected $fillable under App\PegawaiModel.
If certain cells in your spreadsheet are empty, make a validation for it.
Ex.
if ($row[0] === null) {
$row = null;
}
or if it's a string column that's not nullable, you can do
if ($row[0] === null) {
$row = 'NO DATA';
}
I'M USING SYMFONY 4.12 I'm trying to write queries to filter my jobs(I've job table ,départements one) I first try with experience but I'm stuck in
here is my offerController:
/**
* #Route("/offres", name="offres")
* #param Request $request
* #param PaginatorInterface $paginator
* #param FormFactoryInterface $formFactory
* #return Response
*/
public function offreSearch(Request $request, PaginatorInterface $paginator ,FormFactoryInterface $formFactory):Response
{
$datas =new OffreEmploi();
$formFilter=$formFactory->create(OfferFilterForm::class,$datas);
$offres = $this->repository->findSearch($datas);
$formFilter->handleRequest($request);
return $this->render('offre/index.html.twig', [
'controller_name' => 'OffreController',
'offres' => $offres,
'formulaire' =>$formFilter->createView(),
]);
}
and this is my query in the offerRepository:
public function findSearch(OffreEmploi $data):?array
{
$query = $this->createQueryBuilder('o');
if ($data->getExperience() !== null) {
$query
->where('o.experience > :experience')
->setParameter('experience', $data->getExperience());
}
return $query->getQuery()->getResult();
}
when it come to enter any number IT gives the same thing it shows all the jobs stored in the database,I don't know where the problem is.
THE RESULT
Try with this solution:
public function findSearch(OffreEmploi $data):?array
{
$query = $this->createQueryBuilder('o');
if (!empty($data->getExperience())
// ...
}
return $query->getQuery()->getResult();
}
If it doesn't work , try to dump $data->getExperience() to see its value
public function findSearch(OffreEmploi $data):?array
{
$query = $this->createQueryBuilder('o');
dd($data->getExperience()) ;
}
EDIT
So try to do like this but be sure you send the form with GET method not POST:
public function offreSearch(Request $request, PaginatorInterface $paginator)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(OfferFilterForm::class);
$form->handleRequest($request);
$data = $request->query->all();
$qb = $em->getRepository(OffreEmploi::class)->findSearch($data);
$offres = $paginator->paginate($qb, $request->query->get('page', 1), 20);
return $this->render('offre/index.html.twig', array(
'formulaire' =>$form->createView(),
'offres' => $offres,
));
}
In the formType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('experience', IntegerType::class);
//.....
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => null,
'csrf_protection' => false,
));
}
public function getBlockPrefix()
{
return null;
}
and in the Repository:
public function findSearch($data)
{
$query = $this->createQueryBuilder('o');
if (!empty($data['experience'])) {
$query
->where('o.experience > :experience')
->setParameter('experience', $data['experience']);
}
return $query->getQuery()->getResult();
}
I think I found the answer but I just create another class witch contain all the form's field and that's it I don't know how it works because I didn't change significant things for that thinks for your help.
Here the part of the stacktrace where I have a problem:
Zend\Stdlib\Exception\BadMethodCallException
File:
/var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Stdlib/Hydrator/ArraySerializable.php:28
Message:
Zend\Stdlib\Hydrator\ArraySerializable::extract expects the provided object to implement getArrayCopy()
Stack trace:
0 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Fieldset.php(631): Zend\Stdlib\Hydrator\ArraySerializable->extract(Object(BookList\Model\Book))
1 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Form.php(942): Zend\Form\Fieldset->extract()
2 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Form.php(303): Zend\Form\Form->extract()
3 /var/www/html/zf2/module/BookList/src/BookList/Controller/BookController.php(59): Zend\Form\Form->bind(Object(BookList\Model\Book))
The action method in my Controller that call bind:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('book');
}
try {
$book = $this->getBookTable()->getBook($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('book', array(
'action' => 'index'
));
}
$form = new BookForm();
$form->bind($book); // this is the line 59 of BookController
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($book->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getBookTable()->saveBook($book);
// Redirect to list of books
return $this->redirect()->toRoute('book');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
I checked also the BookTable class to see the object returned from the resulset and it's an istance of Book.
Than I opened the ArratSerializable.php and check the object passed and tre response is:
BookList\Model\Book Object ( [id] => 5 [author] => Gotye [title] => Making Mirrors [inputFilter:protected] => )
So it's a correct object, why doesn't it work?
How the result is returned you generally tell that to the ResultSet object while building your model. You actually set a prototype there for returning your result set saying, hey! "Use this prototype" which is, in your case, Book model. It does have a method called getArrayCopy() which is missing. That actually rises error in this case. So please add this to the Book model thus
class Book
{
// other properties and methods should be here
// add this method here
public function getArrayCopy()
{
return get_object_vars($this);
}
}