Active Admin: how to set filter label dynamically - activeadmin

I tried this:
filter :something, :label => lambda{ condition?(current_active_admin_user) ? "option1" : "option2" }
but it does not work. But the same lambda code works for the menu.

Try
if current_active_admin_user
filter :something, :label => "option1"
else
filter :something, :label => "option2"
end
Good luck.

Related

How to use Excel::Writer::XLSX to create a table where inserting a row copies a column's formula?

So, in Excel, I can manually create create the following (I'm having it display the formula in column C):
Then, I can select A:1 through C3, choose Insert -> Table, and press OK on the Create Table dialog to make my data into a table, unchecking the Filter Button box:
Then, when I right-click on row 3 and select Insert, I get a new row 3, with column C's formula copied correctly.
My problem is I can't seem to generate an Excel file with Perl using Excel::Writer::XLSX that can create a table where inserting a row will cause the formula to be copied. It ends up being blank, like this:
Below is my code. Any insights would be much appreciated.
#!/usr/bin/env perl
use strict;
use warnings;
use Excel::Writer::XLSX;
my $filePath = shift;
my $workbook = Excel::Writer::XLSX->new( $filePath );
my $worksheet = $workbook->add_worksheet( 'Metadata' );
my #data = ( [1,2,"=SUM(A2:B2)"], [3,4,"=SUM(A3:B3)"], [5,6,"=SUM(A4:B4)"] );
my $rowCount = (scalar #data) + 1;
$worksheet->add_table(
"A1:C$rowCount",
{
data => \#data,
name => 'Table1',
style => 'Table Style Medium 2',
autofilter => 0,
header_row => 1,
columns => [
{ header => 'Value 1' },
{ header => 'Value 2' },
{ header => 'Sum' },
]
}
);
$workbook->close();
Excel tables are so underused... it's good to see someone with an appreciation for what they have to offer, and kudos to the module author for adding table support.
A couple of things... if you want a table-based formula, declare it in the formula property of the table column. This will cause it to be copied to any new rows that are created.
{ header => 'Title', formula => '=1+2' }
Secondly, there may be a way to do this via a R1C1 syntax (Excel supports it, but I don't know if Excel::Writer::XLSX does), but I find when you are referencing other columns in the table, it's easiest to do it based on the table column rather than the cell reference -- this is one of big advantages of Excel tables over standard ranges.
formula => '=[#[Header A]]*[#[Header B]]'
The impacted code should look as follows:
my #data = ( [1,2], [3,4], [5,6] );
my $rowCount = (scalar #data) + 1;
$worksheet->add_table(
"A1:C$rowCount",
{
data => \#data,
name => 'Table1',
style => 'Table Style Medium 2',
autofilter => 0,
header_row => 1,
columns => [
{ header => 'Value 1' },
{ header => 'Value 2' },
{ header => 'Sum',
formula => '=SUM([#[Value 1]]:[#[Value 2]])'
},
]
}
);
When you open the spreadsheet and add a row, I think you will get the behavior you desire.

Perl TK multiple commands on a single button

I would like to do is to have a button to close my window (button_window), but also call a function (user_info):
my $btn = $main -> Button (-text => 'Start',
-command => sub {$button_window -> destroy},
-command => \&user_info)
-> pack ();
its executing only the last command
thanks in advance
The sub can take any number of calls to other subs.
my $btn = $main->Button(
-text => 'Start',
-command => sub {
user_info();
# do something else...
$button_window->destroy;
},
)->pack();
It's executing only the last command because a hash parameter can have only one '-command' key, so is overwritten.

ActiveAdmin 'show' layout not same as edit / new

I have customized the form for new/edit to use two column layout for the form fields.
The customization uses formtastic.
Shouldn't the same layout display for "show" by default? Instead I get the activeadmin default one field per row display.
How do I get to display the same layout in "show" as my form (new/edit) pages?
By default the show page has its own layout, so you have to use some css to arrange the inputs, or you can override this method:
https://github.com/activeadmin/activeadmin/blob/master/lib/active_admin/views/components/attributes_table.rb#L22-L43
#collection.each_slice(2) do |records|
td do
content_for(record[0], block || title)
end
td do
content_for(record[1], block || title)
end
end
Or create a new one, and use this in the show block:
module ActiveAdmin
module Views
class AttributesTable < ActiveAdmin::Component
builder_method :attributes_table_for
def row_with_two_fields(*args, &block)
title = args[0]
options = args.extract_options!
classes = [:row]
if options[:class]
classes << options[:class]
elsif title.present?
classes << "row-#{title.to_s.parameterize('_')}"
end
options[:class] = classes.join(' ')
#table << tr(options) do
th do
header_content_for(title)
end
#collection.each_slice(2) do |records|
td do
content_for(record[0], block || title)
end
td do
content_for(record[1], block || title)
end
end
end
end
end
end
Or something similar... I haven't tried it.
I ended up doing the CSS hack
show do
panel "Mandatory Details" do
attributes_table_for contract do
row :account, :class => "column1"
row :customer, :class => "column2"
end
end
panel "Dates And Financials" do
attributes_table_for contract do
row :start_date, :class => "column1"
row :current_end_date, :class => "column2"
row :end_date_w_options, :class => "column1"
end
end

Excel is stripping leading 0's from CSV files

It believe that Excel is stripping leading 0s. I was told that updating the column format to text during the export will fix this and to modify Excel output (coming from "ProofAndTracking actionIpromoteuAutomation" file, yet I can't find this file or how to access where the excel formatting code is generated).
I've never worked with Excel. I tried this, but it seems to be a local fix:
http://excelribbon.tips.net/T010262_Handling_Leading_Zeros_in_CSV_Files.html
Could someone point me in the right direction to start?
I've researched these answers How to stop the leading 0's from being stripped off when exporting to excel from a datatable? and Export Excel : Avoid stripping the leading zeros
Thanks in advance!
Here is the function I believe is causing the problem, but not sure yet how to format columns to text here. /*
* format and send order and tracking info (via Excel spreadsheet) for the day for ipromoteu (150837)
*/
public function actionIpromoteuAutomation() {
$ordersGroup1 = $this->getIpromoteuProof();
$ordersGroup2 = $this->getIpromoteuProofHistory();
$orders = array_merge($ordersGroup1, $ordersGroup2);
$fileName = 'Hit Promo Order Tracking ' . date('m-d-Y');
$this->_export($orders, $fileName);
$fileName = $fileName . '.xls';
$toIPROMOTEU = array(//email to be sent to HR when request is submitted
'body' => 'Attached, please find the Excel spreadsheet containing'
. ' order details for orders on ' . date('m/d/Y') . '.',
'from_email' => 'donotreply#hitpromo.net',
'from_name' => 'Hit Promotional Products',
'subject' => 'Order Tracking Information - ' . date('m/d/Y'),
'to_emails' => 'orders#ipromoteu.com',
'attachments' => array(array('path' => Yii::app()->basePath . '/../tmp/' . $fileName, 'filename' => $fileName)),
);
Hit::email((object) $toIPROMOTEU);
$this->logForDeveloper('Order records sent to iPromoteU for '. date('m/d/Y'));
}
private function _export($data, $fileName, $format = 'excel', $output = false) {
// get a reference to the path of PHPExcel classes
$phpExcelPath = Yii::getPathOfAlias('ext.phpexcel');
// Turn off our yii library autoload
spl_autoload_unregister(array('YiiBase', 'autoload'));
include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
if ($format == 'excel') {
// Set properties
$objPHPExcel->getProperties()->setCreator(Yii::app()->user->name)
->setLastModifiedBy(Yii::app()->user->name)
->setTitle('Order Tracking Report');
}
$styleArray = array(
'font' => array(
'bold' => true,
'underline' => true,
)
);
$objPHPExcel->setActiveSheetIndex(0);
$sheet = $objPHPExcel->getActiveSheet();
for ($rowCounter = 0; $rowCounter < sizeof($data); $rowCounter++) {
$sheet->getStyle("A" . ($rowCounter + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$sheet->getStyle("B" . ($rowCounter + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$sheet->getStyle("C" . ($rowCounter + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$sheet->setCellValue("A" . ($rowCounter + 1), date('m/d/Y', strtotime($data[$rowCounter]['date'])));
//$sheet->setCellValue("A".($rowCounter+1), $data[$rowCounter]['date']);
if ($data[$rowCounter]['fedex_tracking'] != '')
$sheet->setCellValue("B" . ($rowCounter + 1), $data[$rowCounter]['fedex_tracking']);
else
$sheet->setCellValue("B" . ($rowCounter + 1), $data[$rowCounter]['other_tracking']);
$sheet->setCellValue("C" . ($rowCounter + 1), $data[$rowCounter]['sales_order_number']);
$sheet->getStyle("B" . ($rowCounter + 1))->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
}
$sheet->setCellValue("A1", "DATE")
->setCellValue("B1", "TRACKING")
->setCellValue("C1", "PO NUMBER")
->getStyle("A1:C1")->applyFromArray($styleArray);
////Set the column widths
$sheet->getColumnDimension("A")->setWidth(25);
$sheet->getColumnDimension("B")->setWidth(25);
$sheet->getColumnDimension("C")->setWidth(25);
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Order Tracking Report');
// Set active sheet index to the first sheet,
// so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
$fileName = $fileName . ($format == 'excel' ? '.xls' : '.csv');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$path = Yii::app()->basePath . '/../tmp/' . $fileName;
$objWriter->save($path);
// Once we have finished using the library, give back the
// power to Yii...
spl_autoload_register(array('YiiBase', 'autoload'));
}
public function getIpromoteuProof() {
$date = date('Ymd');
$db2params = Yii::app()->params['db2params'];
$db = Zend_Db::factory('Db2', $db2params);
$select = $db->select()
->from(
// table
array('t' => 'WBPIPRAE'),
// columns
array(
'sales_order_number' => 'TRIM(WAESPO#)',
),
// schema
$db2params['schemas']['hitdta'])
->joinLeft(
// table
array('f' => 'MFD1MD'), 'CONCAT(TRIM(WAEORD#),RIGHT(TRIM(MDORDR),3))=TRIM(MDORDR)',
// columns
array(
'fedex_tracking' => 'TRIM(MDFTRK)',
'other_tracking' => 'TRIM(MDFBRC)',
'date' => 'TRIM(MDUPDT)',
),
// schema
$db2params['schemas']['varfil'])
->where("MDUPDT = '" . $date . "'")
->where("WAEIVKY='150837'")
->order('sales_order_number')
->distinct(true);
$stmt = $db->query($select);
$orders = $stmt->fetchAll();
return $orders;
}
OK, Excel can create the csv columns as text but the issue is with the import.
When Excel opens csv files it 'helpfully' converts anything that looks like a number to a number, stripping leading zero's.
First make sure Excel is exporting it as it should, open the file in a text editor and check the leading zero is present.
You will probably have to change how the file is imported. Instead of them just double clicking the csv file, they need to run through the data import wizard:
Import 'From Text'
Select Delimited
Make sure comma is ticked
Select column as text
This should resolve the problem on the other side.
Another alternative is to add a single apostrophe ' before the numbers, however if they use macros/software to interact with the file this might break that.
Edit
After looking at the PHP code (I can't test) you might be able to change the line:
$sheet->getStyle("B" . ($rowCounter + 1))->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
To:
$sheet->getStyle("B" . ($rowCounter + 1))->getNumberFormat()->setFormatCode('000000000000'); // With however many zero's you need to keep
This however may still get removed when you export as it's still technically a number and formatting will be removed.

How do I stop ReSharper from placing "x => new" on a new line?

I know this is a fairly small detail, but for some reason it's incredibly annoying to me and I cannot figure out how to correct it (I've looked at the "Line Breaks and Wrapping" options).
Here's how I like this code formatted:
var reps = ctx.Commissions
.GroupBy(x => x.SalesRep)
.Select(x => new
{
x.Key.UserID,
Name = x.Key.FirstName + " " + x.Key.LastName
})
.ToList();
ReSharper, though, likes to format it as
var reps = ctx.Commissions
.GroupBy(x => x.SalesRep)
.Select(
x => new
{
x.Key.UserID,
Name = x.Key.FirstName + " " + x.Key.LastName
})
.ToList();
Any ideas as to how I can stop ReSharper from doing this?
Thank you,
Andrew
It looks like you should disable Prefer wrap after '(' in invocation option in Code Editing -> C# -> Formatting Style -> Line Breaks and Wrapping section.

Resources