Yii2 karthik editable column first row not working - yii2

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>

Related

Yii2 - Class 'mPDF' not found

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');

Yii2-Unable to send image name via client interface

I am working on Yii2. I have developed an API which will save the incoming records from the client. A client can send an image so I am saving its name and then uploading in the folder. Along with the name of the image I am also sending data with it. All the data except the image name are saved. Below is my API call.
public function actionAddnew()
{
$fp = fopen('preinstall.txt', 'w+');
fwrite($fp, file_get_contents('php://input'));
fclose($fp);
$inputs = json_decode(file_get_contents('php://input'));
return PreInstallations::saveAll($inputs);
}
The function saveAll is
public static function saveAll($inputs)
{
$coutner = 0;
$arr_status = [];
foreach ($inputs as $input) {
$s = new PreInstallations;
foreach ((array)$input as $key => $value) {
if ($key != 'image_names') {
if ($s->hasAttribute($key)) {
$s->$key = $value;
}
}
}
$user = Yii::$app->user;
if (isset($input->auth_key) && Users::find()->where(['auth_key' => $input->auth_key])->exists()) {
$user = Users::find()->where(['auth_key' => $input->auth_key])->one();
}
$s->created_by = $user->id;
if (PreInstallations::find()->where(['ref_no' => $input->ref_no])->exists()) {
$arr_status[] = ['install_id' => $input->install_id, 'status' => 2, 'messages' => "Ref # Already exists"];
continue;
}
$s->sync_date = date('Y-m-d H:i:s  ');
if ($s->save()) {
if ($s->pre_install_status == 'Pre Installed') {
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[8]);
}
$arr_status[] = ['install_id' => $input->install_id, 'status' => 1];
$coutner++;
if (isset($input->site_images_name)) {
foreach ($input->site_images_name as $img) {
$image2 = new PreInstallationImagesSite;
$image2->image_name = $img->image_name;
$image2->pre_install_id = $s->id;
$image2->save();
}
}
}
else {
$arr_status[] = ['install_id' => $input->install_id, 'status' => 0, 'messages' => $s->errors];
}
}
return ['status' => 'OK', 'details' => $arr_status, 'records_saved' => $coutner];
}
Below part of above code saves the images name
if (isset($input->site_images_name)) {
foreach ($input->site_images_name as $img) {
$image2 = new PreInstallationImagesSite;
$image2->image_name = $img->image_name;
$image2->pre_install_id = $s->id;
$image2->save();
}
}
For testing purpose API call is made from POSTMAN with below details
[{
"ref_no": "20371521444700U",
"meter_msn" :"002999001189",
"billing_msn" : "74516" ,
"latitude": "36.2703169",
"longitude": "78.178266",
"tarrif": "07",
"s_load": "07",
"customer_id" :"37010673625",
"pre_install_status": "Pre Installed",
"site_issues" : "No issue",
"install_id" : "20371521444700U_1521263491",
"created_date": "2018-03-17 10:12:12",
"consumer_name": "HDA PUMPING STATION SEVERAGE UNO.8 LATIFABAD HYD",
"consumer_address" :"HDA PUMPING STATION SEVERAGE UNO.8 LATIFABAD HYD",
"auth_key": "key",// replaced the original auth key with key
"ct_ratio": "200/5",
"ct_ratio_quantity":"4",
"cable_type":"37/83",
"cable_length":"11",
"atb_installed": "Yes",
"meter_type":"L.T.TOU",
"site_images_name":["20371521444700U_1522299780_site_1.jpg"]
}]
When I Send the request I am getting an error
{
"name": "PHP Notice",
"message": "Trying to get property of non-object",
"code": 8,
"type": "yii\\base\\ErrorException",
"file": "E:\\xampp\\htdocs\\inventory-web\\common\\models\\PreInstallations.php",
"line": 137,
"stack-trace": [
"#0 E:\\xampp\\htdocs\\inventory-web\\common\\models\\PreInstallations.php(137): yii\\base\\ErrorHandler->handleError(8, 'Trying to get p...', 'E:\\\\xampp\\\\htdocs...', 137, Array)",
"#1 E:\\xampp\\htdocs\\inventory-web\\api\\modules\\v1\\controllers\\PreinstallationController.php(36): common\\models\\PreInstallations::saveAll(Array)",
"#2 [internal function]: api\\modules\\v1\\controllers\\PreinstallationController->actionAddnew()",
"#3 E:\\xampp\\htdocs\\inventory-web\\vendor\\yiisoft\\yii2\\base\\InlineAction.php(57): call_user_func_array(Array, Array)",
"#4 E:\\xampp\\htdocs\\inventory-web\\vendor\\yiisoft\\yii2\\base\\Controller.php(156): yii\\base\\InlineAction->runWithParams(Array)",
"#5 E:\\xampp\\htdocs\\inventory-web\\vendor\\yiisoft\\yii2\\base\\Module.php(523): yii\\base\\Controller->runAction('addnew', Array)",
"#6 E:\\xampp\\htdocs\\inventory-web\\vendor\\yiisoft\\yii2\\web\\Application.php(102): yii\\base\\Module->runAction('v1/preinstallat...', Array)",
"#7 E:\\xampp\\htdocs\\inventory-web\\vendor\\yiisoft\\yii2\\base\\Application.php(380): yii\\web\\Application->handleRequest(Object(yii\\web\\Request))",
"#8 E:\\xampp\\htdocs\\inventory-web\\api\\web\\index.php(35): yii\\base\\Application->run()",
"#9 {main}"
]
}
The line 137 is $image2->image_name = $img->image_name;.
The Image model is
public function rules()
{
return [
[['pre_install_id'], 'required'],
[['pre_install_id', 'image_upload_flag'], 'integer'],
[['image_name'], 'string', 'max' => 255],
[['pre_install_id'], 'exist', 'skipOnError' => true, 'targetClass' => PreInstallations::className(), 'targetAttribute' => ['pre_install_id' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'pre_install_id' => 'Pre Install ID',
'image_name' => 'Image Name',
'image_upload_flag' => 'Image Upload Flag',
];
}
I must be missing something that I don't know. Any help would be highly appreciated.

Symfony3 Forms–obtain Form with choices, default data etc. as JSON

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.

yii2 How to transfer post data from one view to two?

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.

yii2 : make SerialColumn a link

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.