I have dynamic data that will be exported into excel using maatwebsite. I have a case where I need to merge the same data. How can I do it from a collection?
From This:
To This:
class PerencanaanExport implements
FromCollection,
WithCustomStartCell,
WithEvents,
ShouldAutoSize,
WithStyles
{
/**
* #return \Illuminate\Support\Collection
*/
public function __construct(string $tahun)
{
$this->tahun = $tahun;
}
public function startCell(): string
{
return "A3";
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
/** #var Sheet $sheet */
$tahun =
$this->tahun == "null"
? ""
: ($this->tahun == "all"
? ""
: $this->tahun);
$sheet = $event->sheet;
$sheet->mergeCells("A1:E1");
$sheet->setCellValue("A1", "Kode");
$sheet->setCellValue("A2", "Urusan");
$sheet->setCellValue("B2", "Bidang Urusan");
$sheet->setCellValue("C2", "Program");
$sheet->setCellValue("D2", "Kegiatan");
$sheet->setCellValue("E2", "Sub Kegiatan");
$sheet->mergeCells("F1:F2");
$sheet->setCellValue(
"F1",
"Urusan/ Bidang Urusan Pemerintahan Daerah dan Program Kegiatan"
);
$sheet->mergeCells("G1:G2");
$sheet->setCellValue(
"G1",
"Indikator Kinerja Program/ Kegiatan"
);
$sheet->mergeCells("H1:K1");
$sheet->setCellValue("H1", "Rencana Tahun " . $tahun);
$sheet->setCellValue("H2", "LOKASI");
$sheet->setCellValue("I2", "TARGET KINERJA");
$sheet->setCellValue("J2", "ANGGARAN");
$sheet->setCellValue("K2", "SUMBER DANA");
$styleArray = [
"borders" => [
"allBorders" => [
"borderStyle" =>
\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
"color" => ["argb" => "000000"],
],
],
];
$cellRange = "A1:K" . $sheet->getHighestRow(); // All headers
$event->sheet
->getDelegate()
->getStyle($cellRange)
->applyFromArray($styleArray);
$event->sheet
->getStyle("A1:K2")
->getAlignment()
->setVertical(StyleAlignment::VERTICAL_TOP)
->setHorizontal(StyleAlignment::VERTICAL_CENTER)
->setWrapText(true);
},
];
}
public function collection()
{
$arr = [];
$tahun = $this->tahun;
$jointahun = "";
if ($tahun) {
$jointahun = " AND d.tahun =" . $tahun;
}
$query = "XXXXX";
$query .= "XXXXX";
$data = DB::select($query);
$oldProgram = "";
$oldKegiatan = "";
foreach ($data as $key => $value) {
if ($key != 0) {
$oldProgram = $data[$key - 1]->program;
$oldKegiatan = $data[$key - 1]->kegiatan;
}
if ($oldProgram != $value->program) {
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
"",
"",
$value->program,
]);
}
if ($oldKegiatan != $value->kegiatan) {
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
$value->kode_kegiatan,
"",
$value->kegiatan,
$value->indikator_kegiatan,
]);
}
array_push($arr, [
$value->kode_urusan,
$value->kode_bidang_urusan,
$value->kode_program,
$value->kode_kegiatan,
$value->kode_sub_kegiatan,
$value->sub_kegiatan,
$value->indikator_perencanaan,
$value->lokasi,
$value->target_kinerja,
$value->anggaran,
$value->sumber_dana,
]);
}
return collect($arr);
}
public function styles(Worksheet $sheet)
{
$sheet
->getStyle("1:2")
->getFont()
->setBold(true);
}
Related
I am generating a xlsx file with PHPspreadshet and it always gives me an empty file (0kb) when it has more than 16 rows. I already tried to search for erros etc. and found nothing. It just depends on the row.
The Spreadsheet (Html for testing):
And when I switch following lines:
$this->sheet->setCellValue("A16", "Besetzt");
To
$this->sheet->setCellValue("A17", "Besetzt");
The generator (execute() is the entry point):
class ExcelOperation extends AbstractOperation
{
private function addWork($cell, $name = "", $phone = ""){
if($cell != null){
$richText = new \PhpOffice\PhpSpreadsheet\RichText\RichText();
$boldText = $richText->createText($name);
//$boldText->getFont()->setBold(true);
$richText->createText("\n".$phone);
$this->sheet->getCell($cell)->setValue($richText);
$this->sheet->getStyle($cell)->getAlignment()->setWrapText(true);
$this->sheet->getStyle($cell)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
}
}
public function execute(WebRequest $wreq, WebResponse $wres){
$eventId = $wreq->getParameter();
$userId = "1839357067871549236";
$calendar = $this->getCalendar($userId, $eventId);
$eventStatistics = $this->getEventStatistics($eventId);
//All Positions
$this->renderPositionData($calendar);
//$this->renderCurrentStatus($eventStatistics);
$this->formatColumn("A");
$this->formatColumn("B");
$this->formatColumn("C");
$this->formatColumn("D");
//$writer = new Xlsx($this->spreadsheet);
$writer = new Html($this->spreadsheet);
$wres->success(true);
$wres->set("filename", "Schichtplan.html");
$wres->set("file", $writer->save('php://output'));
}
private function addFullBorder($from, $to){
/*$styleArray = array(
'borders' => array(
'outline' => array(
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
'color' => array('argb' => PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLACK),
),
),
);
$this->sheet ->getStyle($from.':'.$to)->applyFromArray($styleArray);*/
}
private function renderCurrentStatus($statistics){
$this->sheet->setCellValue("F2", "Stand");
$this->sheet->mergeCells('F2:G2');
$this->sheet->getStyle("F2")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
$this->sheet->getStyle("F2")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
$this->sheet->getStyle("F2")->getFill()->getStartColor()->setRGB("A4DDF5");
$this->sheet->getStyle("F2")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$frei = $statistics["gesamt"]-($statistics["warten"]+$statistics["besetzt"]);
$this->sheet->setCellValue("F2", "Frei");
$this->sheet->setCellValue("G2", $frei);
$this->sheet->setCellValue("F4", "Besetzt");
$this->sheet->setCellValue("G4", $statistics["besetzt"]);
$this->sheet->setCellValue("F6", "Wartend");
$this->sheet->setCellValue("G6", $statistics["warten"]);
$this->sheet->setCellValue("F8", "Gesamt");
$this->sheet->setCellValue("G8", $statistics["gesamt"]);
$this->addFullBorder("F2", "G8");
}
private function renderPositionData($calendar){
foreach($calendar as $positionId => $position){
$positionName = $position["position"]["alle_positionen_description"];
preg_match('/Pos\. [0-9]+/', $positionName, $matches);
$positionEndCell = null;
$actualCol = $this->positionCount%$this->positionsPerLine;
if(isset($matches[0])){
$shortPositionName = $matches[0];
}else{
$shortPositionName = $positionName;
}
if($actualCol <5){
$cell = $this->getCell($actualCol, $this->actualRowPerPosition);
//var_dump($cell);
//For Position header
$this->actualRowPerPosition[$actualCol] += 1;
$this->addPositionHeader($cell, $shortPositionName);
$positionStartCell = $cell;
//All shifts within this job
foreach($position["jobs"] as $job){
//For Each Shift in Position
$cell = $this->getCell($actualCol, $this->actualRowPerPosition);
//$cell = "A17";
//var_dump($cell);
$this->sheet->setCellValue("A17", "Besetzt");
$formattedDateFrom = $this->dbDateToTime($job["job"]["alle_schichten_start"]);
$formattedDateTo = $this->dbDateToTime($job["job"]["alle_schichten_ende"]);
$this->addShiftHeader($cell, $formattedDateFrom." - ".$formattedDateTo);
$this->actualRowPerPosition[$actualCol] = 18;
$positionEndCell = $cell;
foreach($job["workers"] as $worker){
$fullName = $worker["firstname"]." ".$worker["secondname"];
$phone = "+43";
$cell = $this->getCell($actualCol, $this->actualRowPerPosition);
$this->addWork($cell, $fullName, $phone);
//$this->actualRowPerPosition[$actualCol] += 1;
$positionEndCell = $cell;
}
}
if($positionEndCell == null){
$positionEndCell = $positionStartCell;
}
$this->addFullBorder($positionStartCell, $positionEndCell);
$this->positionCount++;
}
}
}
private function formatColumn($columnName){
$this->sheet->getColumnDimension($columnName)->setWidth(35);
}
private function dbDateToTime(string $dateTime){
$date = new \DateTime($dateTime);
$formattedDateFrom = $date->format('H:i');
return $formattedDateFrom;
}
private function getCell($actualCol, $actualRowPerPosition){
$actualRow = $actualRowPerPosition[$actualCol]+1;
$actualColName = $this->getColName($actualCol);
$cell = $actualColName.$actualRow;
$this->sheet->getRowDimension($actualRow)->setRowHeight(30);
return $cell;
}
private function addPositionHeader($cell, $positionName){
$this->sheet->setCellValue($cell, $positionName);
//Font Color
$this->sheet->getStyle($cell)->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$this->sheet->getStyle($cell)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
//Background Color
$this->sheet->getStyle($cell)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
$this->sheet->getStyle($cell)->getFill()->getStartColor()->setRGB("A4DDF5");
}
private function addShiftHeader($cell, $shiftText){
$this->sheet->setCellValue($cell, $shiftText);
$this->sheet->getStyle($cell)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
}
private function getColName($colId){
$cols = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"];
return $cols[$colId];
}
private function getCalendar($userId, $eventId){
$dbManager = new DbManager();
$jobs = $dbManager->getAdminCalendarForUser($eventId, $userId);
$calendar = $this->generateCalendarArray($jobs);
return $calendar;
}
private function getEventStatistics($eventId){
$dbManager = new DbManager();
$eventStatistics = $dbManager->getEventStatistics($eventId);
return $eventStatistics;
}
private function generateCalendarArray($jobs){
$dbManager = new DbManager();
$calendar = [];
foreach ($jobs as $job) {
if(!isset($calendar[$job["alle_positionen_id"]])){
$jobFieldsWithValues = $this->getJobFieldsWithValues($dbManager, $job["alle_positionen_id"]);
$job["needs_approval"] = $job["needs_approval"] ? true : false;
$calendar[$job["alle_positionen_id"]] =
[
"position" =>$job,
"jobFieldsWithValues"=> $jobFieldsWithValues,
"jobs" => [],
"positionPermission"=>$job["positionPermission"]
];
}
//Check if position has shift
if($job["alle_schichten_id"] != null){
//Check if job in this shift (falsely defined as job) exists
if(!isset($calendar[$job["alle_positionen_id"]]["jobs"][$job["alle_schichten_id"]])){
$calendar[$job["alle_positionen_id"]]["jobs"][$job["alle_schichten_id"]] = [
"job"=>$job,
"workers"=>[]
];
}
if($job["Email"] != null){
$jobDef = [
"email"=>$job["Email"],
"approved"=>$job["Approved"],
"userId"=>$job["id"]."",
"firstname"=>$job["Vorname"],
"secondname"=>$job["Nachname"]
];
array_push($calendar[$job["alle_positionen_id"]]["jobs"][$job["alle_schichten_id"]]["workers"], $jobDef);
}
}
}
return $calendar;
}
private function getJobFieldsWithValues(DbManager $dbManager, int $positionId) : array{
$jobFieldsWithValues = [];
$jobFields = $dbManager->getJobFieldsWithValues($positionId);
foreach ($jobFields as $jobField) {
if(isset($jobFieldsWithValues[$jobField["id"]])){
array_push($jobFieldsWithValues[$jobField["id"]]["values"], ["data-value"=>$jobField["value"], "value"=>$jobField["value"]]);
}else{
$jobFieldsWithValues[$jobField["id"]] = [
"id"=>$jobField["id"],
"fieldBaseType"=>$jobField["fieldDataType"],
"name"=>$jobField["Bezeichnung"],
"description"=>$jobField["description"],
"values"=>[]];
array_push($jobFieldsWithValues[$jobField["id"]]["values"], ["data-value"=>$jobField["value"], "value"=>$jobField["value"]]);
}
}
return $jobFieldsWithValues;
}
public function __construct() {
$this->spreadsheet = new Spreadsheet();
$this->sheet = $this->spreadsheet->getActiveSheet();
$this->positionsPerLine = 4;
$this->actualRowPerPosition = [0,0,0,0];
$this->positionCount = 0;
$this->colors = [
"black"=>\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLACK
];
}
}
It generates an empty file.
One of my project needs code indentation, it has many of controller files looking like below code.
so basically I want to do is format code which should be done automatically without changing each file manually.
Controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use File;
use Html;
use DB;
use Illuminate\Validation\Rule;
use Illuminate\Support\Str;
use Validator;
use Datatables;
use AppHelper;
use LaraCore;
use Image;
use App\Models\Customer;
use App\Models\_List;
use Carbon;
class CustomerController extends Controller
{
public function validator(array $data, $id = NULL)
{
$email_Rules = explode(',',"required,email,unique");
$email_Rules['unique'] = Rule::unique('customers')->ignore($id);
if(($key = array_search('unique',$email_Rules)) !== false) {
unset($email_Rules[$key]);
}
return Validator::make($data, [
'secret_key' => 'required|min:6|max:10',
'email' => $email_Rules,
'first_name' => 'required|alpha_num',
'city' => 'required',
]
);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('panel.customers.index');
}
public function create()
{
$data = array();
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
return view('panel.customers.create',$data);
}
public function edit($id,Request $request)
{
$data = array();
$Dates = array();
$customers = Customer::findOrFail($id);
$data['customers'] = $customers;
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$preference= explode(',',$customers->preference);
$customers->preference = $preference;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
if($customers->ready!=''){
$ready= explode(',',$customers->ready);
$customers->ready = $ready;
}
if($customers->approved!=''){
$approved= explode(',',$customers->approved);
$customers->approved = $approved;
}
$Name = explode(',','start_date,end_date');
$Dates[0] = new Carbon($customers->$Name[0]);
$Dates[1] = new Carbon($customers->$Name[1]);
$data['start_dateend_date'] = $Dates[0]->format('m/d/Y').' - '.$Dates[1]->format('m/d/Y') ;
return view('panel.customers.create',$data);
}
public function store(Request $request,$id="")
{
$this->validator($request->all(),$request->id)->validate();
if($request->id == null || $request->id == ""){
$inputs = $request->all();
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}else{
$inputs['ready'] = "";
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$nameArr = explode(',',$key_file);
$file = $value_file;
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
}
Customer::create($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
else{
$customers = Customer::where(['id'=>$request->input('id')])->first();
$inputs = $request->except('_token');
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$nameArr = explode(',',$key_file);
$OldFile = $customers->$nameArr[1];
if($OldFile!=''){
$OldFile = $destinationPath.'/'.$OldFile;
if(\File::exists($OldFile)){
\File::delete($OldFile);
}
}
$file = $value_file;
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
$SavedFile = $destinationPath.$encrypted_name;
}
$customers->update($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
}
public function listCustomer(Request $request)
{
$customers = Customer::all();
$datatables = Datatables::of($customers)
->addColumn('actions', function($customers){
$html = '';
$html .= '<i class="fa fa-edit"></i>';
$html .= '<i class="fa fa-trash"></i>';
return $html;
})
->setRowId('id');
return $datatables->make();
}
public function destroy($id)
{
$customer = Customer::find($id);
$customer->delete();
return response()->json(array(
"status" => "success",
"message" => "Customer Deleted Successfully",
));
}
}
Maybe you could call a php beautifier on the file you created ? http://pear.php.net/package/PHP_Beautifier/
Note : you can call a command with exec
exec("php_beautifier $filename $filename");
It is hard to tell without more of your source but I imagine expressions like explode(',', $value["dbfield"] )[0] are catching some sort of tab character or importing blank fields that are somehow translated into spaces or tabs and causing the unwanted spacing.
#foreach($fields as $key => $value)
#if($value['dbfield'] == '')
#continue
#endif
#if($value['validation'])
#if(in_array('unique',explode(',',$value['validation'])))
'{{$value['dbfield']}}' => ${{$value['dbfield']}}_rules,
#else
#if(strpos($value["dbfield"],","))
'{{ explode(',', $value["dbfield"] )[0] }}' => '{{str_replace(',', '|', $value['validation'])}}',
#else
'{{$value['dbfield']}}' => '{{str_replace(',', '|', $value['validation'])}}',
#endif
#endif
#endif
#endforeach
I'm a total newbie to Wordpress and having a hard time figuring things out.
I'm using plugin called "WP-Pro-Quiz", a quiz plugin, and within the plugin there's an option to show "Leaderboard" of all users who completed the quiz. In the leaderboard on the frontend, there's user id, time, points and user's Display Name, etc for each user..
What I want to achieve is to make Display name clickable (and then to go to author's profile once clicked). That is, to connect Display Name with author profile who took the quiz, to create hyperlink from Display Name.
This is from controller WpProQuiz_Controller_Toplist.php :
<?php
class WpProQuiz_Controller_Toplist extends WpProQuiz_Controller_Controller
{
public function route()
{
$quizId = $_GET['id'];
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
default:
$this->showAdminToplist($quizId);
break;
}
}
private function showAdminToplist($quizId)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
$view = new WpProQuiz_View_AdminToplist();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$view->quiz = $quiz;
$view->show();
}
public function getAddToplist(WpProQuiz_Model_Quiz $quiz)
{
$userId = get_current_user_id();
if (!$quiz->isToplistActivated()) {
return null;
}
$data = array(
'userId' => $userId,
'token' => wp_create_nonce('wpProQuiz_toplist'),
'canAdd' => $this->preCheck($quiz->getToplistDataAddPermissions(), $userId),
);
if ($quiz->isToplistDataCaptcha() && $userId == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$data['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$data['captcha']['code'] = $captcha->getPrefix();
}
}
return $data;
}
private function handleAddInToplist(WpProQuiz_Model_Quiz $quiz)
{
if (!wp_verify_nonce($this->_post['token'], 'wpProQuiz_toplist')) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!isset($this->_post['points']) || !isset($this->_post['totalPoints'])) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$quizId = $quiz->getId();
$userId = get_current_user_id();
$points = (int)$this->_post['points'];
$totalPoints = (int)$this->_post['totalPoints'];
$name = !empty($this->_post['name']) ? trim($this->_post['name']) : '';
$email = !empty($this->_post['email']) ? trim($this->_post['email']) : '';
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$captchaAnswer = !empty($this->_post['captcha']) ? trim($this->_post['captcha']) : '';
$prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
if ($quiz == null || $quiz->getId() == 0 || !$quiz->isToplistActivated()) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!$this->preCheck($quiz->getToplistDataAddPermissions(), $userId)) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$numPoints = $quizMapper->sumQuestionPoints($quizId);
if ($totalPoints > $numPoints || $points > $numPoints) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$clearTime = null;
if ($quiz->isToplistDataAddMultiple()) {
$clearTime = $quiz->getToplistDataAddBlock() * 60;
}
if ($userId > 0) {
if ($toplistMapper->countUser($quizId, $userId, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
$user = wp_get_current_user();
$email = $user->user_email;
$name = $user->display_name;
} else {
if ($toplistMapper->countFree($quizId, $name, $email, $ip, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
if (empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return array('text' => __('No name or e-mail entered.', 'wp-pro-quiz'), 'clear' => false);
}
if (strlen($name) > 15) {
return array('text' => __('Your name can not exceed 15 characters.', 'wp-pro-quiz'), 'clear' => false);
}
if ($quiz->isToplistDataCaptcha()) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
if (!$captcha->check($prefix, $captchaAnswer)) {
return array('text' => __('You entered wrong captcha code.', 'wp-pro-quiz'), 'clear' => false);
}
}
}
}
$toplist = new WpProQuiz_Model_Toplist();
$toplist->setQuizId($quizId)
->setUserId($userId)
->setDate(time())
->setName($name)
->setEmail($email)
->setPoints($points)
->setResult(round($points / $totalPoints * 100, 2))
->setIp($ip);
$toplistMapper->save($toplist);
return true;
}
private function preCheck($type, $userId)
{
switch ($type) {
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ALL:
return true;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_ANONYM:
return $userId == 0;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_USER:
return $userId > 0;
}
return false;
}
public static function ajaxAdminToplist($data)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
return json_encode(array());
}
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$j = array('data' => array());
$limit = (int)$data['limit'];
$start = $limit * ($data['page'] - 1);
$isNav = isset($data['nav']);
$quizId = $data['quizId'];
if (isset($data['a'])) {
switch ($data['a']) {
case 'deleteAll':
$toplistMapper->delete($quizId);
break;
case 'delete':
if (!empty($data['toplistIds'])) {
$toplistMapper->delete($quizId, $data['toplistIds']);
}
break;
}
$start = 0;
$isNav = true;
}
$toplist = $toplistMapper->fetch($quizId, $limit, $data['sort'], $start);
foreach ($toplist as $tp) {
$j['data'][] = array(
'id' => $tp->getToplistId(),
'name' => $tp->getName(),
'email' => $tp->getEmail(),
'type' => $tp->getUserId() ? 'R' : 'UR',
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
if ($isNav) {
$count = $toplistMapper->count($quizId);
$pages = ceil($count / $limit);
$j['nav'] = array(
'count' => $count,
'pages' => $pages ? $pages : 1
);
}
return json_encode($j);
}
public static function ajaxAddInToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$ctn = new WpProQuiz_Controller_Toplist();
$quizId = isset($data['quizId']) ? $data['quizId'] : 0;
$prefix = !empty($data['prefix']) ? trim($data['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$r = $ctn->handleAddInToplist($quiz);
if ($quiz->isToplistActivated() && $quiz->isToplistDataCaptcha() && get_current_user_id() == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$captcha->remove($prefix);
$captcha->cleanup();
if ($r !== true) {
$r['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$r['captcha']['code'] = $captcha->getPrefix();
}
}
}
if ($r === true) {
$r = array('text' => __('You signed up successfully.', 'wp-pro-quiz'), 'clear' => true);
}
return json_encode($r);
}
public static function ajaxShowFrontToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$quizIds = empty($data['quizIds']) ? array() : array_unique((array)$data['quizIds']);
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$j = array();
foreach ($quizIds as $quizId) {
$quiz = $quizMapper->fetch($quizId);
if ($quiz == null || $quiz->getId() == 0) {
continue;
}
$toplist = $toplistMapper->fetch($quizId, $quiz->getToplistDataShowLimit(), $quiz->getToplistDataSort());
foreach ($toplist as $tp) {
$j[$quizId][] = array(
'name' => $tp->getName(),
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
}
return json_encode($j);
}
}
and from model WpProQuiz_Model_Toplist.php:
<?php
class WpProQuiz_Model_Toplist extends WpProQuiz_Model_Model
{
protected $_toplistId;
protected $_quizId;
protected $_userId;
protected $_date;
protected $_name;
protected $_email;
protected $_points;
protected $_result;
protected $_ip;
public function setToplistId($_toplistId)
{
$this->_toplistId = (int)$_toplistId;
return $this;
}
public function getToplistId()
{
return $this->_toplistId;
}
public function setQuizId($_quizId)
{
$this->_quizId = (int)$_quizId;
return $this;
}
public function getQuizId()
{
return $this->_quizId;
}
public function setUserId($_userId)
{
$this->_userId = (int)$_userId;
return $this;
}
public function getUserId()
{
return $this->_userId;
}
public function setDate($_date)
{
$this->_date = (int)$_date;
return $this;
}
public function getDate()
{
return $this->_date;
}
public function setName($_name)
{
$this->_name = (string)$_name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setEmail($_email)
{
$this->_email = (string)$_email;
return $this;
}
public function getEmail()
{
return $this->_email;
}
public function setPoints($_points)
{
$this->_points = (int)$_points;
return $this;
}
public function getPoints()
{
return $this->_points;
}
public function setResult($_result)
{
$this->_result = (float)$_result;
return $this;
}
public function getResult()
{
return $this->_result;
}
public function setIp($_ip)
{
$this->_ip = (string)$_ip;
return $this;
}
public function getIp()
{
return $this->_ip;
}
}
I'm just practicing using session in Codeigniter and i've got a Problem here's my controller
public function ajax_Addfees()
{
if($this->input->is_ajax_request())
{
$input = $this->input->post();
if($this->session->userdata('html')){
$html = $this->session->userdata('html');
}
$id = explode($input['fno']);
$html[$id] = ['amount' => $input['amount'], 'oldamount' => $input['deduction']];
$this->session->set_userdata('html', $html);
}
}
public function savetuition()
{
$this->Tuition_model->savefees();
redirect('tuitionsetup_con');
}
This is my model
public function savefees()
{
$fees = $this->session->userdata('html');
$feeslist = [];
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
array_push($feeslist, [
'amount' => $value['amount'],
'oldamount' => $value['oldamount'],
'f_no' => $key,
'sy_no' => $this->session->userdata('sy'),
'level_no' => $this->session->userdata('lvl'),
'id' => $this->session->userdata('id')
]);
$this->db->insert_batch('tuition', $feeslist);
} }
}
Well what I'm trying to do is to save data from session->set_userdata('html') to my database using codeigniter.
There's no error but it doesn't save data to database
You need to modify your model as:
public function savefees() {
$fees = $this->session->userdata('html');
$feeslist = array();
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
$feeslist[$key]["amount"] = $value['amount'];
$feeslist[$key]["oldamount"] = $value['oldamount'];
$feeslist[$key]["f_no"] = $key;
$feeslist[$key]["sy_no"] = $this->session->userdata('sy');
$feeslist[$key]["level_no"] = $this->session->userdata('lvl') ;
$feeslist[$key]["id"] = $this->session->userdata('id') ;
}
}
$this->db->insert_batch('tuition', $feeslist);
}
I used PHPExcel extension in Yii2 project and i have created component of PHPExcel object but this component export "Unreadable Content" Excel file.
I have read all possible solution for this issue from these links:
PHPExcel - .xlsx file downloads unreadable content
PHPExcel creates 'unreadable content'
https://stackoverflow.com/questions/32103447/excel-found-unreadable-content-with-phpexcel
PHPExcel unreadable content
I getting following "Unreadable content" Excel file :
And my code is,
component ExcelGrid.php :
<?php
namespace app\components;
use Yii;
use Closure;
use yii\i18n\Formatter;
use yii\base\InvalidConfigException;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\widgets\BaseListView;
use yii\base\Model;
use \PHPExcel;
use \PHPExcel_IOFactory;
use \PHPExcel_Settings;
use \PHPExcel_Style_Fill;
use \PHPExcel_Writer_IWriter;
use \PHPExcel_Worksheet;
class ExcelGrid extends \yii\grid\GridView
{
public $columns_array;
public $properties;
public $filename='excel';
public $extension='xlsx';
private $_provider;
private $_visibleColumns;
private $_beginRow = 1;
private $_endRow;
private $_endCol;
private $_objPHPExcel;
private $_objPHPExcelSheet;
private $_objPHPExcelWriter;
public function init(){
parent::init();
}
public function run(){
//$this->test();
if (function_exists('mb_internal_encoding')) {
$oldEncoding=mb_internal_encoding();
mb_internal_encoding('utf8');
}
ob_start();
$this->init_provider();
$this->init_excel_sheet();
$this->initPHPExcelWriter('Excel2007');
$this->generateHeader();
$row = $this->generateBody();
$writer = $this->_objPHPExcelWriter;
$this->setHttpHeaders();
ob_end_clean();
$writer->save('php://output');
if (function_exists('mb_internal_encoding'))
mb_internal_encoding($oldEncoding);
exit;
Yii::$app->end();
//$writer->save('test.xlsx');
parent::run();
}
public function init_provider(){
$this->_provider = clone($this->dataProvider);
}
public function init_excel_sheet(){
$this->_objPHPExcel=new PHPExcel();
$creator = '';
$title = '';
$subject = '';
$description = 'Excel Grid';
$category = '';
$keywords = '';
$manager = '';
$created = date("Y-m-d H:i:s");
$lastModifiedBy = '';
extract($this->properties);
$this->_objPHPExcel->getProperties()
->setCreator($creator)
->setTitle($title)
->setSubject($subject)
->setDescription($description)
->setCategory($category)
->setKeywords($keywords)
->setManager($manager)
//->setCompany($company)
->setCreated($created)
->setLastModifiedBy($lastModifiedBy);
$this->_objPHPExcelSheet = $this->_objPHPExcel->getActiveSheet();
}
public function initPHPExcelWriter($writer)
{
$this->_objPHPExcelWriter = PHPExcel_IOFactory::createWriter(
$this->_objPHPExcel,
$writer
);
}
public function generateHeader(){
$this->setVisibleColumns();
$sheet = $this->_objPHPExcelSheet;
$colFirst = self::columnName(1);
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
$this->_endCol++;
$head = ($column instanceof \yii\grid\DataColumn) ? $this->getColumnHeader($column) : $column->header;
$cell = $sheet->setCellValue(self::columnName($this->_endCol) . $this->_beginRow, $head, true);
}
$sheet->freezePane($colFirst . ($this->_beginRow + 1));
}
public function generateBody()
{
$columns = $this->_visibleColumns;
$models = array_values($this->_provider->getModels());
if (count($columns) == 0) {
$cell = $this->_objPHPExcelSheet->setCellValue('A1', $this->emptyText, true);
$model = reset($models);
return 0;
}
$keys = $this->_provider->getKeys();
$this->_endRow = 0;
foreach ($models as $index => $model) {
$key = $keys[$index];
$this->generateRow($model, $key, $index);
$this->_endRow++;
}
// Set autofilter on
$this->_objPHPExcelSheet->setAutoFilter(
self::columnName(1) .
$this->_beginRow .
":" .
self::columnName($this->_endCol) .
$this->_endRow
);
return ($this->_endRow > 0) ? count($models) : 0;
}
public function generateRow($model, $key, $index)
{
$cells = [];
/* #var $column Column */
$this->_endCol = 0;
foreach ($this->_visibleColumns as $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
} else {
$format = $column->format;
$value = ($column->content === null) ?
$this->formatter->format($column->getDataCellValue($model, $key, $index), $format) :
call_user_func($column->content, $model, $key, $index, $column);
}
if (empty($value) && !empty($column->attribute) && $column->attribute !== null) {
$value =ArrayHelper::getValue($model, $column->attribute, '');
}
$this->_endCol++;
$cell = $this->_objPHPExcelSheet->setCellValue(self::columnName($this->_endCol) . ($index + $this->_beginRow + 1),
strip_tags($value), true);
}
}
protected function setVisibleColumns()
{
$cols = [];
foreach ($this->columns as $key => $column) {
if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
continue;
}
$cols[] = $column;
}
$this->_visibleColumns = $cols;
}
public function getColumnHeader($col)
{
if(isset($this->columns_array[$col->attribute]))
return $this->columns_array[$col->attribute];
/* #var $model yii\base\Model */
if ($col->header !== null || ($col->label === null && $col->attribute === null)) {
return trim($col->header) !== '' ? $col->header : $col->grid->emptyCell;
}
$provider = $this->dataProvider;
if ($col->label === null) {
if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) {
$model = new $provider->query->modelClass;
$label = $model->getAttributeLabel($col->attribute);
} else {
$models = $provider->getModels();
if (($model = reset($models)) instanceof Model) {
$label = $model->getAttributeLabel($col->attribute);
} else {
$label =$col->attribute;
}
}
} else {
$label = $col->label;
}
return $label;
}
public static function columnName($index)
{
$i = $index - 1;
if ($i >= 0 && $i < 26) {
return chr(ord('A') + $i);
}
if ($i > 25) {
return (self::columnName($i / 26)) . (self::columnName($i % 26 + 1));
}
return 'A';
}
protected function setHttpHeaders()
{
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: application/{$this->extension}; charset=utf-8");
header("Content-Disposition: attachment; filename={$this->filename}.{$this->extension}");
header("Expires: 0");
}
}
View file countryExcel.php :
<?php
\app\components\ExcelGrid::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'extension'=>'xlsx',
'filename'=>'country-list'.date('Y-m-dH:i:s'),
'properties' =>[
//'creator' =>'',
//'title' => '',
//'subject' => '',
//'category' => '',
//'keywords' => '',
//'manager' => '',
],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'country_name',
[
'attribute' => 'created_at',
'value' => function ($data) {
return Yii::$app->formatter->asDateTime($data->created_at);
},
],
[
'attribute' => 'created_by',
'value' => 'createdBy.user_login_id',
],
[
'attribute' => 'updated_at',
'value' => function ($data) {
return (!empty($data->updated_at) ? Yii::$app->formatter->asDateTime($data->updated_at) : Yii::t('stu', ' (not set) '));
},
],
[
'attribute' => 'updated_by',
'value' => 'updatedBy.user_login_id',
],
],
]);
?>
Controller File CountryController.php :
<?php
class CountryController extends Controller
{
.....
.......
public function actionExcel()
{
$searchModel = new CountrySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->renderPartial('CountryExportExcel', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
........
.....
}
?>
Thanks in Advance.
Its not a valid solution but it works for me..
header("Content-Disposition: attachment; filename=\"$filename\"");
$export =\moonland\phpexcel\Excel::export([
'models' => $exportData,
'columns' => $exportColumns,
'headers' => [
'created_at' => dtTZ()
],
]);
Your file seems a correct xlsx file opened with an editor like notepad++
could be a charcter encoding problem
Try change the encode
if (function_exists('mb_internal_encoding')) {
$oldEncoding=mb_internal_encoding();
mb_internal_encoding('utf8');
}
using a value for cp1250 -- to cp1258
encoding for microsoft in US-EN
(I hope your excel country installation config )