In my Excel sheet has a Gender column. I want to get only "Male" entries but when importing the data via maatwebsite, my code displays all the results.
How can I filter the results properly?
$data = Excel::load($path, function ($reader){
$results = $reader->get(array('user_url','gender'=>'Male')))->take(10);
if (!empty($results)) {
foreach ($results as $val => $link) {
$userid = $link['fb_unique_id'];
print_r($userid);
}
}
}
Related
I am working on a function to find a field from any form based on the label text. I'd like to return different attributes of the field so that I can use them later.
Originally, I just needed the value of the field, so I used the work here to return the value of a field based on the label:
function itsg_get_value_by_label( $form, $entry, $label ) {
foreach ( $form['fields'] as $field ) {
$lead_key = $field->label;
if ( strToLower( $lead_key ) == strToLower( $label ) ) {
return $entry[ $field->id ];
}
}
return false;
}
I get my value by setting a variable and passing in the field label that I'm looking for:
$mobile_phone = itsg_get_value_by_label( $form, $entry, "Mobile Phone" );
Later on, as I continued to work on my solution, I found that I also needed to find those fields and return the ID. Initially, I wrote the same function and just returned the ID, but I'd like to make the solution more efficient by rewriting the function to return multiple field attributes in an array, as such:
function get_field_atts_by_label( $form, $entry, $label ) {
foreach ( $form['fields'] as $field ) {
$lead_key = $field->label;
if ( strToLower( $lead_key ) == strToLower( $label ) ) {
$field_atts = array(
'value' => $entry[ $field->id ],
'id' => $field->id,
);
return $field_atts;
}
}
return false;
}
My problem now is that I am not quite sure how to retrieve the specific attributes from my function and set them to a variable.
Well, I'll go ahead and answer my own question. Such a simple solution to this one. Had a momentary brain fart.
$mobile_phone = get_field_atts_by_label( $form, $entry, "Mobile Phone" );
$mobile_phone_id = $mobile_phone['id'];
$mobile_phone_value = $mobile_phone['value'];
I'm using matlab excel plugin for convert excel to array. My code is:-
public static function ImportExcel($table="", $path=""){
$data = array();
Excel::load($path, function ($reader) use($data) {
$data = $reader->toArray();
//here data has all excel data in array.
});
return $data; //but here it shows empty array.
}
Check my comments in code. Inside the Excel::load data has array of all data. But its scope is only inside the Excel::load. I need it outside.
The load has an internal function, thus the variables are enclosed inside that function and it also cannot access variables from outside this function, unless they are passed to the function with the use statement. In other words, $data inside the function does not reference to the $data outside it. In order to fix this you will have to add $data to the use statement like this:
public static function ImportExcel($table="", $path=""){
$data = array();
Excel::load($path, function ($reader) use($table, $data) {
$data = $reader->toArray();
//here data has all excel data in array.
});
return $data; //but here it shows empty array.
}
try this way
$data = Excel::load($path, function ($reader) use($table) {
$data = $reader->toArray();
//here data has all excel data in array.
});
otherwise create array before and after clousers
$array = [];
Excel::load($path, function ($reader) use($table, $array) {
$array = $reader->toArray();
//here data has all excel data in array.
});
third way doing like that
$results = Excel::load($path);
$data = $results->toArray();
I write an answer with more detail for another persons who wants to use Maatwebsite\Excel :
if ($request->hasFile('imported_file')){
$updateFile = $request->file('imported_file');
$path = $updateFile->getRealPath();
$fileExtension = $updateFile->getClientOriginalExtension();
$formats = ['xls', 'xlsx', 'ods', 'csv'];
if (! in_array($fileExtension, $formats)) {
return back()->with("status", 'The uploaded file format is not allowed.');
}
$data = Excel::load($path, function ($reader) {}, 'UTF-8')->get();
if (! empty($data) && $data->count()) {
$data = $data->toArray();
foreach ($data as $perData) {
// Do whatever you like on per data in your imported data
}
}
}
I have date-property in my DataObject.
How can I search by date-range in ModelAdmin?
For example: "search all items where date is more than 2007-13-01 and less than 2007-17-01"
or "search all items where date is between 2007-13-01 and 2007-17-01"
For now I can search only with GreaterTranFilter or with LessThanFilter, but not with both.
class MyObject extends DataObject {
private static $db = [
"Date" => "Date",
];
private static $summary_fields = [
"Date" => "Date",
];
private static $searchable_fields = [
"Date" => [
"field" => "DateField",
"filter" => "GreaterThanFilter",
"title" => 'Date from ...'
],
];
}
Additionally search field must use a calendar(datepicker)
DateField:
default_config:
showcalendar: true
Can you give an example how to search by date-range?
There is a WithinRangeFilter, but it's not going to get you very far if you're using configuration only. This is something you really need to implement procedurally.
Add the range filters by overloading getSearchContext(), then overload getList() and check the q request param for the date ranges, and apply them to the list.
public function getSearchContext()
{
$context = parent::getSearchContext();
$context->getFields()->push(DateField::create('q[Start]','Start'));
$context->getFields()->push(DateField::create('q[End]','End'));
return $context;
}
public function getList()
{
$list = parent::getList();
$params = $this->getRequest()->requestVar('q');
$filters = [];
if(isset($params['Start'])) {
$filters['Date:LessThanOrEqual'] = $params['Start'];
}
if(isset($params['End'])) {
$filters['Date:GreaterThanOrEqual'] = $params['End'];
}
return $list->filter($filters);
}
I'm writing a plug-in for my component. For this component I have table "#__radiocatalog_item" with columns id, name, description, and I need to lookup at column name. For this, I wrote this plugin:
<?php
defined('JPATH_BASE') or die;
require_once JPATH_ADMINISTRATOR.'/components/com_finder/helpers/indexer/adapter.php';
class PlgFinderRadioitem extends FinderIndexerAdapter
{
protected $context = 'Radioitem';
protected $extension = 'com_radiocatalog';
protected $layout = 'item';
protected $type_title = 'item';
protected $table = '#__radiocatalog_item';
protected $state_field = 'parent';
protected $autoloadLanguage = true;
protected function setup()
{
return true;
}
public function onFinderDelete($context, $table)
{
if ($context == 'com_radiocatalog.item')
{
$id = $table->id;
}
elseif ($context == 'com_finder.index')
{
$id = $table->id;
}
else
{
return true;
}
return $this->remove($id);
}
public function onFinderChangeState($context, $pks, $value)
{
if ($context == 'com_radiocatalog.item')
{
$this->itemStateChange($pks, $value);
}
if ($context == 'com_plugins.plugin' && $value === 0)
{
$this->pluginDisable($pks);
}
}
protected function index(FinderIndexerResult $item, $format = 'html')
{
if (JComponentHelper::isEnabled($this->extension) == false)
{
return;
}
$item->url = $this->getURL($item->id, 'com_radiocatalog&layout=item', $this->layout);
$item->route = 'index.php?option=com_radiocatalog&view=item&layout=item&id='.$item->id;
$item->addTaxonomy('Type', 'Radioitems');
$item->addTaxonomy('Language', $item->language);
$this->indexer->index($item);
}
protected function getListQuery($sql = null)
{
$db = JFactory::getDbo();
$sql = $sql instanceof JDatabaseQuery ? $sql : $db->getQuery(true);
$sql->select('a.id as id, a.name as title, a.description as description');
$sql->from('#__radiocatalog_item AS a');
return $sql;
}
protected function getStateQuery()
{
$sql = $this->db->getQuery(true);
$sql->select($this->db->quoteName('a.id'));
$sql->select($this->db->quoteName('a.name').' as title');
$sql->from($this->db->quoteName('#__radiocatalog_item') . ' AS a');
return $sql;
}
}
?>
After full indexing, search on the site does not work.
I was struggling with the same problem. So I enabled Joomla debugging {Global Configuration / System / Debug System = true} and tried to search for a term "myterm" using public site SmartSearch module. Then I checked the performed SQL queries. First, the term was found:
SELECT t.term, t.term_id
FROM j_finder_terms AS t
WHERE t.term = 'myterm'
AND t.phrase = 0
with ID=653 (used later):
SELECT l.link_id,m.weight AS ordering
FROM `j_finder_links` AS l
INNER JOIN `j_finder_links_terms2` AS m
ON m.link_id = l.link_id
WHERE l.access IN (1,1)
AND l.state = 1
AND (l.publish_start_date = '0000-00-00 00:00:00' OR l.publish_end_date <= '2014-01-04 17:34:00')
AND (l.publish_end_date = '0000-00-00 00:00:00' OR l.publish_end_date >= '2014-01-04 17:34:00')
AND m.term_id IN (653)
But this query didn't return any result, because j_finder_links.access and j_finder_links.state values were set to 0 instead of 1.
So my suggest you to check the queries and if you have the same problem, try to change your query from getStateQuery() method or select "1 AS access, 1 AS state" in the getListQuery() query and leave the $state_field variable unset.
I'm sorry for a vague explanation, I don't know much about how the SmartSearch work, I'm just trying to make it work somehow with my component.
my code export into excel works fine, 1 to 10 rows export if I filters rows that my code export filtered rows as my criteria. If I click to next page e.g 11 to 20 and then click on export button, export only first page 1 to 10 rows.
in my admin view export button code:
<div id='menub'><?php $this->widget('zii.widgets.CMenu', array(
'encodeLabel'=>false,
'htmlOptions'=>array(
'class'=>'actions'),
'items'=>array(
array(
'label'=>'<img align="absmiddle" alt = "'.Yii::t('internationalization','Export'). '" src = "'.Yii::app()->request->baseUrl.'/images/export.jpg" />',
//'label'=>'Export',
'url'=>array('expenses/excel'),
),
),
));
above link call to excel method in expenses controller.
code in my controller:
public function actionExcel() {
$issueDataProvider = $_SESSION['report-excel'];
$i = 0;
$data = array();
//fix column header.
//Could have used something like this - $data[]=array_keys($issueDataProvider->data[0]->attributes);.
//But that would return all attributes which i do not want
//$data[]=array_keys($issueDataProvider->data[0]->attributes);
$data[$i]['expenses_type_id'] = 'Type';
$data[$i]['amount'] = 'Amount';
$data[$i]['exp_date'] = 'Date';
$data[$i]['description'] = 'Description';
$i++;
//populate data array with the required data elements
foreach($issueDataProvider->data as $issue)
{
$data[$i]['expenses_type_id'] = $issue->expensesType->name;
$data[$i]['amount'] = $issue['amount'];
$data[$i]['exp_date'] = $issue['exp_date'];
$data[$i]['description'] = $issue['description'];
$i++;
}
Yii::import('application.extensions.phpexcel.JPhpExcel');
$xls = new JPhpExcel('UTF-8', false, 'test');
$xls->addArray($data);
$xls->generateXML('test_file');
}
I save data in
$_SESSION['report-excel']
and in my Model:
public function getSearchCriteria()
{
$criteria=new CDbCriteria;
if(!empty($this->from_date) && empty($this->to_date))
{
$criteria->condition = "exp_date >= '$this->from_date'"; // date is database date column field
}elseif(!empty($this->to_date) && empty($this->from_date))
{
$criteria->condition = "exp_date <= '$this->to_date'";
}elseif(!empty($this->to_date) && !empty($this->from_date))
{
$criteria->condition = "exp_date >= '$this->from_date' and exp_date <= '$this->to_date'";
}
$criteria->with = 'expensesType';
$criteria->join = 'LEFT JOIN expenses_type p ON t.expenses_type_id = p.id';
//s$criteria->compare('id',$this->id,true);
$criteria->compare('p.name',$this->expenses_type_id,true);
$criteria->compare('amount',$this->amount,true);
$criteria->compare('exp_date',$this->exp_date,true);
$criteria->compare('description',$this->description,true);
$criteria->order ='exp_date DESC';
return $criteria;
}
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$data = new CActiveDataProvider(get_class($this), array(
'pagination'=>array('pageSize'=> Yii::app()->user->getState('pageSize',
Yii::app()->params['defaultPageSize']),),
'criteria'=>$this->getSearchCriteria(),
));
$_SESSION['report-excel']=$data;
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$this->getSearchCriteria(),
));
every thing is works fine but on pagination.
kindly help.
CActiveDataProvider holds a set of items(all).So when you call actionExcel() the $page param is lost. So when you do actionAdmin() in your controller or search() in your model save your $_GET['page'] to an other session value. then set it when you do actionExcel().
$_GET['page'] = $_SESSION['your_session_page_value'];
Hope this helps
Best Regards