I am trying to save the attendance details for each employee into a db from an excel file as a bulk attendance upload , the code below displays Excel Data Imported Succesfully , but does not store values into the db, the line $last_id=$this->mod_common->add_attendence_data($data_user); is not executed , thats why its not working , How to make this line execute ? As this code was written by some other developer i am finding it difficult to understand.
Controller: admin_list.php
function upload_bulk_attendance(){
$data['htmltext'] = $this->mod_common->get_allleaves();
$this->data['maincontent'] = $this->load->view('maincontents/upload_attendance_sheet', $data,true);
$this->load->view('layout', $this->data);
}
function importExcel() {
//$this->mod_common->delete_attendance();
$this->load->library('excel');
//microsoft excel 2007
if(!$objReader = PHPExcel_IOFactory::createReader('Excel5')){
die('Unable to create reader object');
}
//$objReader = PHPExcel_IOFactory::createReader('Excel2007');
//set to read only
$objReader->setReadDataOnly(false);
//load excel file
global $SITE;
if(!$upload_val=$this->admin_init_elements->do_upload_docs('user_attendance',$SITE->client_logo_image_src,false)){
$data['error'] = $this->upload->display_errors();
$this->load->view('maincontents/upload_attendance_sheet', $data,true);
} else {
$file_path = $upload_val['upload_data']['full_path'];
}
$objPHPExcel = $objReader->load($file_path);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(1);
/*---------------------------------------------------------------------------*/
$excelrow = 1;
$from_Date = $objWorksheet->getCellByColumnAndRow(4,1)->getValue();
$to_Date = $objWorksheet->getCellByColumnAndRow(6,1)->getValue();
$total_rows_in_sheet = $objPHPExcel->getActiveSheet()->getHighestRow();
if (PHPExcel_Shared_Date::isDateTime($objPHPExcel->getActiveSheet()->getCell('E1'))) {
$dateValue = PHPExcel_Shared_Date::ExcelToPHP($from_Date);
$from_date = date('Y-m-d',$dateValue);
}
if (PHPExcel_Shared_Date::isDateTime($objPHPExcel->getActiveSheet()->getCell('G1'))) {
$dateValue = PHPExcel_Shared_Date::ExcelToPHP($to_Date);
$to_date = date('Y-m-d',$dateValue);
}
$start = strtotime($from_date);
$end = strtotime($to_date);
$days_between = ceil(abs($end - $start) / 86400);
$excelrow = $excelrow + 2;
$emp_code_id_array = $this->mod_common->get_Details2('pr_users_details',array('userid','emp_code'));
foreach($emp_code_id_array as $e){ $emp_code_id[$e['emp_code']] = $e['userid']; }
do {
$shift_excelrow = ++$excelrow;
/*--------------- Moving row wise for each employees data --------------*/
$emp_code = $objWorksheet->getCellByColumnAndRow(0,$excelrow)->getValue();
$emp_code =($emp_code==null)?0:$emp_code;
if($emp_code<=0) continue;
$emp_code = str_pad($emp_code, 3, '0', STR_PAD_LEFT);
$emp_id =($emp_code_id[$emp_code]==null)?0:$emp_code_id[$emp_code];
$emp_name = $objWorksheet->getCellByColumnAndRow(1,$excelrow)->getValue();
/*--------------- Moving column wise for each days data --------------*/
$col_no=3;
for($i=0;$i<=$days_between;$i++) {
$dt = date('Y-m-d',strtotime($from_date));
$day = date('d', strtotime($dt .' +'.$i.' day'));
$entry[] = $day."|".$objWorksheet->getCellByColumnAndRow($col_no,$shift_excelrow)->getValue();
$col_no++;
}
$present=$objWorksheet->getCellByColumnAndRow(34,$shift_excelrow)->getValue();
$absent=$objWorksheet->getCellByColumnAndRow(35,$shift_excelrow)->getValue();
$total=$objWorksheet->getCellByColumnAndRow(36,$shift_excelrow)->getValue();
if($emp_id!=0){
$emp_id_arr[] = $emp_id;
}
/* CREATING ARRAY FOR DB INSERT */
$data_user['emp_code'] = $emp_code;
$data_user['emp_id'] = $emp_id;
$data_user['name'] = $emp_name;
$data_user['entry'] = implode(",",$entry);
$data_user['from_date'] = $from_date;
$data_user['to_date'] = $to_date;
$data_user['present'] = $present;
$data_user['absent'] = $absent;
$data_user['total'] = $total;
$data_user['current_date'] = date('Y-m-d');
$last_id=$this->mod_common->add_attendence_data($data_user);
//Reset array
$entry=array();
}while($excelrow <=$total_rows_in_sheet);
/*----------------------------------------------------*/
if(count($emp_id_arr)==0){
$emp_id_arr[] = 0;
}
$this->mod_common->save_attendance_notification($last_id,implode(",",$emp_id_arr),$data_user['from_date']);
$this->session->set_flashdata('success', 'Excel Data Imported Succesfully');
redirect(base_url().'admin_list/upload_bulk_attendance');
}//importExcel() END
Model: mod_common.php
function add_attendence_data($datauser) {
$emp_code = str_pad($datauser['emp_code'], 3, '0', STR_PAD_LEFT);
$this->db_replace->select('*');
$this->db_replace->from($this->myTables['attendance']);
$this->db_replace->where('emp_code',$emp_code);
$this->db_replace->where('from_date',$datauser['from_date']);
$query=$this->db_replace->get();
if($query->num_rows() <= 0)
{
$datauser['emp_code'] = $emp_code;
$this->db_replace->insert($this->myTables['attendance'],$datauser);
$instanceid = $this->db_replace->insert_id();
return $instanceid;
} else return false;
}
view : upload_attendance_sheet.php
<section class="content-header">
<h1>
Upload Attendance
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i> Home</li>
<li> Admin</li>
<li>Attendance</li>
<li class="active">Upload Attendance</li>
</ol>
</section>
<section class="content">
<div class="container-fluid">
<div class="row">
<!-- Thought Day-->
<div class="panel wrapper clearfix m-b-none">
<div class="box-header with-border">
<?php if($bulkUploadMsg!=''){?>
<?php echo $bulkUploadMsg;?>
<?php } ?>
<?php
if($this->session->flashdata('success') == TRUE){
echo $this->session->flashdata('success');
}
?>
<br>
<?php
echo form_open_multipart('admin_list/importExcel', array('method'=>'post','name'=>'uploadUserForm','id'=>'upload_file','class'=>"custom-form"));
?>
Please download attendance upload format by clicking here<br><br>
<table cellpadding="10px" style="background:none;width:100%;" RULES="ROWS">
<thead>
<tr>
<td width="50px;">Upload</td>
<td>:</td>
<td>
<?php echo form_upload(array("required"=>"required","name"=>"user_attendance","id"=>"user_attendance")); ?>
</td>
</tr>
</table>
<h3>Instructions to Upload : </h3>
<ul>
<li>Complete the sheet below and upload to update attendance records of all employees
</li><li>
You may add as many rows as needed - one for each employee
</li><li>Enter the start and end dates in the dd/mm/yyyy format only
</li><li>Only use the legend given to enter primary attendance details - Present at assigned office location-X, Absent without notification-A, On Official Travel-O, Present but not in office location-P, Week Off-W, Holiday-H, Half day working-D
</li><li>Use the following legends for entering Leave Details-<?php echo $htmltext; ?>
</li><li>As good practice, ensure that this sheet is uploaded at approximately the same interval each month
</li></ul><br>
</p>
<br>
<?php
echo form_submit(array('name'=>'submit','value'=>'Upload','class'=>'btn btn-info btn-submit pull-right add'));
echo form_close();
?>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/plugins/data-tables/DT_bootstrap.js"></script>
Table : pr_attendance
Please try this way:-
<?php
public function importContacts($id)
{
if(isset($_POST["Import"]))
{
$filename=$_FILES["file"]["name"];
$f_extension = explode('.',$filename);
$f_extension = strtolower(end($f_extension));
if($f_extension == 'csv') // for import CSV file
{
$file_tmp_name=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($file_tmp_name, "r");
$row = array();
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
array_push($row, $emapData);
}
fclose($file);
unset($row[0]);
foreach(array_values($row) as $r){
$data = array(
'gc_group_id' => $id,
'gc_user_id' => $this->session->userdata('userId'),
'gc_name' => #$r[1],
'gc_number' => #$r[0],
'gc_email' => #$r[2],
'gc_added_date' => date('Y-m-d'),
);
$this->user_model->add('groups_contact',$data);
array_push($valid_no, $r[0]);
}
fclose($file);
}
}
if($f_extension == 'xlsx' || $f_extension == 'xls')
{
/* PHPExcel library */
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
require_once APPPATH.'third_party/PHPExcel/IOFactory.php';
$file_tmp_name=$_FILES["file"]["tmp_name"];
try {
$objPHPExcel = PHPExcel_IOFactory::load($file_tmp_name);
} catch(Exception $e) {
die('Error loading file :' . $e->getMessage());
}
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
unset($sheetData[1]);
foreach(array_values($sheetData) as $s){
$data = array(
'gc_group_id' => $id,
'gc_user_id' => $this->session->userdata('userId'),
'gc_name' => #$s[B],
'gc_number' => #$s[A],
'gc_email' => #$s[C],
'gc_added_date' => date('Y-m-d'),
);
$this->user_model->add('groups_contact',$data);
array_push($valid_no, $s[A]);
}
}
$msg = 'Contacts Added Successfully ';
}
}
?>
Let me know please if you find any issues.
Related
I have archive.php in my content management system which allows to search for articles like mywebsite.com/archive?s=test. Now i tried to show this posts of the search query in another page of my page. Like <?php insert('archive.php?s=test'); ?> .
I am not an expert on PHP coding. But maybe you can show me a way how i could import this post of a search query with archive.php loop. Or tell me that this is not possible :-) Thank you.
This is the code my archive page.
<?php if (!$t['page_heading']) : ?>
<?php endif; ?>
<?php if (has_items($t['latest_posts'])) : ?>
<div class="row">
<?php foreach ($t['latest_posts'] as $t['loop']) : ?>
<div class="col-12 mb-3">
<?php insert('partials/loop.php'); ?>
</div>
<?php endforeach; ?>
</div> </div> </div>
<?= $t['pagination_html']; ?>
<?php else : ?>
<?php
insert(
'partials/empty.php',
[
'empty_message' => __('nothing-found-archive', _T)
]
);
?>
<?php endif; ?>
This is the loop.php
<?= e(limit_string($t['loop.post_title'], 65), false); ?>
</h3></a>
<div class="post-footer text-muted">
<div id="hidden-xs"> <?= e(limit_string($t['loop.post_excerpt'], 145), false); ?></div>
<div class="mb-1 mt-1"> <span class="badge badge-cat"><i class="fas fa-newspaper"></i> <?= e_attr($t['loop.feed_name']) ?></span> <span class="badge badge-cat"><i class="far fa-folder-open"></i> <?= e_attr($t['loop.category_name']) ?></span>
<span class="badge badge-cat"><i class="far fa-clock"></i> vor <?= time_ago($t['loop.post_pubdate'], _T); ?></span>
search function
public function archive()
{
$app = app();
$postModel = new PostModel;
$feedModel = new FeedModel;
$engineModel = new EngineModel;
$categoryModel = new CategoryModel;
$data = [
'title' => __('archive', _T),
'meta.description' => __('archive-description', _T),
'body_class' => 'archive',
'searching_site' => false,
'by_feed' => false,
];
$query = sp_strip_tags(trim($app->request->get('s')), true);
$feedID = (int) $app->request->get('feed', 0);
$feedsTable = $feedModel->getTable();
$postsTable = $postModel->getTable();
$categoriesTable = $categoryModel->getTable();
// Current page number
$currentPage = (int) $app->request->get('page', 1);
$filters['sort'] = 'post-publish-date';
if (mb_strlen($query) > 3) {
$filters['where'][] = ["{$postsTable}.post_title", 'LIKE', "%$query%"];
$filters['where'][] = ["{$postsTable}.post_content", 'LIKE', "%$query%", 'OR'];
$data['site_search_query'] = $query;
$data['searching_site'] = true;
$data['page_heading'] = sprintf(__('search-results-for', _T), $query);
$data['title'] = sprintf(__('search-results-for-title', _T), $query);
$data['meta.description'] = sprintf(__('search-results-for-desc', _T), $query);
$data['body_class'] .= ' search-results';
}
if ($feedID) {
$feed = $feedModel->read($feedID, ['feed_id', 'feed_name']);
if ($feed) {
$filters['where'][] = ["{$postsTable}.post_feed_id", '=', $feed['feed_id']];
$data['by_feed'] = true;
$data['feed'] = $feed;
$data['title'] = $feed['feed_name'];
$data['page_heading'] = $feed['feed_name'];
}
}
$itemsPerPage = (int) get_option('latest_posts_count', 10);
// Total item count
$totalCount = $postModel->countRows(null, $filters);
$pageQuery = [];
if ($data['searching_site']) {
$pageQuery['s'] = $query;
}
if ($data['by_feed']) {
$pageQuery['feed'] = $feedID;
}
$queryStr = http_build_query($pageQuery);
if (!empty($queryStr)) {
$queryStr = "&{$queryStr}";
}
// Pagination instance
$pagination = new Pagination($totalCount, $currentPage, $itemsPerPage);
$pagination->setUrl("?page=#id#{$queryStr}");
// Generated HTML
$paginationHtml = $pagination->renderHtml();
// Offset value based on current page
$offset = $pagination->offset();
// Fields to query
$fields[] = "{$postsTable}.post_id, {$postsTable}.post_category_id, {$postsTable}.post_title, {$postsTable}.post_excerpt, {$postsTable}.post_featured_image, {$postsTable}.post_type, {$postsTable}.post_source, {$postsTable}.post_pubdate, {$postsTable}.created_at, {$postsTable}.post_hits";
$fields[] = "{$feedsTable}.feed_name, {$feedsTable}.feed_id, {$feedsTable}.feed_logo_url";
$fields[] = "{$categoriesTable}.category_name, {$categoriesTable}.category_slug, {$categoriesTable}.category_icon";
// Query to fetch the users and their respective role names
$sql = $postModel->select($fields)
->leftJoin(
$feedsTable,
"{$postsTable}.post_feed_id",
'=',
"{$feedsTable}.feed_id"
)->leftJoin(
$categoriesTable,
"{$postsTable}.post_category_id",
'=',
"{$categoriesTable}.category_id"
)->limit($itemsPerPage, $offset);
// Apply Filters
$sql = $postModel->applyModelFilters($sql, $filters);
$stmt = $sql->execute();
// List entries
$latestPosts = $stmt->fetchAll();
$maxSliderItems = get_option('max_slider_items', 10);
$sliderPosts = array_slice($latestPosts, 0, $maxSliderItems);
$engines = $engineModel->readMany(['engine_id', 'engine_name']);
$data['default_engine'] = (int) get_option('default_engine');
$data['engines'] = $engines;
$data['archive_active'] = 'active';
$data['slider_posts'] = $sliderPosts;
$data['latest_posts'] = $latestPosts;
$data['pagination_html'] = $paginationHtml;
return view('archive.php', $data);
}
Here is my query:
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues WHERE tmplvarid=107");
I need to sort it by menuindex so i tried this:
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues JOIN modResource WHERE tmplvarid=107 ORDER BY menuindex DESC");
I'm not familiar at all whith this. Of course it doesn't work. Someone told me to use XPDO but i know nothing about it. Do i miss something? What should i do to make it work ?
Here is the full code :
<?php
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues WHERE tmplvarid=107");
// description tv: 108
// vignette tv: 121
if (!is_object($results)) {
return;
}
$breves = array();
while($r = $results->fetch(PDO::FETCH_COLUMN, 0)){
$breves[] = $r;
}
$queryIn = implode(',' , $breves);
$results_2 = $modx->query("SELECT contentid, tmplvarid, value FROM modx_site_tmplvar_contentvalues WHERE contentid IN ({$queryIn}) AND tmplvarid IN (108, 121)");
if (!is_object($results_2)) {
return;
}
$tvValues = array();
while($v = $results_2->fetch(PDO::FETCH_ASSOC)){
if($v['tmplvarid'] == 108){
$tvValues[$v['contentid']]['desc'] = $v['value'];
} else {
$tvValues[$v['contentid']]['vignette'] = $v['value'];
}
}
$output = "";
foreach ($breves as $res_id) {
$page = $modx->getObject('modResource', $res_id);
$alias = $page->get('alias');
$id = $page->get('id');
$page_title = $page->get('pagetitle');
$description = $tvValues[$res_id]['desc'];
if(!$description || $description == ""){
$description = $page->get('content');
}
$description = strip_tags($description);
$description = mb_strimwidth($description, 0, 150, "...");
$vignette = $tvValues[$res_id]['vignette'];
if($vignette){
$vignette = "/assets/upload/pln/" . $vignette;
} else {
$vignette = "https://www.commune-ploudaniel.fr/assets/templates/pln/default-b7824fcd998f51baf0f0af359a72e760.png";
}
$output .= <<<HTML
<div class="xpro-slider-item">
<div class="xp-news-classic-block">
<div class="xp-hover-image">
</div>
<a class="xp-view-lightbox" href="{$alias}.html" ><i class="fa fa-plus"></i></a>
<img src="{$vignette}" alt="{$alias}" style="width:375px; height:270px; object-fit: cover;"/>
</div>
<div class="xp-news-detail">
<h4>{$id}{$page_title}</h4>
<p>{$description}</p>
<div class='xp-news-footer'></div>
</div>
</div>
</div>
HTML;
$output .= PHP_EOL;
}
return $output;
Try this for MODX:
$q = $modx->newQuery('modTemplateVarResource');
$q->leftJoin('modResource', 'mr', 'mr.id = modTemplateVarResource.contentid');
$q->where(array(
'modTemplateVarResource.tmplvarid' => 107
));
$q->select(array(
'modTemplateVarResource.contentid'
));
$q->sortby('modResource.menuindex', 'DESC');
$q->prepare();
$q->stmt->execute();
$result = $q->stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
How to count total numbers of images inside our folders and subfolders?
I put this in my view. Well, as MVC way, this may look sucks to be in view. I know how to put this into models, but don't know how to call it with controllers and views
<?php
$img = count(glob("./assets/images/*.*"));
$about = count(glob("./assets/images/aboutus/*.*"));
$blog1 = count(glob("./assets/images/blog/*.*"));
$mason = count(glob("./assets/images/blog/masonary/*.*"));
$tl = count(glob("./assets/images/blog/timeline/*.*"));
$blog2 = count(glob("./assets/images/blogdetails/*.*"));
$gallery = count(glob("./assets/images/gallery/*.*"));
$home = count(glob("./assets/images/home/*.*"));
$home2 = count(glob("./assets/images/home/slider/*.*"));
$ico = count(glob("./assets/images/ico/*.*"));
$lb = count(glob("./assets/images/lightbox/*.*"));
$keg = count(glob("./assets/images/kegiatan/*.*"));
$port1 = count(glob("./assets/images/portfolio/*.*"));
$port2 = count(glob("./assets/images/portfolio-details/*.*"));
$leader = count(glob("./assets/images/leaders/*.*"));
$srv = count(glob("./assets/images/services/*.*"));
$usr = count(glob("./assets/images/users/*.*"));
$count = $img+$about+$blog1+$mason+$tl+$blog2+$gallery+$home+$home2+$ico+$lb+$keg+$port1+$port2+$leader+$srv+$usr;
?>
Output:
<div class="col-sm-3 text-center wow bounceIn" data-wow-duration="1000ms" data-wow-delay="300ms">
<h1 class="timer bold" data-to="<?= $count;?>" data-speed="3000" data-from="0"></h1>
<h3>Total Images</h3>
</div>
Is there a way to make this simple?
Please take a look at
https://stackoverflow.com/a/10895775/7089527
You could do it like this using the [RecursiveDirectoryIterator][1]
<?php
function scan_dir($path){
$ite=new RecursiveDirectoryIterator($path);
$bytestotal=0;
$nbfiles=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
$filesize=$cur->getSize();
$bytestotal+=$filesize;
$nbfiles++;
$files[] = $filename;
}
$bytestotal=number_format($bytestotal);
return array('total_files'=>$nbfiles,
'total_size'=>$bytestotal,'files'=>$files);
}
$files = scan_dir('./');
echo "Total: {$files['total_files']} files, {$files['total_size']} >bytes\n";
//Total: 1195 files, 357,374,878 bytes
?>
[1]: http://php.net/manual/en/class.recursivedirectoryiterator.php
Hope it helps
Format to call a method in a model from a controller.
Model file:
application/models/Photo_shoot_model.php
class Photo_shoot_model extends CI_Model {
public function image_count() {
$img = count(glob("./assets/images/*.*"));
$about = count(glob("./assets/images/aboutus/*.*"));
$blog1 = count(glob("./assets/images/blog/*.*"));
$mason = count(glob("./assets/images/blog/masonary/*.*"));
$tl = count(glob("./assets/images/blog/timeline/*.*"));
$blog2 = count(glob("./assets/images/blogdetails/*.*"));
$gallery = count(glob("./assets/images/gallery/*.*"));
$home = count(glob("./assets/images/home/*.*"));
$home2 = count(glob("./assets/images/home/slider/*.*"));
$ico = count(glob("./assets/images/ico/*.*"));
$lb = count(glob("./assets/images/lightbox/*.*"));
$keg = count(glob("./assets/images/kegiatan/*.*"));
$port1 = count(glob("./assets/images/portfolio/*.*"));
$port2 = count(glob("./assets/images/portfolio-details/*.*"));
$leader = count(glob("./assets/images/leaders/*.*"));
$srv = count(glob("./assets/images/services/*.*"));
$usr = count(glob("./assets/images/users/*.*"));
$count = $img+$about+$blog1+$mason+$tl+$blog2+$gallery+$home+$home2+$ico+$lb+$keg+$port1+$port2+$leader+$srv+$usr;
return $count;
}
}
In controller:
public function index() {
// load model
$this->load->model('photo_shoot_model');
// call method
$howManyImages = $this->photo_shoot_model->image_count()
}
All about models: https://codeigniter.com/user_guide/general/models.html
But really, I'd use the RecursiveDirectoryIterator mentioned by #MayurVirkar.
I am trying save batch record from form and save to database.
I got sample from Advanced Example it is a widgets. this. example only add record without save it I add a save bottom under widget and form top of widget. add code for add or update ,I add id filed in widget . records read from database .
when I update record i have not any problem but when I add record my program don't save new record i trace program and see $_post[model] include old record and have not new record . when I element id field from from . all record re-save I left program
pic1 pic2
_form_batch.php
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'person-form',
'enableAjaxValidation'=>true,
'enableClientValidation' => true,
)); ?>
<h2><?php
$persons2=Person::model()->findAll();
echo Help::item('annotation','title',!Yii::app()->user->isGuest); ?></h2>
<div class="large-text"><?php echo Help::item('annotation','content'); ?></div>sas
<?php $this->widget('ext.widgets.tabularinput.XTabularInput',array(
'models'=>$persons2,
'containerTagName'=>'table',
'headerTagName'=>'thead',
'header'=>'
<tr>
<td>'.CHtml::activeLabelEX(Person::model(),'id').'</td>
<td>'.CHtml::activeLabelEX(Person::model(),'firstname').'</td>
<td>'.CHtml::activeLabelEX(Person::model(),'lastname').'</td>
<td>'.CHtml::activeLabelEX(Person::model(),'country_id').'</td>
<td>'.CHtml::activeLabelEX(Person::model(),'eyecolor_code').'</td>
<td>'.CHtml::activeLabelEX(Person::model(),'email').'</td>
<td></td>
</tr>
',
'inputContainerTagName'=>'tbody',
'inputTagName'=>'tr',
'inputView'=>'extensions/_tabularInputAsTable',
'inputUrl'=>$this->createUrl('request/addTabularInputsAsTable2'),
'addTemplate'=>'<tbody><tr><td colspan="6">{link}</td></tr></tbody>',
'addLabel'=>Yii::t('ui','Add new row'),
'addHtmlOptions'=>array('class'=>'blue pill full-width'),
'removeTemplate'=>'<td>{link}</td>',
'removeLabel'=>Yii::t('ui','Delete'),
'removeHtmlOptions'=>array('class'=>'red pill'),
)); ?>
<div class="action">
<?php echo CHtml::submitButton($model->isNewRecord ? Yii::t('ui', 'Create') : Yii::t('ui','Save'),array('class'=>'btn btn-primary')); ?>
<?php echo CHtml::link(Yii::t('ui', 'Cancel'), $model->isNewRecord ? array('admin') : $this->getReturnUrl(), array('class'=>'btn')) ?>
</div>
<?php $this->endWidget(); ?>
controller:
$person = new Person;
$persons = $this->getItemsToUpdate();
// print_r($_POST); exit;
if (isset($_POST['Person'])) {
$valid = true;
foreach ($persons as $i => $person) {
if (isset($_POST['Person'][$i]))
$person->attributes = $_POST['Person'][$i];
$valid = $person->validate() && $valid;
print_r($_POST['Person'][$i]);
$person->save();
$errores = $person->getErrors();
// print_r($errores);
// echo " valid: " . $valid . "<br>";
}
}
$this->render('hame', array(
'model' => $persons,
));
}
public function getItemsToUpdate() {
// Create an empty list of records
$persons = array();
print_r($_POST['Person']);
// Iterate over each item from the submitted form
if (isset($_POST['Person']) && is_array($_POST['Person'])) {
foreach ($_POST['Person'] as $person) {
// If item id is available, read the record from database
if (array_key_exists('id', $person)) {
$persons[] = Person::model()->findByPk($person['id']);
}
// Otherwise create a new record
else {
$persons[] = new Person();
}
}
}
return $persons;
}
first point is:
**$person** = new Person;
foreach ($persons as $i => **$person**) {
second is:
i had some problems with foreach and save, better use
$cmd = Yii::app()->db->createCommand();
$cmd->insert(...
$cmd->update(...
otherwise you have to create new model on each iteration and than use save()
i'm currently trying to modify a module that works almost perfectly for my requirements, but lacks pagination. I can't seem to grasp how i should add the pagination to it; most JPagination examples assume i have access to the query but in this module (which uses JFactory, JmoduleHelper & JModel) i don't see the query in order to add the limits and such.
mod_otmininews.php
//No direct access!
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__).DS.'helper.php';
$doc = &JFactory::getDocument();
$doc->addStyleSheet(JURI::base().'/modules/mod_otmininews/css/layout.css');
$list = modOtMiniNewsHelper::getList($params);
$moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'));
require JModuleHelper::getLayoutPath('mod_otmininews', $params->get('layout', 'default'));
helper.php
//No direct access!
defined('_JEXEC') or die;
require_once JPATH_SITE.'/components/com_content/helpers/route.php';
jimport('joomla.application.component.model');
JModel::addIncludePath(JPATH_SITE.'/components/com_content/models');
abstract class modOtMiniNewsHelper
{
public static function getList(&$params)
{
// Get the dbo
$db = JFactory::getDbo();
// Get an instance of the generic articles model
$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$app = JFactory::getApplication();
$appParams = $app->getParams();
$model->setState('params', $appParams);
// Set the filters based on the module params
$model->setState('list.start', 0);
$model->setState('list.limit', (int) $params->get('count', 3));
$model->setState('filter.published', 1);
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$model->setState('filter.access', $access);
// Category filter
$model->setState('filter.category_id', $params->get('catid', array()));
// User filter
$userId = JFactory::getUser()->get('id');
switch ($params->get('user_id'))
{
case 'by_me':
$model->setState('filter.author_id', (int) $userId);
break;
case 'not_me':
$model->setState('filter.author_id', $userId);
$model->setState('filter.author_id.include', false);
break;
case '0':
break;
default:
$model->setState('filter.author_id', (int) $params->get('user_id'));
break;
}
// Filter by language
$model->setState('filter.language',$app->getLanguageFilter());
// Featured switch
switch ($params->get('show_featured'))
{
case '1':
$model->setState('filter.featured', 'only');
break;
case '0':
$model->setState('filter.featured', 'hide');
break;
default:
$model->setState('filter.featured', 'show');
break;
}
// Set ordering
$order_map = array(
'm_dsc' => 'a.modified DESC, a.created',
'mc_dsc' => 'CASE WHEN (a.modified = '.$db->quote($db->getNullDate()).') THEN a.created ELSE a.modified END',
'c_dsc' => 'a.created',
'p_dsc' => 'a.publish_up',
'h_dsc' => 'a.hits',
);
$ordering = JArrayHelper::getValue($order_map, $params->get('ordering'), 'a.publish_up');
$dir = 'DESC';
$model->setState('list.ordering', $ordering);
$model->setState('list.direction', $dir);
$items = $model->getItems();
foreach ($items as &$item) {
$item->slug = $item->id.':'.$item->alias;
$item->catslug = $item->catid.':'.$item->category_alias;
if ($access || in_array($item->access, $authorised))
{
// We know that user has the privilege to view the article
$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
}
else {
$item->link = JRoute::_('index.php?option=com_user&view=login');
}
//$item->title = htmlspecialchars( $item->title );
$item->content= strip_tags(preg_replace('/<img([^>]+)>/i',"",$item->introtext));
$item->content = substr($item->content, 0, $params->get('introtext_limit'));
preg_match_all('/img.+src="([^"]+)"/i', $item->introtext, $matches);
if(empty($matches[1][0])){
$item->images="";
}else{
$item->images= $matches [1] [0];
}
//Show thumbnails
if($params->get('showthumbnails')==1){
if($item->images == ""){
$item->thumbnail = '<img src="'.$params->get('directory_thumbdefault').'" width="'.$params->get('thumbwidth').'" height="'.$params->get('thumbheight').'" alt="'.$item->title.'" />';
}else{
$item->thumbnail = '<img src="' .$item->images.'" width="'.$params->get('thumbwidth').'" height="'.$params->get('thumbheight').'" alt="'.$item->title.'" />' ; //show images
}
}
$item->created_date = $item->created;
}
return $items;
}
}
All this code creates an array used by
default.php
defined('_JEXEC') or die;
?>
<div class="ot_news">
<div class="ot_news_i">
<?php
$count = 0;
foreach ($list as $item) : ?>
<?php $count++; ?>
<div class="ot_items <?php echo ($params->get('count') == $count)?'last-item':''; ?>">
<!-- Show thumbnails -->
<?php if($params->get('showthumbnails') == 1){?>
<div class="ot_thumbs" style="width:<?php echo $params->get('thumbwidth')?>px; height:<?php echo $params->get('thumbheight')?>px;">
<?php if($params->get('enablelinkthumb') == 1) {?>
<?php echo $item->thumbnail ;?>
<?php } else { ?>
<?php echo $item->thumbnail?>
<?php }?>
</div>
<?php } else { ?>
<?php echo ''; ?>
<?php } ?>
<!-- End -->
<!-- Show Titles -->
<div class="ot_articles">
<?php if($params->get('showtitle') == 1) { ?>
<div class="ot_title">
<?php if($params->get('enablelinktitle') == 1) { ?>
<?php echo $item->title; ?>
<?php }else{?>
<span class="title"><?php echo $item->title; ?></span>
<?php }?>
</div>
<?php } ?>
<!-- Show Created Date -->
<?php
if ($params->get('show_date') == 1) {
echo '<p class="createddate"><span class="ot_date">';
$date = $item->created_date;
echo JHTML::_('date', $date, $params->get( 'date_format' ));
echo '</span></p>';
}
?>
<!-- Show Content -->
<div class="ot_content"><?php echo $item->content; ?></div>
<!-- Show Readmore -->
<?php if($params->get('readmore') == 1) {?>
<div class="ot_readmore"><?php echo JText::_('READMORE') ?></div>
<?php }else {?>
<?php echo ''; ?>
<?php } ?>
</div>
</div>
<div class="spaces"></div>
<?php endforeach; ?>
</div>
</div>
<div class="ot-mini-news"><?php echo JText::_('ABOUT_OT_MINI_NEWS'); ?></div>
that just uses a for each to show the items with their photos links and descriptions.
So as you can see i have seriously no clue where to add the Pagination code, and i suspect they even use some part of it for the display (i saw a getlist function in the helper.php file.
Any help would be much appreciated.
http://docs.joomla.org/Using_JPagination_in_your_component This is a highly useful document for this - even though this is for a module and the wiki page is using it for a component.
$db =& JFactory::getDBO();
$lim = $mainframe->getUserStateFromRequest("$option.limit", 'limit', 14, 'int'); //I guess getUserStateFromRequest is for session or different reasons
$lim0 = JRequest::getVar('limitstart', 0, '', 'int');
$db->setQuery('SELECT SQL_CALC_FOUND_ROWS x, y, z FROM jos_content WHERE x',$lim0, $lim);
$rL=&$db->loadAssocList();
if (empty($rL)) {$jAp->enqueueMessage($db->getErrorMsg(),'error'); return;}
else {
////Here the beauty starts
$db->setQuery('SELECT FOUND_ROWS();'); //no reloading the query! Just asking for total without limit
jimport('joomla.html.pagination');
$pageNav = new JPagination( $db->loadResult(), $lim0, $lim );
foreach($rL as $r) {
//your display code here
}
echo $pageNav->getListFooter( ); //Displays a nice footer
You can see in their code that whilst they do use the db result, that the pagination doesn't 'depend' on the query. Only the results which come from it. So for the $db->loadResult() for example you can just use a php count forumla to see how many rows there are in the array being produced by the module. In your case counting the number of $items.
The foreach command is still as you have it as well. With just the foreach($rL as $r) just corresponding to the existing foreach($items as $item). So the fact you don't have the database query as you see - shouldn't actually be an issue!
So the code you want will be something like:
global $option; //If Joomla 1.5
global $mainframe; //If Joomla 2.5
$option = JRequest::getCmd('option') //If Joomla 2.5
$mainframe = JFactory::getApplication(); //If Joomla 2.5
$lim = $mainframe->getUserStateFromRequest("$option.limit", 'limit', 14, 'int'); //I guess getUserStateFromRequest is for session or different reasons
$lim0 = JRequest::getVar('limitstart', 0, '', 'int');
if (empty($items)) {
$app->enqueueMessage($db->getErrorMsg(),'error');
return;
} else {
jimport('joomla.html.pagination');
$pageNav = new JPagination( count($list), $lim0, $lim );
foreach($list as $item) {
//wrap in your code here that you had in the foreach already
}
echo $pageNav->getListFooter( ); //Displays a nice footer
Make sure you remove one of the top two lines depending on whether you're using Joomla 1.5 or 2.5 but that should work.