Displaying CSV file content in Yii Framework's CGridView - yii

I am trying to display CSV file content in CGridView, I want to display CSV file header as CGridView "Column" and its content as DataProvider. Please provide any idea to achieve this?

You can use CArrayDataProvider.
http://www.yiiframework.com/doc/api/1.1/CArrayDataProvider
$dataProvider = new CArrayDataProvider(str_getcsv(file_get_contents('file.csv')));
You can do something like this.
$file = fopen('test.csv', 'r');
$data = array();
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
$data[] = $line;
}
fclose($file);
$columns = array();
foreach ($data[0] as $key => $value) {
$columns[] = array(
'name' => $key,
'header' => $value,
);
}
$data = array_slice($data, 1);
$dataProvider = new CArrayDataProvider($data, array(
'keyField' => 0,
));
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $dataProvider,
'columns' => $columns
));
If you want to create a generic data provider for CSV, you can create a new class.
class CsvDataProvider extends CArrayDataProvider {
private $_columns = array();
public function __construct($file, $config = array()) {
$handler = fopen($file, 'r');
$data = array();
while (($line = fgetcsv($handler)) !== FALSE) {
$data[] = $line;
}
fclose($handler);
$this->_columns = array();
foreach ($data[0] as $key => $value) {
$this->_columns[] = array(
'name' => $key,
'header' => $value,
);
}
$data = array_slice($data, 1);
parent::__construct($data, array_merge($config, array(
'keyField' => 0,
)));
}
public function getColumns() {
return $this->_columns;
}
}
Then you can do something like this.
$dataProvider = new CsvDataProvider('file.csv');
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $dataProvider,
'columns' => $dataProvider->getColumns(),
));

Related

Codeigniter post data from declared variable

function index_post() {
$sql = "SELECT id_so FROM so_detail ORDER BY id_so DESC LIMIT 1";
$last_id2 = $this->db->query($sql)->result();
foreach ($last_id2 as $row) {
$last_id = $row->id_so;
}
//echo $last_id;
$data = array(
'id_so' => $this->post($last_id),
'id_product' => $this->post('id_product'),
'harga' => $this->post('harga'),
'harga_dasar'=> $this->post('harga'),
'modal' => $this->post('modal'),
'pajak' => $this->post('pajak'),
'qty' => $this->post('qty'),
'keterangan' => $this->post('keterangan'),
'create_user'=> $this->post('create_user'),
'create_time'=> $this->post('create_time'),
'update_user'=> $this->post('create_user'),
'update_time'=> $this->post('create_time'));
$insert = $this->db->insert('so_detail', $data);
if ($insert) {
$this->response($data, 200);
} else {
$this->response(array('status' => 'fail', 502));
}
}
i got a problem that the posted id_so is "null". when i echo $last_id it show correct id ex: 120. but when i call it to $this->post($last_id), it just be null..
How to post id_so with a string that already declared before ($last_id) ??
there are many array in $last_id2 variable.data will insert multiple time based on your last_id2.try this:
foreach ($last_id2 as $row) {
$data = array(
'id_so' =>$row->id_so,
'id_product' => $this->post('id_product'),
'harga' => $this->post('harga'),
'harga_dasar'=> $this->post('harga'),
'modal' => $this->post('modal'),
'pajak' => $this->post('pajak'),
'qty' => $this->post('qty'),
'keterangan' => $this->post('keterangan'),
'create_user'=> $this->post('create_user'),
'create_time'=> $this->post('create_time'),
'update_user'=> $this->post('create_user'),
'update_time'=> $this->post('create_time'));
}
$this->db->insert_batch('so_detail',$data);

Additional fields in Prestashop module - changes not displaing, parse error & class missing

I'm usually working with WP, but I need to manipulate a module blockcontactinfos on Prestashop - just simply add two more fields which will be shown on the front end, but somehow it's not working.
I have carrefully copied one of the fields, changed it everywhere but I when trying to clear the cache (in the Performance menu):
2 errors
blockcontactinfos (parse error in /modules/blockcontactinfos/blockcontactinfos.php)
blockcontactinfos (class missing in /modules/blockcontactinfos/blockcontactinfos.php)
Could anybody help me out of this? Thanks a lot in advance. Prestashop is 1.6. Fields are displayed correctly in settings, values saved, but there is the error above and I just can't force the web page to load changed template file.
blockcontactinfos.php (added the ones with _url), lines 31-141, changes marked with // KV:
<?php
if (!defined('_CAN_LOAD_FILES_'))
exit;
class Blockcontactinfos extends Module
{
protected static $contact_fields = array(
'BLOCKCONTACTINFOS_COMPANY',
'BLOCKCONTACTINFOS_ADDRESS',
'BLOCKCONTACTINFOS_ADDRESS_URL',
'BLOCKCONTACTINFOS_PHONE',
'BLOCKCONTACTINFOS_PHONE_URL',
'BLOCKCONTACTINFOS_EMAIL',
);
public function __construct()
{
$this->name = 'blockcontactinfos';
$this->author = 'PrestaShop';
$this->tab = 'front_office_features';
$this->version = '1.2.0';
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Contact information block');
$this->description = $this->l('This module will allow you to display your e-store\'s contact information in a customizable block.');
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
}
public function install()
{
Configuration::updateValue('BLOCKCONTACTINFOS_COMPANY', Configuration::get('PS_SHOP_NAME'));
Configuration::updateValue('BLOCKCONTACTINFOS_ADDRESS', trim(preg_replace('/ +/', ' ', Configuration::get('PS_SHOP_ADDR1').' '.Configuration::get('PS_SHOP_ADDR2')."\n".Configuration::get('PS_SHOP_CODE').' '.Configuration::get('PS_SHOP_CITY')."\n".Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), Configuration::get('PS_SHOP_COUNTRY_ID')))));
Configuration::updateValue('BLOCKCONTACTINFOS_ADDRESS_URL', Configuration::get('PS_SHOP_ADDRESS_URL'));
Configuration::updateValue('BLOCKCONTACTINFOS_PHONE', Configuration::get('PS_SHOP_PHONE'));
Configuration::updateValue('BLOCKCONTACTINFOS_PHONE_URL', Configuration::get('PS_SHOP_PHONE_URL'));
Configuration::updateValue('BLOCKCONTACTINFOS_EMAIL', Configuration::get('PS_SHOP_EMAIL'));
$this->_clearCache('blockcontactinfos.tpl');
return (parent::install() && $this->registerHook('header') && $this->registerHook('footer'));
}
public function uninstall()
{
foreach (Blockcontactinfos::$contact_fields as $field)
Configuration::deleteByName($field);
return (parent::uninstall());
}
public function getContent()
{
$html = '';
if (Tools::isSubmit('submitModule'))
{
foreach (Blockcontactinfos::$contact_fields as $field)
Configuration::updateValue($field, Tools::getValue($field));
$this->_clearCache('blockcontactinfos.tpl');
$html = $this->displayConfirmation($this->l('Configuration updated'));
}
return $html.$this->renderForm();
}
public function hookHeader()
{
$this->context->controller->addCSS(($this->_path).'blockcontactinfos.css', 'all');
}
public function hookFooter($params)
{
if (!$this->isCached('blockcontactinfos.tpl', $this->getCacheId()))
foreach (Blockcontactinfos::$contact_fields as $field)
$this->smarty->assign(strtolower($field), Configuration::get($field));
return $this->display(__FILE__, 'blockcontactinfos.tpl', $this->getCacheId());
}
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Company name'),
'name' => 'BLOCKCONTACTINFOS_COMPANY',
),
array(
'type' => 'textarea',
'label' => $this->l('Address'),
'name' => 'BLOCKCONTACTINFOS_ADDRESS',
),
array(
'type' => 'text',
'label' => $this->l('URL na Google mapy'),
'name' => 'BLOCKCONTACTINFOS_ADDRESS_URL',
),
array(
'type' => 'text',
'label' => $this->l('Phone number'),
'name' => 'BLOCKCONTACTINFOS_PHONE',
),
array(
'type' => 'text',
'label' => $this->l('Telefonní číslo bez mezer'),
'name' => 'BLOCKCONTACTINFOS_PHONE_URL',
),
array(
'type' => 'text',
'label' => $this->l('Email'),
'name' => 'BLOCKCONTACTINFOS_EMAIL',
),
),
'submit' => array(
'title' => $this->l('Save')
)
),
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => array(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
foreach (Blockcontactinfos::$contact_fields as $field)
$helper->tpl_vars['fields_value'][$field] = Tools::getValue($field, Configuration::get($field));
return $helper->generateForm(array($fields_form));
}
}
blockcontactinfos.tpl (added the ones with _url), lines 32-33:
{if $blockcontactinfos_address != ''}<li><pre> {$blockcontactinfos_address|escape:'html':'UTF-8'|nl2br}</pre></li>{/if}
{if $blockcontactinfos_phone != ''}<li>{l s='Tel' mod='blockcontactinfos'} {$blockcontactinfos_phone|escape:'html':'UTF-8'}</li>{/if}

Creating a PDF document from a filtered CGridView - Yii

I am trying to create a PDF from a filtered CGridView. The value will be passed via dropdown in Advanced search but the problem is that i am unable to filter the search by my pdf function.
Controller
public function actionPrint() {
$mPDF1 = Yii::app()->ePdf->mpdf('ar','A4','14','dejavusanscondensed');
$model=new Country('search');
$model->center_id = 1;// This value will be passed from dropdown
//and i want the report to be made on this
$model->unsetAttributes();
if(isset($_GET['Country']))
$model->attributes=$_GET['Country'];
$html = '';
$html .= $this->renderPartial('candidates', array('model'=>$model, 'enablePagination' => false),true);
$mPDF1->WriteHTML($html, false);
$mPDF1->Output('list.pdf','D');
}
View
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'country-grid',
'dataProvider'=>$model->search($enablePagination),
'summaryText' => '',
// 'enablePagination' => false,
'filter'=>$model,
'columns'=>array(
'name',
array(
'header'=>' Total Registered Candidates',
'value'=>'$data->itemsTotal',
),
),
));
echo CHtml::link(
'Save as PDF',
Yii::app()->createUrl('country/print'),
array('class'=>'btnPrint btn btn-danger','target'=>'_blank'));
Model
public function search($enablePagination = true)
{
$criteria->together= true;
$criteria->with=array('center');
$criteria->compare('center.name', $this->center_id, true);
..........
if ($enablePagination)
{
$pagination = array(
'pageSize' => 30,
);
}
else
{
$pagination = false;
}
return new CActiveDataProvider($model, array(
'criteria' => $criteria,
'pagination' => $pagination,
));
}
Since center_id is a foreign key the line
$criteria->compare('center.name', $this->center_id, true);
should read
$criteria->compare('center_id', $this->center_id);
You could also do the following but this adds a condition on the joined table and could lead to slower queries.
$criteria->compare('center.id', $this->center_id);

Adding CbuttonColumn to Csv Header Column array (Used in CgridView) - Yii Framework

I am trying to add Delete button to CgridView , I am displaying CgridView columns from CSV file headers . I am storing Csv columns names in array, Now i want to add one more button column to delete the record.
Here is my code,
<?php
$file = fopen('D:/xampp/htdocs/ccvv7/images/importcsv/load.csv', 'r');
$data = array();
while (($line = fgetcsv($file)) !== FALSE) {
$data[] = $line;
}
fclose($file);
$columns = array();
foreach ($data[0] as $key => $value) {
$columns[] = array(
'name' => $key,
'header' => $value,
);
}
$data = array_slice($data, 1);
$dataProvider = new CArrayDataProvider($data, array(
'keyField' => 0,
));?>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' =>'BCImported-grid',
'dataProvider' => $dataProvider,
'columns' => $columns,
)); ?>
Please look into the code, now i need to add one more button column to $columns array
Add this to $column :
array(
'class'=>'CButtonColumn',
'template'=>'{delete}',
'deleteButtonUrl'=>'Yii::app()->controller->createUrl("delete",array("id"=>$data["id"]))',
),

Kohana ORM Display Information

I'm trying to learn how to display information from two tables.
Tables:
categories {category_id, category_title}
forums {forum_id, forum_title}
categories_forums {id_category, id_forum}
Models:
class Model_Forum extends ORM {
protected $_primary_key = 'forum_id';
protected $_belongs_to = array(
'categories'=> array(
'model' => 'category',
'through' => 'categories_forums',
'far_key' => 'id_category',
'foreign_key' => 'id_forum'
),
);
}
class Model_Category extends ORM {
protected $_primary_key = 'category_id';
protected $_has_many = array(
'forums'=> array(
'model' => 'forum',
'through' => 'categories_forums',
'far_key' => 'id_forum',
'foreign_key' => 'id_category'
),
);
}
I'm unsure how to display.
So far I have the following:
$categories = ORM::factory('category');
$forums = $categories->forums->find_all();
I don't how to display category_id, category_title, forum_id, forum_title.
You can use foreach loops, like this:
$categories = ORM::factory('category');
foreach ($categories->find_all() as $category){
echo $category->category_title, ' ', $category->id;
}
The following seems to work:
$categories = ORM::factory('category')->find_all();
$view = new View('default/index');
$view->categories = $categories;
$this->response->body($view);
foreach ($categories as $category) :
echo $category->category_title;
echo $category->category_id;
foreach ($category->forums->find_all() as $forum) :
echo $forum->forum_title;
echo $forum->forum_id;
endforeach;
endforeach;