Retrieve online data and generate and xml output of it - windows

The project requires to grep online data and generate an xml file of it. This is how the output should be:
<!DOCTYPE MetaIssue SYSTEM "http://schema.highwire.org/public/toc/MetaIssue.pubids.dtd">
<MetaIssue volume="306" issue="1">
<Provider>Cadmus</Provider>
<IssueDate>January 1, 2014</IssueDate>
<PageRange>C1-C76</PageRange>
<TOC>
<TocSection>
<Heading>Editorial Focus</Heading>
<DOI>10.1152/ajpcell.00342.2013</DOI>
</TocSection>
<TocSection>
<Heading>Review</Heading>
<DOI>10.1152/ajpcell.00281.2013</DOI>
</TocSection>
<TocSection>
<Heading>CALL FOR PAPERS | Stem Cell Physiology and Pathophysiology</Heading>
<DOI>10.1152/ajpcell.00156.2013</DOI>
<DOI>10.1152/ajpcell.00066.2013</DOI>
</TocSection>
<TocSection>
<Heading>Articles</Heading>
<DOI>10.1152/ajpcell.00130.2013</DOI>
<DOI>10.1152/ajpcell.00047.2013</DOI>
<DOI>10.1152/ajpcell.00070.2013</DOI>
<DOI>10.1152/ajpcell.00096.2013</DOI>
</TocSection>
<TocSection>
<Heading>Corrigendum</Heading>
<DOI>10.1152/ajpcell.zh0-7419-corr.2014</DOI>
</TocSection>
</TOC>
</MetaIssue>
The output which I am getting is:
<!DOCTYPE MetaIssue SYSTEM "http://schema.highwire.org/public/toc/MetaIssue.pubids.dtd">
<MetaIssue volume="306" issue="1">
<Provider>Cadmus</Provider>
<IssueDate>January 1, 2014 </IssueDate>
<PageRange>C1-</PageRange>
<TOC>
<TocSection>
<Heading>Review</Heading>
<DOI>10.1152/ajpcell.00281.2013</DOI>
</TocSection>
<TocSection>
<Heading>CALL FOR PAPERS | Stem Cell Physiology and Pathophysiology</Heading>
<DOI>10.1152/ajpcell.00156.2013</DOI>
</TocSection>
<TocSection>
<Heading>Articles</Heading>
<DOI>10.1152/ajpcell.00130.2013</DOI>
</TocSection>
<TocSection>
<Heading>Corrigendum</Heading>
<DOI>10.1152/ajpcell.zh0-7419-corr.2014</DOI>
</TocSection>
</TOC>
</MetaIssue>
The code I tried is:
#!/usr/bin/perl
use strict;
use warnings;
use LWP::Simple;
my $path1 = $ARGV[0];
open(F6, ">meta_issue.xml");
print "Enter the URL:";
my $url = <STDIN>;
chomp $url;
print "Enter the Volume Number:";
my $vol = <STDIN>;
chomp $vol;
print "Enter the Issue Number:";
my $iss = <STDIN>;
chomp $iss;
my $website_content = get($url);
print F6 "\<\!DOCTYPE MetaIssue SYSTEM \"http://schema.highwire.org/public/toc/MetaIssue.pubids.dtd\">\n";
print F6 "<MetaIssue volume=\"$vol\" issue=\"$iss\">\n";
print F6 "<Provider>Cadmus</Provider>\n";
if ($website_content =~ m#<span class="highwire-cite-metadata-date">(.*?)</span>#s) {
#<span class="highwire-cite-metadata-date">January 1, 2014 </span>
print F6 "<IssueDate>$1</IssueDate>\n"; #<IssueDate>January 1, 2014</IssueDate>
}
if ($website_content =~ m#(<span class="label">:</span>\s?(.*?)(-(.*?))?</span>)#gs) {
#.*?(?!<span class="label">:</span>\s?(.*?)(-(.*?))?</span>)$#gs) #<PageRange>C1-C76</PageRange>
my $first = $2;
print F6 "<PageRange>$2-</PageRange>\n";
}
print F6 "<TOC>\n";
while ($website_content =~ m#<h2 id=".*?" class=".*?">(.*?)</h2>#gs) {
my $h = $1;
print F6 "<TocSection>\n";
print F6 "<Heading>$h</Heading>\n";
if ( $website_content =~ m#(.*?<p><span class="label">DOI:</span>\s?(.*?)\n?</p>\s?</span>\s?\n?</div>.*?)#gs ) {
my $doi = $1;
my $doi1 = $2;
print F6 "<DOI>$doi1</DOI>\n";
print F6 "</TocSection>\n";
}
}
print F6 "</TOC>\n</MetaIssue>\n";
Note: Each <Heading> might have one or more <DOI> values, which I am not able to retrieve
I cannot place the particular <DOI> values under that <Heading>.
I cannot retrieve the last occurrence of the digit from
<span class="label">:</span>\s?(.*?)(-(.*?))?</span>
since there are variation such as </span> c14</span> or <span> c12-c14</span>. So from here I need to grep the last digit i.e c14
I execute the code in cmd as follows;
D:\Code>Perl File name (Enter)
Enter the URl: http://ajpcell.physiology.org/content/306/1
Enter the Volume Number: 306
Enter the Issue Number: 1
UPDATE:
In the URL's :
1) http://ajpendo.physiology.org/content/283/5
2) http://ajpendo.physiology.org/content/280/1
The DOI is not there, so in that case, the output in place of
<DOI>$_</DOI> tag
should be
<ResId type=”publisher-id”>$volume/$issue/$first_page</ResId>
where $first_page is specific to that particular section.
I added "else{} loop" in "sub retrieve_doi()" and also in the "for{} loop" below, but not getting the desired output .
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
use HTML::Parser;
use WWW::Mechanize;
my ($date, $first_page, $last_page, #toc);
sub get_date {
my ($self, $tag, $attr) = #_;
if ('span' eq $tag
and $attr->{class}
and 'highwire-cite-metadata-date' eq $attr->{class}
and not defined $date
) {
$self->handler(text => \&next_text_to_date, 'self, text');
} elsif ('span' eq $tag
and $attr->{class}
and 'highwire-cite-metadata-pages' eq $attr->{class}
) {
if (not defined $first_page) {
$self->handler(text => \&parse_first_page, 'self, text');
} else {
$self->handler(text => \&parse_last_page, 'self, text');
}
} elsif ('span' eq $tag
and $attr->{class}
and 'highwire-cite-metadata-doi' eq $attr->{class}
) {
$self->handler(text => \&retrieve_doi, 'self, text');
} elsif ('div' eq $tag
and $attr->{class}
and $attr->{class} =~ /\bissue-toc-section\b/
) {
$self->handler(text => \&next_text_to_toc, 'self, text');
}
}
sub next_text_to_date {
my ($self, $text) = #_;
$text =~ s/^\s+|\s+$//g;
$date = $text;
$self->handler(text => undef);
}
sub parse_first_page {
my ($self, $text) = #_;
if ($text =~ /([A-Z0-9]+)(?:-[0-9A-Z]+)?/) {
$first_page = $1;
$self->handler(text => undef);
}
}
sub parse_last_page {
my ($self, $text) = #_;
if ($text =~ /(?:[A-Z0-9]+-)?([0-9A-Z]+)/) {
$last_page = $1;
$self->handler(text => undef);
}
}
sub next_text_to_toc {
my ($self, $text) = #_;
push #toc, [$text];
$self->handler(text => undef);
}
sub retrieve_doi {
my ($self, $text) = #_;
if ('DOI:' ne $text)
{
$text =~ s/^\s+|\s+$//g;
push #{ $toc[-1] }, $text;
$self->handler(text => undef);
}
else #UPDATE
{
$text =~ s/^\s+|\s+$//g;
push #{ $toc[-1] }, $text;
$self->handler(text => undef);
}
}
print STDERR 'Enter the URL: ';
chomp(my $url = <>);
my ($volume, $issue) = (split m(/), $url)[-2, -1];
my $p = 'HTML::Parser'->new( api_version => 3,
start_h => [ \&get_date, 'self, tagname, attr' ],
);
my $mech = 'WWW::Mechanize'->new(agent => 'Mozilla');
$mech->get($url);
my $contents = $mech->content;
$p->parse($contents);
$p->eof;
my $toc;
for my $section (#toc) {
$toc .= "<TocSection>\n";
$toc .= "<Heading>".shift(#$section)."</Heading>\n";
$toc .= join q(), map "<DOI>$_</DOI>\n", #$section;
$toc .= join q(), map "<ResId type=”publisher-id”>$volume/$issue/$first_page</ResId>\n", #$section; #UPDATE
$toc .= "</TocSection>\n";
}
open (F6, ">meta_issue_$issue.xml");
print F6 <<"__HTML__";
<!DOCTYPE MetaIssue SYSTEM "http://schema.highwire.org/public/toc/MetaIssue.pubids.dtd">
<MetaIssue volume="$volume" issue="$issue">
<Provider>Cadmus</Provider>
<IssueDate>$date</IssueDate>
<PageRange>$first_page-$last_page</PageRange>
<TOC>
$toc</TOC>
</MetaIssue>
__HTML__
Please let me know how to update the code to get the desired output.

Use a proper module to parse the HTML:
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
use HTML::Parser;
use WWW::Mechanize;
my ($date, $first_page, $last_page, #toc);
sub get_info {
my ($self, $tag, $attr) = #_;
if ('span' eq $tag
and $attr->{class}
and 'highwire-cite-metadata-date' eq $attr->{class}
and not defined $date
) {
$self->handler(text => \&next_text_to_date, 'self, text');
} elsif ('span' eq $tag
and $attr->{class}
and 'highwire-cite-metadata-pages' eq $attr->{class}
) {
if (not defined $first_page) {
$self->handler(text => \&parse_first_page, 'self, text');
} else {
$self->handler(text => \&parse_last_page, 'self, text');
}
} elsif ('span' eq $tag
and $attr->{class}
and 'highwire-cite-metadata-doi' eq $attr->{class}
) {
$self->handler(text => \&retrieve_doi, 'self, text');
} elsif ('div' eq $tag
and $attr->{class}
and $attr->{class} =~ /\bissue-toc-section\b/
) {
$self->handler(text => \&next_text_to_toc, 'self, text');
}
}
sub next_text_to_date {
my ($self, $text) = #_;
$text =~ s/^\s+|\s+$//g;
$date = $text;
$self->handler(text => undef);
}
sub parse_first_page {
my ($self, $text) = #_;
if ($text =~ /([A-Z0-9]+)(?:-[0-9A-Z]+)?/) {
$first_page = $1;
$self->handler(text => undef);
}
}
sub parse_last_page {
my ($self, $text) = #_;
if ($text =~ /(?:[A-Z0-9]+-)?([0-9A-Z]+)/) {
$last_page = $1;
$self->handler(text => undef);
}
}
sub next_text_to_toc {
my ($self, $text) = #_;
push #toc, [$text];
$self->handler(text => undef);
}
sub retrieve_doi {
my ($self, $text) = #_;
if ('DOI:' ne $text) {
$text =~ s/^\s+|\s+$//g;
push #{ $toc[-1] }, $text;
$self->handler(text => undef);
}
}
print STDERR 'Enter the URL: ';
chomp(my $url = <>);
my ($volume, $issue) = (split m(/), $url)[-2, -1];
my $p = 'HTML::Parser'->new( api_version => 3,
start_h => [ \&get_info, 'self, tagname, attr' ],
);
my $mech = 'WWW::Mechanize'->new(agent => 'Mozilla');
$mech->get($url);
my $contents = $mech->content;
$p->parse($contents);
$p->eof;
my $toc;
for my $section (#toc) {
$toc .= " <TocSection>\n";
$toc .= " <Heading>" . shift(#$section) . "</Heading>\n";
$toc .= join q(), map " <DOI>$_</DOI>\n", #$section;
$toc .= " </TocSection>\n";
}
print << "__HTML__";
<!DOCTYPE MetaIssue SYSTEM "http://schema.highwire.org/public/toc/MetaIssue.pubids.dtd">
<MetaIssue volume="$volume" issue="$issue">
<Provider>Cadmus</Provider>
<IssueDate>$date</IssueDate>
<PageRange>$first_page-$last_page</PageRange>
<TOC>
$toc </TOC>
</MetaIssue>
__HTML__
Basic explanation:
HTML::Parser is callback-based, which means you give it subroutines to run when it encounters a given event in the parsed document. I use a general callback get_info, which searches for various indicators of needed information in the HTML. As we are often interested in something like "nearest text after the given span", it just registers the new callback for the text. For example, when the span with the class highwire-cite-metadata-date is found and date is not yet defined, it registers a new text handler, which would run next_text_to_date. The handler just assigns the text to the $date variable and removes the handler. I'm not sure that's the "correct" way to do it, but in this case at least, it works.
I used WWW::Mechanize in order to be able to specify the User Agent. With the default value of the much simpler LWP::Simple, I wasn't getting the whole HTML.
The output smells of a template. Switching to Template might be a good step forward.

Related

N-tier navigation in codeigniter

How to create top navigation in code-igniter?
In controller I have declare a function and call model
private function getNavigation(){
$this->load->model('xx');
$data['nav'] = $this->xx->prepareTree();
$this->load->view('index',$data);
}
And In model I have declare three functions
public function prepareTree(){
$this->db->select("`catalog_parent` as parent_id, `catalog_name` as menu_item, `catalog_id` as id, `catalog_template` as pager_id");
$this->db->from("catalog_category");
$this->db->where("`catalog_navigation` = '1'");
$this->q = $this->db->get();
$create = '';
if ($this->q->num_rows() > 0) {
$create = $this->prepareList($this->q->result_array());
}
if(!empty($create)){
return $this->category_tree($create);
} else {
return '';
}
}
private function prepareList(array $items, $pid = 0) {
$output = array();
foreach ($items as $item) {
if ((int) $item['parent_id'] == $pid) {
if ($children = $this->prepareList($items, $item['id'])) {
$item['children'] = $children;
}
$output[] = $item;
}
}
return $output;
}
private function category_tree($menu_items, $child = false){
$output = '';
if (count($menu_items)>0) {
$output .= ($child === false) ? '<ul id="main-menu" class="sm sm-blue">' : '<ul>' ;
foreach ($menu_items as $item) {
$output .= '<li>';
$output .= ''.$item['menu_item'].'';
if (isset($item['children']) && count($item['children'])) {
$output .= $this->category_tree($item['children'], true);
}
$output .= '</li>';
}
$output .= '</ul>';
}
return $output;
}
If some suggest an more easy way please suggest us.
Thanks

How to match column value between two array with foreach in CI

how could I get all data from $uData where TraineeID match with $aData using foreach in CI.
print_r($uData);
output
Array
(
[0]=>Array
(
[TraineeID]=>FMM003
[Status]=>P
[Review]=>1
[Remarks]=>Allow
)
[1]=>Array
(
[TraineeID]=>30089
[Status]=>P
[Review]=>1
[Remarks]=>Allow
)
[2]=>Array
(
[TraineeID]=>30097
[Status]=>P
[Review]=>1
[Remarks]=>countable class not start
)
)
print_r($aData);
output:
Array
(
[0]=>Array
(
[TraineeID]=>30089
)
[1]=>Array
(
[TraineeID]=>30097
)
)
just find out below solution..i hope it may help you
$i = 0;
foreach($uData as $k=>$v)
{
if($aData[$i]['TraineeID'] == $v['TraineeID'])
{
echo "match";
$output[] = $v;
}
else
{
echo "fail";
}
$i++;
}
print_r($output);
One Solution Could be Less code and easy to read :-
foreach($aData as $value )
{
$key = array_search($value["TraineeID"], array_column($uData, 'TraineeID'));//get key of matched result
if($key !== false )//check not falsy
{
echo "<pre>";
print_r($uData[$key]);
echo "</pre>";
}
}
die();
Try below code. It might help you.
$result = array();
foreach($uData as $key=> $val) {
foreach($aData as $key2 => $val2) {
if($val['TraineeID'] == $val2['TraineeID']) {
$result[] = $val;
}
}
}
echo "<pre>";
print_r($result);

Magento export categories -> import with magmi

we need to change the categories of some products and it is easier for us to do this with a csv file.
Is there a way to export the categories in magmi format?
sku,categories
"abc","cat1/cat2;;cat5/cat6/cat1"
"bgb","cat1/cat2"
or is there maybe a small tool to manage the products in categories?
Edit:
this is the current code which is displaying the category names.
But I am trying to display the category path like this:
FirstCat/Tools/Screwdriver
But it is displaying like this:
FirstCat/Screwdriver/Tools
so the categoryid is not sorted.
<?php
error_reporting(E_ALL | E_STRICT);
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
Mage::app();
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_ids');
$products->addAttributeToSelect('sku');
$products->addAttributeToFilter('status', 1);//optional for only enabled products
$products->addAttributeToFilter('visibility', 4);//optional for products only visible in catalog and search
$fp = fopen('exports.csv', 'w');
$csvHeader = array("sku", "category_ids");
fputcsv( $fp, $csvHeader,",");
foreach ($products as $product){
$sku = $product->getSku();
$i = 2;
$len = count($product->getCategoryIds());
$str = "";
foreach ($product->getCategoryIds() as $id){
$category = Mage::getModel('catalog/category')->load($id);
$name = $category->getName();
$str .= $name;
if($i <= $len) {
$str = $str .= "/";
}
$i++;
}
fputcsv($fp, array($sku, $str), ",");
}
fclose($fp);
I use this code to export out categories. You can try to run it, don't forget to modify your path to your mage/app.php:
<?php
require_once('../yourpath/app/Mage.php');
Mage::app('admin');
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::register("isSecureArea", true);
function saveData($file, $data) {
$fh = fopen($file, 'w');
foreach ($data as $dataRow) {
fputcsva($fh, $dataRow);
}
fclose($fh);
return $this;
}
function fputcsva(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {
$str = '';
$escape_char = '\\';
foreach ($fields as $value) {
if (strpos($value, $delimiter) !== false ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false) {
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i = 0; $i < $len; $i++) {
if ($value[$i] == $escape_char) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2 . $delimiter;
} else {
if (strlen($value)):
$str .= $enclosure . $value . $enclosure . $delimiter;
else:
$str .= $value . $delimiter;
endif;
}
}
$str = substr($str, 0, -1);
$str .= "\n";
return fwrite($handle, $str);
}
function geturl($connect, $value){
$id= $value;
if ($id) {
$sql = "SELECT value FROM magento.catalog_category_entity_url_key where entity_id=$id;";
$result = $connect->query($sql)->fetchObject();
} else {
return "";
}
return $result->value;
}
$modifiedarray = array();
$configpricearray=array();
$coreResource = Mage::getSingleton('core/resource');
$connect = $coreResource->getConnection('core_write');
$sql = "SELECT entity_id FROM catalog_category_entity;";
$category_row = $connect->query($sql);
$i=1;
$problematiccats=array(394,395,397,398);
$problematiccolumn=array('path','parent_id','level', 'position');
while ($row = $category_row->fetch()) {
$catid=$row['entity_id'];
echo "Category id: ".$catid.PHP_EOL;
if (in_array($catid,$problematiccats)): continue; endif;
$catsql="SELECT
ce.entity_id,
ce.parent_id,
ce.path,
ce.level,
ce.position,
ce.children_count,
ea.attribute_id,
ea.attribute_code,
CASE ea.backend_type
WHEN 'varchar' THEN ce_varchar.value
WHEN 'int' THEN IFNULL (eav_option.value,ce_int.value)
WHEN 'text' THEN ce_text.value
WHEN 'decimal' THEN ce_decimal.value
WHEN 'datetime' THEN ce_datetime.value
ELSE ea.backend_type
END AS value,
ea.is_required AS required
FROM catalog_category_entity AS ce
LEFT JOIN eav_attribute AS ea
ON ce.entity_type_id = ea.entity_type_id
LEFT JOIN catalog_category_entity_varchar AS ce_varchar
ON ce.entity_id = ce_varchar.entity_id
AND ea.attribute_id = ce_varchar.attribute_id
AND ea.backend_type = 'varchar'
AND ce_varchar.store_id = 0
LEFT JOIN catalog_category_entity_int AS ce_int
ON ce.entity_id = ce_int.entity_id
AND ea.attribute_id = ce_int.attribute_id
AND ea.backend_type = 'int'
AND ce_int.store_id = 0
LEFT JOIN catalog_category_entity_text AS ce_text
ON ce.entity_id = ce_text.entity_id
AND ea.attribute_id = ce_text.attribute_id
AND ea.backend_type = 'text'
AND ce_text.store_id = 0
LEFT JOIN catalog_category_entity_decimal AS ce_decimal
ON ce.entity_id = ce_decimal.entity_id
AND ea.attribute_id = ce_decimal.attribute_id
AND ea.backend_type = 'decimal'
AND ce_decimal.store_id = 0
LEFT JOIN catalog_category_entity_datetime AS ce_datetime
ON ce.entity_id = ce_datetime.entity_id
AND ea.attribute_id = ce_datetime.attribute_id
AND ea.backend_type = 'datetime'
LEFT JOIN eav_attribute_option_value as eav_option
ON eav_option.option_id=ce_int.value
AND eav_option.store_id=0
WHERE ce.entity_id = '$catid';";
$category_info = $connect->query($catsql);
$csvrow=array();
if ($i==1): $csvrow['entity']='entity_id';$csvrow['parent']='parent_id'; $csvrow['path']='path';
$csvrow['level']='level';
$csvrow['position']='position';
$csvrow['children_count']='children_count';endif;
while ($catrow = $category_info->fetch()) {
if (in_array($catrow['attribute_code'],$problematiccolumn)): continue; endif;
if ($i==1):
$csvrow[]=$catrow['attribute_code'];
else:
$csvrow['entity']=$catrow['entity_id'];
$csvrow['parent']=$catrow['parent_id'];
$csvrow['path']=$catrow['path'];
$csvrow['level']=$catrow['level'];
$csvrow['position']=$catrow['position'];
$csvrow['children_count']=$catrow['children_count'];
$csvrow[$catrow['attribute_code']]=($catrow['value']?$catrow['value']:"");
if ($catrow['attribute_code']=="url_key"):
if (strlen($catrow['url_key'])<3):
$csvrow['url_key']=geturl($connect,$catid);
endif;
endif;
endif;
}
$csv[]=$csvrow;
$i++;
}
$file_path = 'categoryexport.csv';
try {
saveData($file_path, $csv);
} catch (Exception $e) {
echo "[ERROR] Creating sale report file: " . $e->getMessage() . PHP_EOL;
}
In this solution the db was'n in very well state, so the url needs to grabbed separately, you can remove that part if not necessary for you.
I used this on EE 1.13.0.2
You can run it from the shell.
Now here is my solution. Its displaying the csv in the browser. After that you can reimport with magmi
<?php
error_reporting(E_ALL | E_STRICT);
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
Mage::app();
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_ids');
$products->addAttributeToSelect('sku');
$products->addAttributeToFilter('status', 1);//optional for only enabled products
$products->addAttributeToFilter('visibility', 4);//optional for products only visible in catalog and search
foreach ($products as $product){
$sku = $product->getSku();
echo $sku.",";
$i = 2;
$anzahl = count($product->getCategoryIds());
foreach ($product->getCategoryIds() as $id){
$category = Mage::getModel('catalog/category')->load($id);
$path = $category->getPath();
$ids = explode("/", $path);
$name = "";
$i2 = 2;
$anzahl2 = count($ids);
foreach($ids as $id_2) {
$category = Mage::getModel('catalog/category')->load($id_2);
$name .= $category->getName();
echo $category->getName();
if($i2 <= $anzahl2) {
$name .= "/";
echo "/";
}
$i2++;
}
if($i <= $anzahl) {
$name .= ";;";
echo ";;";
}
$i++;
}
echo "<br />";
}

yii apply sort to CActiveDataProvider

I am trying to apply sort from remember filters on my admin function i have
if (isset($_GET[ucfirst($this->id) .'_sort'])) {
$extractSort = $_GET[ucfirst($this->id) .'_sort'];
//Yii::log($extractSort);
Yii::app()->user->setState(ucfirst($this->id) .'_sort', $extractSort);
} else if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
$_GET['sort'] = Yii::app()->user->getState(ucfirst($this->id) .'_sort');
//Yii::log(Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
}
On my view I have jquery which triggers n update to get the state of a model on another function. however I am having trouble applying the sort.
$model=Yii::app()->user->getState('exportModel');
$dataProvider = $model->weeklystatus(array(),false);
if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
Yii::log(Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
$explode = explode("Yii::app()->user->getState(ucfirst($this->id) .'_sort')" , ".");
$sort = new CSort();
$sort->attributes = array(
$explode[0]=>array(
'asc'=>$explode[0]." ASC",
'desc'=>$explode[0] . " DESC",
),
'*',
);
$sort->applyOrder($model);
$dataProvider->setSort($sort);
}
My model function search
public function weeklystatus($arr = array(),$ignore = false,$showspline = false)
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
//Yii::log(var_dump($this->getPlannedPOC()));
$criteria=new CDbCriteria;
$criteria->select='*, ((CURDATE() - StartDATE) / (ProjectEndDate - StartDATE ))*100 as PlannedPOC';
if($showspline)
$criteria->addCondition('PROJECT = "' .$this->PROJECT . '"');
else
$criteria->compare('PROJECT',$this->PROJECT,true);
$stradd = '';
if(!empty($arr) && isset($arr['PROJCODE'])){
$str = '';
foreach($arr['PROJCODE'] as $value) {
$str .= "PROJCODE = '$value' || ";
}
$criteria->addCondition(substr($str, 0, -3));
$stradd .= substr($str, 0, -3);
}else
$criteria->compare('PROJCODE',$this->PROJCODE,true);
$criteria->compare('PROJID',$this->PROJID);
$criteria->mergeWith($this->dateRangeSearchCriteria('StartDATE', $this->StartDATE));
$criteria->mergeWith($this->dateRangeSearchCriteria('ProjectEndDate', $this->ProjectEndDate));
$criteria->mergeWith($this->dateRangeSearchCriteria('ActualEndDate', $this->ActualEndDate));
$criteria->mergeWith($this->dateRangeSearchCriteria('ExpectedCompletionDate', $this->ExpectedCompletionDate));
$criteria->compare('PROCESSOR',$this->PROCESSOR,true);
if(!empty($arr) && isset($arr['OFFICE'])){
$stro = '';
foreach($arr['OFFICE'] as $value) {
$stro .= "OFFICE = '$value' || ";
}
$criteria->addCondition(substr($stro, 0, -3));
$stradd .= ") AND ( ".substr($stro, 0, -3);
}else
$criteria->compare('OFFICE',$this->OFFICE,true);
$criteria->compare('DEPTCODE',$this->DEPTCODE,true);
$criteria->compare('PERCENT',$this->PERCENT,true);
$criteria->compare('PERCENTPlanned',$this->PERCENTPlanned,true);
$criteria->compare('KM',$this->KM,true);
$criteria->compare('KMPlanned',$this->KMPlanned,true);
if(!empty($arr) && isset($arr['MC'])){
$str = '';
foreach($arr['MC'] as $value) {
$str .= "MC = '$value'";
}
$criteria->addCondition($str);
if(!empty($stradd)){
$stradd = "($stradd) AND ($str) AND ";
}
}else{
$criteria->compare('MC',$this->MC,true);
}
$criteria->compare('MCSALE',$this->MCSALE);
$criteria->compare('CATEGORY',$this->CATEGORY,true);
$criteria->compare('AREA',$this->AREA,true);
$criteria->compare('COUNTRY',$this->COUNTRY,true);
$criteria->compare('PROJINFO',$this->PROJINFO,true);
$criteria->compare('quality_timing',$this->quality_timing,true);
$criteria->compare('REGION',$this->REGION,true);
$criteria->compare('ASAAREA',$this->ASAAREA,true);
$criteria->compare('LORM',$this->LORM,true);
//$ignore = false;
//echo "1st: $ignore";
if(isset($_REQUEST['ViewWebprojectreport'])){
foreach ($_REQUEST['ViewWebprojectreport'] as $key => $value) {
//print_r($key);
//print_r($value);
if($key != "StartDATE"){
if($value != "")
$ignore = true;
}
//echo "\n";
}
}
//echo "2nd: $ignore";
if(!$ignore && !$showspline){
$date = date('Y-m-d',strtotime("-2 week"));
$criteria->addCondition("StartDATE > '".Yii::app()->params['filterStartDateonReports']."-01-01' AND (PERCENT < 100 || PERCENT is null)");
//$criteria->addCondition("(PERCENT < 100 || PERCENT is null)");
//$criteria->addCondition("StartDATE < '$date' AND PERCENT <100 || StartDATE > '$date' AND PERCENT =100 ");
$criteria->addCondition("$stradd (StartDATE > '$date' AND PERCENT =100) ","OR");
/*AND (StartDATE < '$date' AND PERCENT <100)
|| (StartDATE > '$date' AND PERCENT =100) ");*/
//$criteria->addCondition("PERCENT < 100 AND StartDATE < '$date'");
//$criteria->addCondition('StartDATE > '.$date . ' AND PERCENT > -1' );
}elseif(!$showspline){
$criteria->addCondition("StartDATE > '".Yii::app()->params['filterStartDateonReports']."-01-01'");
}
/*
if(isset($_REQUEST['ViewWebprojectreport_sort'])){
$sort = explode(".",$_REQUEST['ViewWebprojectreport_sort']);
if(isset($sort[1]))
$criteria->order = $sort[0] . " " . $sort[1];
else
$criteria->order = $_REQUEST['ViewWebprojectreport_sort'];
}elseif(Yii::app()->user->hasState("ViewWebprojectreport_sort")){
Yii::log(Yii::app()->user->getState("ViewWebprojectreport_sort"));
$sort = explode(".",Yii::app()->user->getState("ViewWebprojectreport_sort"));
if(isset($sort[1]))
$criteria->order = $sort[0] . " " . $sort[1];
else
$criteria->order = Yii::app()->user->getState("ViewWebprojectreport_sort");
}
//$criteria->order = 'id desc';
*/
$sort = new CSort();
$sort->attributes = array(
'*', // preserve sorting capability
"PROJECT"=>array(
"asc"=>"PROJECT ASC",
"desc"=>"PROJECT DESC"),
'PlannedPOC'=>array(
'asc'=>'PlannedPOC ASC',
'desc'=>'PlannedPOC DESC',
),
);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
"sort"=>$sort,
'pagination'=>array(
'pageSize'=>25,
),
));
}
I have tried which does not work
if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
$explode = explode(".",Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
$name = $explode[0];
$sort = new CSort();
if(count($explode)==2){
$sort->attributes = array(
/*$name => array(
"desc"=>$name . "DESC"
),*/
'defaultOrder'=>array(
$name=> CSort::SORT_DESC
),
);
}else{
$sort->attributes = array(
/*$name => array(
"asc"=>$name . " ASC",
),*/
'defaultOrder'=>array(
$name=> CSort::SORT_ASC
),
);
}
//Yii::log(print_r($explode,true));
Yii::log(print_r($sort->attributes,true));
$sort->applyOrder($model);
$dataProvider->setSort($sort);
}
following is print out of CSort
CSort Object
(
[multiSort] =>
[modelClass] => ViewWebprojectreport
[attributes] => Array
(
)
[sortVar] => sort
[descTag] => desc
[defaultOrder] => Array
(
[PROJECT] =>
)
[route] =>
[separators] => Array
(
[0] => -
[1] => .
)
[params] =>
[_directions:CSort:private] => Array
(
[PROJECT] =>
)
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
Would you try :
$model = Yii::app()->user->getState('exportModel');
$dataProvider = $model->weeklystatus(array(),false);
if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
Yii::log(Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
$explode = explode(Yii::app()->user->getState(ucfirst($this->id) .'_sort'), ".");
$sort = new CSort();
$sort->attributes = array(
$explode[0] => array(
'asc' => $explode[1] . " ASC",
'desc' => $explode[1] . " DESC",
),
'*',
);
$sort->applyOrder($model);
$dataProvider->setSort($sort);
}

Laravel url_title helper

Is there a Laravel 4 equivalent to the codeigniter url_title() function? Or should I just copy it over?
For reference this is the codeigniter one:
function url_title($str, $separator = '-', $lowercase = FALSE)
{
if ($separator == 'dash')
{
$separator = '-';
}
else if ($separator == 'underscore')
{
$separator = '_';
}
$q_separator = preg_quote($separator);
$trans = array(
'&.+?;' => '',
'[^a-z0-9 _-]' => '',
'\s+' => $separator,
'('.$q_separator.')+' => $separator
);
$str = strip_tags($str);
foreach ($trans as $key => $val)
{
$str = preg_replace("#".$key."#i", $val, $str);
}
if ($lowercase === TRUE)
{
$str = strtolower($str);
}
return trim($str, $separator);
}
well I would vote for using something little better adjusted to your need and laravel itself https://github.com/MattHans0n/slug
how to use packages you could read on that page http://laravel.com/docs/packages

Resources