How to make the numbering result of the SerialColumn a link. Normally it generates number starting from 1. I want to make it a link. What property to use?
'columns' => [
// ...
[
'class' => 'yii\grid\SerialColumn',
// you may configure additional properties here
],
]
You can't using the actual SerialColumn class.
That being said it should be fairly easy to do with a regular column. You can define a content callback that will receive all the necessary information to do this on its own:
'columns' => [
// ...
[
'content' => function($model, $key, $index, $column) {
$globalIndex = $index + 1;
$pagination = $column->grid->dataProvider->getPagination();
if ($pagination !== false) {
$globalIndex = $pagination->getOffset() + $index + 1;
return \yii\helpers\Html::a($globalIndex, ['/route/action', 'id' => $globalIndex]);
}
],
]
Note: I haven't tested this so might not fully work out of the box.
Related
As I tried to Export to PDF from my Application, but I got this error:
I don't really know what is causing the error. I have tries several means to no avail. This is the component:
<?php
namespace backend\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use common\models\Organization;
use yii\helpers\Html;
use yii\web\NotFoundHttpException;
use mPDF;
class ExportToPdf extends Component
{
public function exportData($title='',$filename='Jkkesrms Pdf',$html=NULL)
{
$mpdf = new mPDF('utf-8', 'A4',0,'',15,15,25,16,4,9,'P');
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
$org = Organization::find()->asArray()->one();
$src = Yii::$app->urlManager->createAbsoluteUrl('site/loadimage');
$org_image=Html::img($src,['alt'=>'No Image','width'=>90, 'height'=>70]);
$org_name=$org['org_name'];
$org_add=$org['org_address_line1']."<br/>".$org['org_address_line2'];
$mpdf->SetHTMLHeader('<table style="border-bottom:1.6px solid #999998;border-top:hidden;border-left:hidden;border-right:hidden;width:100%;"><tr style="border:hidden"><td vertical-align="center" style="width:35px;border:hidden" align="left">'.$org_image.'</td><td style="border:hidden;text-align:left;color:#555555;"><b style="font-size:22px;">'.$org_name.'</b><br/><span style="font-size:10.2px">'.$org_add.'</td></tr></table>');
$stylesheet = file_get_contents('css/pdf.css'); // external css
$mpdf->WriteHTML($stylesheet,0);
$mpdf->WriteHTML('<watermarkimage src='.$src.' alpha="0.33" size="50,30"/>');
$mpdf->showWatermarkImage = true;
$arr = [
'odd' => [
'L' => [
'content' => $title,
'font-size' => 10,
'font-style' => 'B',
'font-family' => 'serif',
'color'=>'#27292b'
],
'C' => [
'content' => 'Page - {PAGENO}/{nbpg}',
'font-size' => 10,
'font-style' => 'B',
'font-family' => 'serif',
'color'=>'#27292b'
],
'R' => [
'content' => 'Printed # {DATE j-m-Y}',
'font-size' => 10,
'font-style' => 'B',
'font-family' => 'serif',
'color'=>'#27292b'
],
'line' => 1,
],
'even' => []
];
$mpdf->SetFooter($arr);
$mpdf->WriteHTML('<sethtmlpageheader name="main" page="ALL" value="on" show-this-page="1">');
$mpdf->WriteHTML($html);
$mpdf->Output($filename.'.pdf',"I");
}
}
?>
I have tried tried several means but the error persists. Please how do I resolve this error?
You need to include the full namespace with the use statement. Looking at the code it looks like that you are using this library. If that is correct then include it like
use Mpdf\Mpdf;
and then use it like below
$mpdf = new Mpdf('utf-8', 'A4',0,'',15,15,25,16,4,9,'P');
I have a Symfony3 Application setup and would like to rebuild the frontend based on React now.
One of the Entities is User and each of them can have one or more Groups so in the HTML form a list of Checkboxes appears, so the admin can select the groups attached to a User.
In UserType.php this looks like that:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', TextType::class)
->add('password', TextType::class)
->add('email', EmailType::class)
->add('groups', EntityType::class, [
'class' => Group::class,
'choice_label' => 'name',
'expanded' => true,
'multiple' => true//,
//'data' => $builder->getData()->getGroups()
]);
}
To render the Form using React, it would be extremely handy to get a JSON response which could look like that:
{
"user": {
…
"groups": [<gid 1>, …]
"groups_available": [
{
"id": <gid 1>,
"name": …
},
…
]
}
}
So that the groups array contains all the ids of the groups, the user is attached to and groups_available a list of all available groups.
Right now I am using FOSRestBundle and in the Controller it looks like that:
public function getUserformAction($id=null)
{
//if the id is null, create a new user
//else get the existing one
…
$form = $this->createForm(UserType::class, $user);
$view = $form->createView();
return $this->handleView($view);
}
How can I do that?
you should try the following code:
->add('groups', EntityType::class, array(
//if Group is in AppBundle or use the required Bundle name
'class' => 'AppBundle:Group',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.name', 'ASC')
},
'choice_label' => 'name',
'multiple' => true,
'expanded' => true,
));
You can also get a reference from here
After digging in the source and with the help of the debugger I could manage to do it in a more less robust and generic way like so:
protected function getFormStructure(Form $form)
{
return $this->iterateFormview($form->createView(), []);
}
private function iterateFormview(FormView $view, array $result)
{
foreach($view as $child) {
$vars = $child->vars;
$data = ['value' => $vars['value']];
if(isset($vars['choices'])) {
$data['choices'] = [];
foreach ($vars['choices'] as $choice) {
array_push($data['choices'], [
'label' => $choice->label,
'value' => $choice->value]);
}
}
$result[$vars['full_name']] = $data;
if(count($child) > 0) {
$result = $this->iterateFormview($child, $result);
}
}
return $result;
}
Result (as json):
{
…
"user[groups]":
{
"value": "",
"choices": [
{
"value": 100,
"label": "the name"
},
…
]
}
}
I guess this routine needs to be extended if I need to support more types… But for now this will do it.
How the pagination can be disabled in Kartik Gridview?
I am using the code like below
echo GridView::widget([
'dataProvider'=>$dataProvider,
'filterModel'=>$searchModel,
'showPageSummary'=>true,
'responsive'=>true,
'hover' => true,
'pjax'=>true,
'containerOptions'=>['style'=>'overflow: auto'], // only set when $responsive = false
'headerRowOptions'=>['class'=>'kartik-sheet-style'],
'filterRowOptions'=>['class'=>'kartik-sheet-style'],
'striped'=>true,
'hover'=>true,
'pager' => [
'options'=>['class'=>'pagination'], // set clas name used in ui list of pagination
'prevPageLabel' => 'Previous', // Set the label for the "previous" page button
'nextPageLabel' => 'Next', // Set the label for the "next" page button
'firstPageLabel'=>'First', // Set the label for the "first" page button
'lastPageLabel'=>'Last', // Set the label for the "last" page button
'nextPageCssClass'=>'next', // Set CSS class for the "next" page button
'prevPageCssClass'=>'prev', // Set CSS class for the "previous" page button
'firstPageCssClass'=>'first', // Set CSS class for the "first" page button
'lastPageCssClass'=>'last', // Set CSS class for the "last" page button
'maxButtonCount'=>10, // Set maximum number of page buttons that can be displayed
],
'panel'=>['type'=>'primary', 'heading'=>'Select Option to Publish Policy'],
'columns'=>[
['class'=>'kartik\grid\SerialColumn'],
['class' => 'kartik\grid\CheckboxColumn',
'rowSelectedClass' => GridView::TYPE_INFO,
'name' => 'id',
'contentOptions' => function ($model, $key, $index, $column){//print_r($model);
return ['username'=>$model->username];
},
'checkboxOptions' => function ($model, $key, $index, $column) {
return ['key' => $model->username, 'value' => $model->username];
},
],
],
]);
I tried adding pageSize and pagination to false, but didnt work.
No pagination mean show all the instance then you can set pageSize = 0
$dataProvider->pagination->pageSize=0;
or you can use
$dataProvider->pagination = false;
I am trying to create make a two-step form in yii2.
This is my SiteController.php
public function actionCreateCharacter()
{
$model = new Character();
var_dump(Yii::$app->request->post('Character'));
if ($model->load(Yii::$app->request->post())) {
$attributes=['imie','nazwisko','plec','wyznanie_id'];
if ($step1 = $model->validate($attributes)) {
//var_dump($step1);
// form inputs are valid, do something here
//var_dump(Yii::$app->request->post('Character');
return $this->render('createCharacterStep2', [
'model' => $model,
]);;
}
else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
}
return $this->render('createCharacter', [
'model' => $model,
]);
}
public function actionCreateCharacterStep2()
{
$model2 = new Character();
var_dump($model);
if ($model2->load(Yii::$app->request->post())) {
var_dump(Yii::$app->request->post('Character'));
if ($model2->validate()) {
// form inputs are valid, do something here
return;
}
}
/*return $this->render('createCharacter2', [
'model' => $model,
]);*/
}
... and this is my Character.php (model + attributeLabels and tableName)
public function rules()
{
return [
[['user_id', 'imie', 'nazwisko', 'plec', 'wyznanie_id', 'avatar_src', 'avatar_svg'], 'required'],
[['user_id', 'wyznanie_id'], 'integer'],
[['avatar_svg'], 'string'],
[['imie'], 'string', 'max' => 15],
[['nazwisko'], 'string', 'max' => 20],
[['plec'], 'string', 'max' => 1],
[['avatar_src'], 'string', 'max' => 30]
];
}
I have access to $_POST by Yii::$app->request->post() in createCharacter - I get imie, nazwisko, plec and wyznanie_id.
But when I send the form in step 2 I have only post data from step 2.
How can I set the post data from step1+step2?
Sorry for my english and thanks in advance.
While rendering step2 from step1 action, you can always pass additional data to controller's action. So I added "STEPONEPOSTS" post variable which contains all posts of step 1. Check below.
public function actionCreateCharacter()
{
$model = new Character();
var_dump(Yii::$app->request->post('Character'));
if ($model->load(Yii::$app->request->post())) {
$attributes=['imie','nazwisko','plec','wyznanie_id'];
if ($step1 = $model->validate($attributes)) {
//var_dump($step1);
// form inputs are valid, do something here
//var_dump(Yii::$app->request->post('Character');
return $this->render('createCharacterStep2', [
'model' => $model,
'STEPONEPOSTS' => Yii::$app->request->post(),
]);;
}
else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
}
return $this->render('createCharacter', [
'model' => $model,
]);
}
And now in step 2 view, you can get step 1 posts variable as
$STEPONEPOSTS
There is another way , if you have to table for step 1 and step 2. then save the data of step 1 first then step2 data. if you are not using two tables then you can create two form each form for each step and also create scenarios for each step according to the fields.I think this may help . You can use session also as per discussion in comments or you can use the extension array wizard but array wizard extension is not well documented , so i suggest you try my way i will help you.
I used karthik grid view and editable column to edit my grid view data. it not work for the first row of the grid view and work for the other rows when i enter value to the first row it give error like this
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
my gridview code is.
<?= GridView::widget([
'dataProvider' => $dataProvider,
'pjax' => true,
'pjaxSettings' => [
'options' => [
'id' => 'grid',
]
],
'export'=>false,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'header'=>'Sub Category',
'value'=>'item.subCategory.name',
],
'item.code',
[
'header'=>'Brand',
'value'=>'item.brand.name',
],
'item.description',
'item.pack_size',
[
'header'=>'Unit',
'value'=>'item.unit',
],
[
'header'=>'Last Price',
'value'=>function($model){
$customerId = $model->customerOrderRequest->customer_id;
$lastPurchasedPrice = Item::getLastPurchasedPrice($customerId,$model->item_id);
return '$ ' . number_format($lastPurchasedPrice, 2);
}
],
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'qty',
'editableOptions' =>
[
'formOptions' => ['action' => 'customer-order-request']
],
'header' => 'Qty',
],
[
'header'=>'Estimate',
'value'=>function($model)
{
return '123123.00';
}
],
[
'header'=>'Price (UNIT)',
'format'=>'raw',
'value'=>function($modal){
$salse_rep_id = Yii::$app->user->identity->ref_id;
$exsist_respond = Respond::find()->where(['sales_rep_id'=>$salse_rep_id,'customer_order_request_id'=>$modal->customer_order_request_id])->one();
if(!empty($exsist_respond)){
$exsist_respond_item = RespondItem::find()->where(['item_id'=>$modal->item_id,'respond_id'=>$exsist_respond->id])->one();
if(!empty($exsist_respond_item)){
$price = $exsist_respond_item->price;
} else {
$price = NULL;
}
} else {
$price = NULL;
}
if(!empty($exsist_respond) && $exsist_respond->status !="Pending"){
return $price;
}else{
return "<input type='text' class='respond-item' cor='$modal->customer_order_request_id' value='$price' item_id='$modal->item_id' />";
}
},
'visible'=>(Yii::$app->user->identity->ref_table =="sales_rep")? true:false
],
],
]); ?>
and my controller is
public function actionEditable()
{
if (Yii::$app->request->post('hasEditable'))
{
$customerItemsId = Yii::$app->request->post('editableKey');
print_r($customerItemsId);die();
$model = RequestItem::findOne($customerItemsId);
$out = Json::encode(['output'=>'', 'message'=>'']);
$post = [];
$posted = current($_POST['RequestItem']);
$post['RequestItem'] = $posted;
if ($model->load($post))
{
$model->save();
$output = '';
$out = Json::encode(['output'=>$output, 'message'=>'']);
}
echo $out;
return;
}
}
any one can help me with this problem.
Form tag nested.
a trick: Add a fake form to let browser remove it.
I meet this problem today, cause I put a form in another, they are nested.
So the browser remove the first nested form.
In the official W3C XHTML specification, Section B. "Element Prohibitions", states that:
"form must not contain other form elements."
official website
Following is sample code:
<form id="thisisMainForm">
<form id="dummy"> ->This will get Removed
<gridview id="thisisEditableGridView">
Gridviewcode.....
</gridview>
</form>
</form>