Why is it 'id' equal to null in yii2 - yii2

controller
After being saved, the ID is equal to the null in the batchInsert
$model= new Sale();
if($model->load(Yii::$app->request->post())) {
$model->status=1;
$model->price = str_replace(",","",$model->price);
//$id = $model->id
$model->save();
$id = $model->id;
if($model->pardakht == 1) {
for($i=0;$i<$model->count;$i++) {
$data[$i][0]=Yii::$app->request->post('number_check')[$i];
$data[$i][1]=Yii::$app->request->post('price_check')[$i];
$data[$i][2]=Yii::$app->request->post('date_check')[$i];
$data[$i][3]=Yii::$id;
$data[$i][4]=Yii::$model->customer_id;
}
Yii::$app->db->creatCommand()->batchInsert('sale_check', [
'number_check',
'price_check',
'date_check',
'user_id',
'customer_id'
], $data)->execute();
}
}
var_dump($id);
$id = null ????????????

Your model has an error, to find where the problem and what attributes has error,
Change this:
$model->save();
$id = $model->id;
to
if($model->save()) {
$id = $model->id;
/** other codes ****/
}else{
var_dump($model->errors);
/** or other usage of this array result **/
}

Related

Creating actionView in yii2-dynamic form

I am working on yii2. I have created a dynamic form using wbraganca
/
yii2-dynamicform. Now I want to implement the view. In the given extension there is no procedure that has implemented a view. It just shows the action method of view. I have tried to implement but couldn't able to do it completely.
Controller Code
/**
* Finds the MdcTariffSlabs model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return MdcTariffSlabs|\yii\db\ActiveQuery
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModelSlabs($id)
{
if (($model = MdcTariffSlabs::find()->where(['t_id'=>$id])) !== null) {
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
public function actionView($id)
{
$model = $this->findModel($id);
$modelTarrifSlabs = $this->findModelSlabs($model->id);
return $this->render('view', [
'model' => $model,
'modelTarrifSlabs' => $modelTarrifSlabs,
]);
}
View
/* #var $this yii\web\View */
/* #var $model common\models\MdcTariff */
/* #var $modelTarrifSlabs \common\models\MdcTariffSlabs */
.
.
.
.
.
.
.
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
't_name',
'created_by',
'created_at',
],
]) ?>
<?= DetailView::widget([
'model' => $modelTarrifSlabs,
'attributes' => [
'id',
't_name',
'created_by',
'created_at',
],
]) ?>
After creating I am rendering my view and getting an error
Getting unknown property: yii\db\ActiveQuery::id
var_dump($modelTarrifSlabs);
exit();
The above code gives me
object(yii\db\ActiveQuery)#131 (33) { ["sql"]=> NULL ["on"]=> NULL ["joinWith"]=> NULL ["select"]=> NULL ["selectOption"]=> NULL ["distinct"]=> NULL ["from"]=> NULL ["groupBy"]=> NULL ["join"]=> NULL ["having"]=> NULL ["union"]=> NULL ["withQueries"]=> NULL ["params"]=> array(0) { } ["queryCacheDuration"]=> NULL ["queryCacheDependency"]=> NULL ["_events":"yii\base\Component":private]=> array(0) { } ["_eventWildcards":"yii\base\Component":private]=> array(0) { } ["_behaviors":"yii\base\Component":private]=> array(0) { } ["where"]=> array(1) { ["t_id"]=> int(1) } ["limit"]=> NULL ["offset"]=> NULL ["orderBy"]=> NULL ["indexBy"]=> NULL ["emulateExecution"]=> bool(false) ["modelClass"]=> string(28) "common\models\MdcTariffSlabs" ["with"]=> NULL ["asArray"]=> NULL ["multiple"]=> NULL ["primaryModel"]=> NULL ["link"]=> NULL ["via"]=> NULL ["inverseOf"]=> NULL ["viaMap":"yii\db\ActiveQuery":private]=> NULL }
I think your error is because you get an Active Query instead of Model. And that what the error says:
Getting unknown property: yii\db\ActiveQuery::id
Try this:
Change this:
protected function findModelSlabs($id)
{
if (($model = MdcTariffSlabs::find()->where(['t_id'=>$id])) !== null) { //<---- here i guess you have error
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
To this:
protected function findModelSlabs($id)
{
if (($model = MdcTariffSlabs::find()->where(['t_id'=>$id])->one()) !== null) {
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}

how to store multiple query results and iteration results in one array

I am creating one API. In that I want to show buyers info, urls for their files/ images, and count in response. I have 3 tables buyers(PK: buyers_id), filedocs(FK: buyers_id), give_credit_transaction_master(FK: buyers_id). In those tables common column is buyers_id.
CODE
public function index()
{
$filedocsObj = FileDoc::with(['relBuyers'])->where('is_active','1')->get();
//return $filedocsCount;
$info = [];
// $profile_urls=[];
// $aadhar_urls=[];
// $pan_urls=[];
// $transaction_count=[];
// $info = array();
for($i = 0; $i < count($filedocsObj); $i++){
$buyer = FileDoc::Join('buyers', 'file_docs.buyers_id', '=', 'buyers.buyers_id')
->where('file_docs.buyers_id',$filedocsObj[$i]->buyers_id)
->select(
'buyers.buyers_id',
'buyers.buyers_name',
'buyers.buyers_address',
'buyers.buyers_contact_number',
'buyers.buyers_aadhar_number',
'buyers.buyers_pan_number',
'file_docs.buyers_profile_image',
'file_docs.buyers_aadhar_file',
'file_docs.buyers_pan_file',
)
->first();
// $info = $buyer->toArray();
array_push($info, [
'info' => $buyer
]);
// $info[] = $buyer;
$existProfile = Storage::disk('local')->exists('public/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image);
if (isset($filedocsObj[$i]->buyers_profile_image) && $existProfile) {
// $profile_urls[$i] = Storage::disk('public')->url('/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image);
array_push($info, [
'profile_url' => Storage::disk('public')->url('/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image)
]);
//$info[] = Storage::disk('public')->url('/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image);
}
else
{
// $profile_urls[$i]="";
array_push($info, [
'profile_url' => ''
]);
// $info[] = "";
}
$existAadhar = Storage::disk('local')->exists('public/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file);
if (isset($filedocsObj[$i]->buyers_aadhar_file) && $existAadhar) {
//$aadhar_urls[$i] = Storage::disk('public')->url('/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file);
array_push($info, [
'aadhar_url' => Storage::disk('public')->url('/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file)
]);
// $info[] = Storage::disk('public')->url('/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file);
}
$existPan = Storage::disk('local')->exists('public/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file);
if (isset($filedocsObj[$i]->buyers_pan_file) && $existPan) {
//$pan_urls[$i] = Storage::disk('public')->url('/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file);
array_push($info, [
'pan_url' => Storage::disk('public')->url('/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file)
]);
//$info[] = Storage::disk('public')->url('/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file);
}
$buyerTransactions = GiveCreditTransactionMaster::where('buyers_id',$filedocsObj[$i]->buyers_id)->get();
array_push($info, [
'transaction_count' => count($buyerTransactions)
]);
// $transaction_count[$i] = count($buyerTransactions);
// $resultSet = array_merge($info,$profile_urls,$aadhar_urls,$pan_urls,$transaction_count);
}
return $this->sendResponse($info, 'Buyers retrieved successfully.');
// return $this->sendResponse($resultSet, 'Buyers retrieved successfully.');
// return $this->sendResponse(array("Info" => $filedocs->toArray(),"profile_path" => $profile_urls, "aadhar_urls" => $aadhar_urls, "pan_urls" => $pan_urls, "transactionCountArray" => $transactionCountArray), 'Buyers retrieved successfully.');
}
In above code, I have taken one array info in which I am pushing query result buyer , iteration result profile_url, aadhar_url, pan_url, and another query result counts transaction_count. And returning info array as response.
MY API response:
{
"success": true,
"data": [
{
"info": {
"buyers_id": 2,
"buyers_name": "uuu",
"buyers_address": "dfgfgf",
"buyers_contact_number": "8986665576",
"buyers_aadhar_number": "654654654545",
"buyers_pan_number": "tytyr43242",
"buyers_profile_image": "2_B_profile_lady_profile.png",
"buyers_aadhar_file": "2_B_aadhar_aadhar_card_image.png",
"buyers_pan_file": "2_B_pan_pan_image.jpg"
}
},
{
"profile_url": "http://localhost/storage/uploads/profile_images/2_B_profile_lady_profile.png"
},
{
"aadhar_url": "http://localhost/storage/uploads/aadhar_files/2_B_aadhar_aadhar_card_image.png"
},
{
"pan_url": "http://localhost/storage/uploads/pan_files/2_B_pan_pan_image.jpg"
},
{
"transaction_count": 2
},
{
"info": {
"buyers_id": 28,
"buyers_name": "lili",
"buyers_address": "hjkhkdfgf",
"buyers_contact_number": "7856564656",
"buyers_aadhar_number": "343435353545",
"buyers_pan_number": "trtre34343",
"buyers_profile_image": "28_B_profile_test_profile.png",
"buyers_aadhar_file": "28_B_aadhar_test_aadhar.jpg",
"buyers_pan_file": "28_B_pan_test_pan.jpg"
}
},
{
"profile_url": "http://localhost/storage/uploads/profile_images/28_B_profile_test_profile.png"
},
{
"aadhar_url": "http://localhost/storage/uploads/aadhar_files/28_B_aadhar_test_aadhar.jpg"
},
{
"pan_url": "http://localhost/storage/uploads/pan_files/28_B_pan_test_pan.jpg"
},
{
"transaction_count": 0
}
],
"message": "Buyers retrieved successfully."
}
But in above response I am getting info of particular buyer separately than profile_url, aadhar_url, pan_url, transaction_count. Also profile_url, aadhar_url, pan_url, transaction_count this are getting separately.
I want all parameters(info,profile_url, aadhar_url, pan_url, transaction_count) of one buyer should come in one {}. How can I get that type of response?
I tried a lot using array_push, array_merge etc. But not getting requied response.
Please help. Thanks in advance.
This will help you with your desired response. I have manged your function. make it try and let me know if it helps you thanks
public
function index()
{
$filedocsObj = FileDoc::with(['relBuyers'])->where('is_active', '1')->get();
//return $filedocsCount;
$info = [];
// $profile_urls=[];
// $aadhar_urls=[];
// $pan_urls=[];
// $transaction_count=[];
// $info = array();
foreach ($filedocsObj as $index => $filedocsObjInfo) {
$buyer = FileDoc::Join('buyers', 'file_docs.buyers_id', '=', 'buyers.buyers_id')
->where('file_docs.buyers_id', $filedocsObjInfo->buyers_id)
->select(
'buyers.buyers_id',
'buyers.buyers_name',
'buyers.buyers_address',
'buyers.buyers_contact_number',
'buyers.buyers_aadhar_number',
'buyers.buyers_pan_number',
'file_docs.buyers_profile_image',
'file_docs.buyers_aadhar_file',
'file_docs.buyers_pan_file',
)
->first();
// $info = $buyer->toArray();
$info[$index]['info'] = $buyer;
// $info[] = $buyer;
$existProfile = Storage::disk('local')->exists('public/uploads/profile_images/' . $filedocsObjInfo->buyers_profile_image);
if (isset($filedocsObjInfo->buyers_profile_image) && $existProfile) {
$info[$index]['profile_url'] = Storage::disk('public')->url('/uploads/profile_images/' . $filedocsObjInfo->buyers_profile_image);
} else {
$info[$index]['profile_url'] = '';
}
$existAadhar = Storage::disk('local')->exists('public/uploads/aadhar_files/' . $filedocsObjInfo->buyers_aadhar_file);
if (isset($filedocsObjInfo->buyers_aadhar_file) && $existAadhar) {
$info[$index]['aadhar_url'] = Storage::disk('public')->url('/uploads/aadhar_files/' . $filedocsObjInfo->buyers_aadhar_file);
}
$existPan = Storage::disk('local')->exists('public/uploads/pan_files/' . $filedocsObjInfo->buyers_pan_file);
if (isset($filedocsObjInfo->buyers_pan_file) && $existPan) {
$info[$index]['pan_url'] = Storage::disk('public')->url('/uploads/pan_files/' . $filedocsObjInfo->buyers_pan_file);
}
$buyerTransactions = GiveCreditTransactionMaster::where('buyers_id', $filedocsObjInfo->buyers_id)->get();
$info[$index]['transaction_count'] = count($buyerTransactions);
// $transaction_count[$i] = count($buyerTransactions);
// $resultSet = array_merge($info,$profile_urls,$aadhar_urls,$pan_urls,$transaction_count);
}
return $this->sendResponse($info, 'Buyers retrieved successfully.');
// return $this->sendResponse($resultSet, 'Buyers retrieved successfully.');
// return $this->sendResponse(array("Info" => $filedocs->toArray(),"profile_path" => $profile_urls, "aadhar_urls" => $aadhar_urls, "pan_urls" => $pan_urls, "transactionCountArray" => $transactionCountArray), 'Buyers retrieved successfully.');
}
on PHP the following solution might work.
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
Try and let me know.
When you use an array_merge try json_decode your value like above.

Activerecord cant update a row

I want update just one column of table I'm getting this error when updating a table rows:
Call to a member function load() on null
This is my action:
public function actionAddNote(){
$id = \Yii::$app->request->post('id');
$model = MainRequest::findOne($id);
if ($model->load(\Yii::$app->request->post()) && $model->validate())
{
if($model->update()){
echo "1";
}else {
print_r($model->getErrors());
}
}
return $this->renderAjax('add-extra-note',['model' => $model]);
}
My model:
class MainRequest extends ActiveRecord {
public static function tableName()
{
return "main_request";
}
public function behaviors()
{
return [
DevNotificationBehavior::className(),
];
}
public function rules() {
return [
[
['who_req',
'req_description',
'req_date',
'extra_note'
], 'safe']
];
}
The form will render properly and I can see my text but when I submit this the error occur:
<div>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'extra_note')->textInput(); ?>
<div class="form-group">
<?= Html::submitButton('save', ['class' => 'btn green']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Can anybody tell what is problem ? Thank you.
You should load the model and the use the model loaded for accessing attribute
and you should manage ythe initial situation where you d0n't have a model to update but need a model for invoke the update render form eg:
public function actionAddNote(){
$myModel = \Yii::$app->request->post();
$model = MainRequest::findOne($myModel->id);
if (isset($model)){
if ($model->load(\Yii::$app->request->post()) && $model->validate())
{
if($model->update()){
echo "1";
}else {
print_r($model->getErrors());
}
}
} else {
$model = new MainRequest();
}
return $this->renderAjax('add-extra-note',['model' => $model]);
}
Use Simple save function or updateAttributes of Yii2:
public function actionAddNote(){
$id = \Yii::$app->request->post('id');
$model = MainRequest::findOne($id);
if ($model->load(\Yii::$app->request->post()) && $model->validate())
{
if($model->**save**()){
echo "1";
}else {
print_r($model->getErrors());
}
}
return $this->renderAjax('add-extra-note',['model' => $model]);
}

YII2 Adding whenClient to a dynamic form

I have used dynamic form widget. The form fields are shown in the image below. As you can see there is a check box named cancel. What I want is if the cancel check box is clicked, It will only requires the check number and will allow the rest to be empty. Without using dynamic form I can easily implement this using when and whenClient validators since I can get exactly the name of the checkbox.
The problem here is that the dynamic form generates this kind of name series for the checkboxes...
TblDvBub[0][is_cancelled][]
TblDvBub[1][is_cancelled][]
TblDvBub[2][is_cancelled][]
I think you could extract the name of is_cancelled checkbox using 'attribute.name' from 'whenClient' => 'function(attribute, value){}' argument. console.log that 'attribute' - there must be an object with 'name' property - there you may get the number (use regex) of current TblDvBub.
By the way why do you use multiple is_cancelled[] field - doesn't it already belong to particular TblDvBub subarray?
1) In the form, you must override fieldClass
<?php $form = ActiveForm::begin([
'fieldClass' => 'backend\widgets\ActiveField'
]); ?>
2) To override the method
<?php
class ActiveField extends \yii\widgets\ActiveField
{
protected function getClientOptions()
{
$attribute = Html::getAttributeName($this->attribute);
if (!in_array($attribute, $this->model->activeAttributes(), true)) {
return [];
}
$enableClientValidation = $this->enableClientValidation || $this->enableClientValidation === null && $this->form->enableClientValidation;
$enableAjaxValidation = $this->enableAjaxValidation || $this->enableAjaxValidation === null && $this->form->enableAjaxValidation;
if ($enableClientValidation) {
$validators = [];
foreach ($this->model->getActiveValidators($attribute) as $validator) {
/* #var $validator \yii\validators\Validator */
$js = $validator->clientValidateAttribute($this->model, $attribute, $this->form->getView());
if ($validator->enableClientValidation && $js != '') {
if ($validator->whenClient !== null) {
$js = "if (({$validator->whenClient})(attribute, value, '{$this->form->id}')) { $js }";
}
$validators[] = $js;
}
}
}
if (!$enableAjaxValidation && (!$enableClientValidation || empty($validators))) {
return [];
}
$options = [];
$inputID = $this->getInputId();
$options['id'] = $inputID;
$options['name'] = $this->attribute;
$options['container'] = isset($this->selectors['container']) ? $this->selectors['container'] : ".field-$inputID";
$options['input'] = isset($this->selectors['input']) ? $this->selectors['input'] : "#$inputID";
if (isset($this->selectors['error'])) {
$options['error'] = $this->selectors['error'];
} elseif (isset($this->errorOptions['class'])) {
$options['error'] = '.' . implode('.', preg_split('/\s+/', $this->errorOptions['class'], -1, PREG_SPLIT_NO_EMPTY));
} else {
$options['error'] = isset($this->errorOptions['tag']) ? $this->errorOptions['tag'] : 'span';
}
$options['encodeError'] = !isset($this->errorOptions['encode']) || $this->errorOptions['encode'];
if ($enableAjaxValidation) {
$options['enableAjaxValidation'] = true;
}
foreach (['validateOnChange', 'validateOnBlur', 'validateOnType', 'validationDelay'] as $name) {
$options[$name] = $this->$name === null ? $this->form->$name : $this->$name;
}
if (!empty($validators)) {
$options['validate'] = new JsExpression("function (attribute, value, messages, deferred, \$form) {" . implode('', $validators) . '}');
}
// only get the options that are different from the default ones (set in yii.activeForm.js)
return array_diff_assoc($options, [
'validateOnChange' => true,
'validateOnBlur' => true,
'validateOnType' => false,
'validationDelay' => 500,
'encodeError' => true,
'error' => '.help-block',
]);
}
}
?>
3) Validation can be used
<?php
'whenClient' => "function(attribute, value, form) {
$("form# " + form + " > attribute")
}"
?>

Laravel error:: Illegal string offset 'category_name'

I'm trying to create an admin side form. Here i'm trying to select data from the database. Also i want to display it. But for some reason it's not working. Here's my controller code,
public function save()
{
if (Input::has('save'))
{
$rules = array('category_name' => 'required|min:1|max:50', 'parent_category' => 'required');
$input = Input::all();
$messages = array('category_name.required' =>'Please enter the category name.', 'category_name.min' => 'Category name must be more than 4 characters', 'category_name.max' =>'Category name must not be more than 15 characters!!!', 'parent_category.required' => 'Please Select Parent Category.',);
$validator = Validator::make($input, $rules, $messages);
if ($validator->fails())
{
return Redirect::to('admin/category/add')->withErrors($validator)->withInput($input);
}
else
{
$insert_db = CategoryModel::insert($input);
$selected_category = CategoryModel::select($input['category_name']);
}
}
}
and my CategoryModel.php is following.
public static function insert($values)
{
$insert = DB::table('add_category')->insert(array('category_name'=>$values['category_name'], 'parent_category'=>$values['parent_category']));
if(isset($insert))
{
echo 'inserted successfully';
}
else
{
echo 'Failed';
}
}
public static function select($values)
{
$insert = DB::table('add_category')->where('category_name' . '=' . $values['category_name']);
}