Yii2 : validate if at least one checkbox is selected - yii2

I have multiple Music releases for a user for which he wants to create a promo, on the promo create form we have all the releases listed and I am using a form model for creating the promo where I define all rules for my several inputs in the promo form model.
I want to check if at-least one release is selected by the user when saving the form but it is not working as the checkboxes are created dynamically.
my form code for that field
foreach ($releaseInfo as $releases) {
if (!is_null($releases->releaseSongs)) {
echo "<fieldset><legend>" . \yii\helpers\Html::activeCheckbox($model, 'selected_releases[]', ['id' => 'release_' . $releases->id, 'onclick' => '$("#songs_' . $releases->id . '").toggle()', 'label' => false]) . " " . $releases->name . "</legend>";
foreach ($releases->releaseSongs as $k => $v) {
echo "<div id='songs_" . $releases->id . "' style='display:none'>";
echo "<div>";
echo $v->song->name;
echo "</div>";
echo "</div>";
}
}
}
echo "</fieldset>";
my rule in model
['selected_releases', 'required', 'on' => ['catalog', 'catalog_update'], 'requiredValue' => 1,
'when' => function ($model) {return ($model->scenario == self::SCENARIO_CATALOG_BASED || $model->scenario == self::SCENARIO_CATALOG_BASED_UPDATE);},
'whenClient' => 'function(attribute,value){return ("' . $this->scenario . '"=="' . self::SCENARIO_CATALOG_BASED . '" || "' . $this->scenario . '"=="' . self::SCENARIO_CATALOG_BASED_UPDATE . '")}',
'message' => 'You must select atleast one release',
]
when i submit my form the posted input variable looks like this
[selected_releases] => Array(
[0] => 0
[1] => 0
)
the requiredValue in the rule does not work because the selected_releases is an array of values it always says that
You must select atleast one release
how shoule i use the requiredValue parameter option for rules in a way that it checks for atleast one slection of the checkbox
OR
do i have to make a custom validation method an call it when validating

i used custom validation method for this purpose , my validation rule looks like following
['selected_releases', 'checkreleaseSelection'
, 'on' => ['catalog', 'catalog_update'],
'when' => function ($model) {return ($model->scenario == self::SCENARIO_CATALOG_BASED || $model->scenario == self::SCENARIO_CATALOG_BASED_UPDATE);},
'whenClient' => 'function(attribute,value){return ("' . $this->scenario . '"=="' . self::SCENARIO_CATALOG_BASED . '" || "' . $this->scenario . '"=="' . self::SCENARIO_CATALOG_BASED_UPDATE . '")}',
]
Custom method
public function checkreleaseSelection()
{
$error = true;
foreach ($this->selected_releases as $selection) {
if ($selection) {
$error = false;
}
}
if ($error) {
$this->addError('selected_releases', 'You must select atleast one of your releases to continue');
}
};

Related

Unable to open file for reading [filename.pdf] yii2 swiftmailer

I am trying to send an email with attachment when I used var_dump($filename)it returns the filename and gettype($filename) it returns string. but when I am trying to send an attachment it still returns Unable to open file for reading [filename.pdf] even if $file_attachment was looped I tried to change UploadedFile::getInstancesByName('file_attachment'); to UploadedFile::getInstanceByName('file_attachment'); but nothing happened. Please help me.
This is my controller
if(Yii::$app->request->isPost){
$email = Yii::$app->request->post('email');
$message = Yii::$app->request->post('message');
$file_attachment = UploadedFile::getInstancesByName('file_attachment');
if($file_attachment){
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message);
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach($filename);
}
//$mail->send();
//echo gettype($filename);
// var_dump($filename);
$mail->send();
}else{
$mail = Yii::$app->mailer->compose()
->setFrom(['myemail#gmail.com' => 'My Email'])
->setTo($email)
->setSubject('My Subject')
->setHtmlBody($message)
->send();
}
}
This is the view
<?php
echo FileInput::widget([
'name' => 'file_attachment',
'attribute' => 'file_attachment',
'options' => ['multiple' => true]
]);
?>
The baseName property of yii\web\UploadedFile contains the original filename but the file is not present on the server under its original filename. You need to use tempName property that contains path to the uploaded file on server.
Your for each cycle that attaches files to mail should look like:
foreach ($file_attachment as $file) {
$filename = $file->baseName. '.' . $file->extension;
$mail->attach(
$file->tempName,
['fileName' => $filename]
);
}
It might also be a good idea to check hasError property of yii\web\UploadedFile before attempting to attach file to see if the upload was successful.
Also make sure that you've set 'enctype' => 'multipart/form-data' in you form options when you are not using ActiveForm with ActiveField::fileInput() otherwise the files might not be uploaded.

How to display data in multiple lines in one cell using excel export in laravel

I have a nayjest table, and I want to export the data in this table into an excel file.
But I am having trouble formatting the data in their cells.
For example, I want to export this data in laravel nayjest table as-is in the excel file,
But after exporting, this is what is being displayed in the excel file,
As you can see, the data that was supposed to be in multiple lines are now in a single line.
This is the code that I currently have. I am using ExcelExport to export the data into the file,
$cfg = (new GridConfig())
...
(new FieldConfig)
->setName('S_CODE')
->setLabel('Course Code')
->setCallback(function ($val, $row) {
$stud_results = StudResult::where('SESSI', $sessi)
->where('SEMESTER', $semester)
->where('MATRIC_NO', $data->MATRIC_NO)
->get();
global $currentStudResults;
$currentStudResults = $stud_results;
$table = '<table>';
foreach ($currentStudResults as $stud_result) {
$table .= '<tr><td>'
$table .= $stud_result->S_CODE;
$table .= '</td></tr>';
}
$table = '</table>'
return $table;
})
,
...
->setComponents([
(new THead)
->setComponents([
(new OneCellRow)
->setRenderSection(RenderableRegistry::SECTION_END)
->setComponents([
new RecordsPerPage,
new ColumnsHider,
(new ExcelExport)
->setFileName(strtoupper('Student Course History') . ' - ' . date('Y-m-d')),
(new HtmlTag)
->setContent('<span class="glyphicon glyphicon-refresh"></span> Filter')
->setTagName('button')
->setRenderSection(RenderableRegistry::SECTION_END)
->setAttributes([
'class' => 'btn btn-success btn-sm',
]),
]),
(new ColumnHeadersRow),
(new FiltersRow),
]),
(new TFoot),
]);
This is the expected result to be in the excel file,
Is there any way to reformat the excel file to follow my output?
I think you can achieve that by adding some line brakes here:
foreach ($currentStudResults as $stud_result) {
$table .= '<tr><td>'
$table .= $stud_result->S_CODE.'</br>';
$table .= '</td></tr>';
}

How to parse php inside html

I tried to parse the php query into html, but on the html page it shows array.
My query looks like this: $comments = get_comments( array('post_id' => $post->ID, 'status' => 'approve') );
I tried to print it on the html page using this: $html .= $comments;
As you can see from the examples.
And as Tom J Nowell commented, you need to loop through each comment and append the comment to the $html.
$args = array(
'status' => 'approve',
'post_id' => $post->ID,
);
$comments = get_comments( $args );
foreach ( $comments as $comment ) :
$html .= $comment->comment_author . '<br />' . $comment->comment_content . '<br />';
endforeach;

Yii2.0 pagination issue second page not working

How do I do a pagination? I have a search form and a search button which passes in a date range. The first page is working successfully, however when I click on the second page, it shows everything. How do I pass the date range into my pagination?
EDIT:
Below is my ReportSearch.php (model)
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 5,
//'params' => array('search' => 'true', 'from_dt'=>$stockmovement_summary_from_sales_date, 'to_dt'=> $stockmovement_summary_to_sales_date),
],
]);
$dataProvider->setSort([
'defaultOrder' => [
'd_item.desc_e_tx' => SORT_ASC,
],
'attributes' => [
'd_item.desc_e_tx'
]
]);
return $dataProvider;
}
Below is my controller:
$searchModel = new ReportSearch();
$dataProvider = $searchModel->searchStockMovementSummary($stockmovement_summary_from_sales_date, $stockmovement_summary_to_sales_date);
return $this->render('stockmovementreportsummary', [
'search' => 'true',
'dataProvider' => $dataProvider,
'from_dt' => $stockmovement_summary_from_sales_date,
'to_dt' => $stockmovement_summary_to_sales_date,
'model' => $searchModel,
]);
Below is my index.php
$reports = $dataProvider->getModels();
$i=1;
echo "<table class='table table-striped table-bordered'>";
echo "<tr><th>#</th><th>Item</th><th>Total Summary Usage Qty</th><th>Current Stock On Hand</th><th>Measurement</th></tr>";
foreach ($reports as $report) {
$item_key = $report['report_item_key'];
$item_model = Item::find()->where(['item_key' =>$item_key])->one();
$item_e_desc_tx = $item_model->desc_e_tx;
$item_c_desc_tx = $item_model->desc_c_tx;
$item_qty_no = $item_model->qty_no;
$item_measurement_tx = $item_model->measurement;
echo "<tr>";
echo "<td>" . $i++ . "</td>";
echo "<td>" . Html::a($item_key, array('stockmovementreportdetailbyitem', 'item_key' => $item_key, 'search' => 'true', 'from_dt' => $from_dt, 'to_dt'=>$to_dt)) . "<br>" . $item_e_desc_tx . "<br>" . $item_c_desc_tx ."</td>";
echo "<td>" . $report['total_summary_usage_qty'] . "</td>";
echo "<td>" . $item_qty_no . "</td>";
echo "<td>" . $item_measurement_tx . "</td>";
echo "</tr>";
}
echo "</table>";
echo \yii\widgets\LinkPager::widget([
'pagination'=>$dataProvider->pagination,
]);
GridView should be used but I do not think it will help. Do you by any chance use POST instead of GET to filter the results? If you take a look here https://github.com/yiisoft/yii2/blob/master/framework/data/Pagination.php#L257 at the createUrl function you will see that it uses getQueryParams http://www.yiiframework.com/doc-2.0/yii-web-request.html#getQueryParams() to create the query string. If you use POST then this function will not pick up the params properly hence the next page pagination will fail.
Ok, because you actually do use POST then you have to create your own pagination function that takes post into consideration. Or just use GET. You are not performing any operations to the DB you can safely use GET. It is better for everybody.
You have to edit the code in your action.
Read this documentation.
And edit $dataProvider->pagination

Magento get all orders numbers shipped as overnight between two dates

Title pretty much describes it, I just need to get all the order numbers
shipped with Overnight shipping between 6-8 to 6-12.
Help appreciated
Here is at least one way of achieving this...
$from = "2012-06-08";
$to = "2012-06-12";
$shippingMethod = "overnight_shipping";
$orderIds = Mage::getResourceModel('sales/order_shipment_collection')
->addAttributeToFilter('created_at', array(
'from' => $from,
'to' => $to,
))
->getColumnValues('order_id')
;
$incrementIds = Mage::getResourceModel('sales/order_collection')
->addAttributeToFilter('shipping_method', array('eq' => $shippingMethod))
->addAttributeToFilter('entity_id', array('in' => $orderIds))
->getColumnValues('increment_id')
;
echo "<ul>";
foreach($incrementIds as $incrementId) {
echo "<li>" . $incrementId . "</li>";
}
echo "</ul>";