Yii2 ListView does not iterate over results - view

My code:
Generating data data provider
$result = Yii::$app->db->createCommand($sql)->queryAll();
$data_provider = new \yii\data\ArrayDataProvider([
'allModels' => $result,
'key' => 'part_id',
'pagination' => [
'pageSize' => 15,
],
]);
View:
ListView::widget([
'dataProvider' => $data_provider,
'layout' => '{items}',
'options' => [
'class' => 'list-view',
'id' => 'search_results'
],
'itemView' => '_result',
]);
And _result :
DetailView::widget([
'model' => $model,
'attributes' => [
'part_id',
],
])
Result:
Part Id 1
Part Id 1
Part Id 1
[...]
Why???
If I do var_dump($data_provider) in View I get:
object(yii\data\ArrayDataProvider)[105]
public 'key' => string 'part_id' (length=7)
public 'allModels' =>
array (size=100)
0 =>
array (size=7)
'part_id' => string '1' (length=1)
[...]
1 =>
array (size=7)
'part_id' => string '2' (length=1)
[...]
2 =>
array (size=7)
'part_id' => string '3' (length=1)
[...]
[...]
What am I doing wrong?

Related

How to update data in database using import excel laravel if any data exist

how to update data in database with import excel if data exist just update, and if not exist just save. i am using laravel 5.8 and maatwebsite 2.1
this is my controller :
$request->validate([
'file' => 'required|mimes:csv,xls,xlsx',
'divisi' => 'required',
'file_type' => 'required'
]);
$path = $request->file('file')->getRealPath();
$data = Excel::load($path)->first();
$divisi = $request->input('divisi');
$file_type = $request->input('file_type');
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$arr[] = [
'product_id' => $value->product_id,
'upc' => $value->upc,
'desc_a' => $value->desc_a,
'name' => $value->name,
'category' => $value->category,
'desc_b' => $value->desc_b,
'desc_c' => $value->desc_c,
'desc_d' => $value->desc_d,
'desc_e' => $value->desc_e,
'desc_f' => $value->desc_f,
'desc_g' => $value->desc_g,
'desc_h' => $value->desc_h,
'fixel_id' => $value->fixel_id,
'x' => $value->x,
'cost' => $value->cost,
'price' => $value->price,
'reg_movement' => $value->reg_movement,
'total_facings' => $value->total_facings,
'total_units' => $value->total_units,
'days_of_supply' => $value->days_of_supply,
'desc_i' => $value->desc_i,
'kode_lokasi' => $value->kode_lokasi,
'created_by' => Auth::user()->id,
'updated_by' => Auth::user()->id,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
'divisi' => $divisi,
'file_type' => $file_type];
}
if(!empty($arr)){
Planogram::updateOrCreate($arr);
} }
from this code my data always multiply with same record.
thank you
Done, just change to this
if($data->count()){
foreach ($data as $key => $value) {
$getsku = PlanogramTemp::updateOrCreate([
'desc_b' => $value->desc_b,
'desc_e' => $value->desc_e
],[
'product_id' => $value->product_id,
'upc' => $value->upc,
'desc_a' => $value->desc_a,
'name' => $value->name,
'category' => $value->category,
'desc_b' => $value->desc_b,
'desc_c' => $value->desc_c,
'desc_d' => $value->desc_d,
'desc_e' => $value->desc_e,
'desc_f' => $value->desc_f,
'desc_g' => $value->desc_g,
'desc_h' => $value->desc_h,
'fixel_id' => $value->fixel_id,
'x' => $value->x,
'cost' => $value->cost,
'price' => $value->price,
'reg_movement' => $value->reg_movement,
'total_facings' => $value->total_facings,
'total_units' => $value->total_units,
'days_of_supply' => $value->days_of_supply,
'desc_i' => $value->desc_i,
'kode_lokasi' => $value->kode_lokasi,
'created_by' => Auth::user()->id,
'updated_by' => Auth::user()->id,
'divisi' => $divisi,
'file_type' => $file_type]);
}

How can I do store multidimensional array base on name in Laravel collection?

In image you can see name and I want to store on base of name
Array index 0 & 2 have the same name. And I want to store same name in one array
Like This:
Josue Koepp DDS => {
id=>2,
item_name=>"Domenic Labadie"
},
{
id=>0,
item_name=>"Prof. Jakayla Willms"
}
}
You can use groupBy()
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->toArray();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
In your case:
$lists = $lists->groupBy('name')->toArray();

Importing excel has an error of "Illegal string offset" in my controller

I'm trying to import an excel to my database table 'users' but it has an error saying Illegal string offset "email". I tried deleting the "email" then it says that Illegal string offset "username" now. Is it really the error in controller? Or maybe the reason is that i also have a repository.
This is my code for the controller
public function userImport()
{
if( Input::file('file_import') ) {
$path = Input::file('file_import')->getRealPath();
$inserts = [];
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
}
});
}
if (!empty($inserts)) {
DB::table('users')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}
return back();
}
As per your dumped $rows, it looks like that you don't need another foreach inside another foreach, modify your code.
// readability purpose
$rows = $reader->toArray();
foreach ($rows as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
$rows already represents each row, so you should probably rename it to $row.

Yii2, elasticsearch. How to assign my _id as primaryKey

i'm newbie so I hope you can help me.
I have yii2 and i need to implement elasticSearch(ES).
All set up.
I made standart model and standart CRUD. Just a few changes to implement ES like
use yii\elasticsearch\ActiveRecord;
But I have a problem with getting _id in my view/index.php
to get _id in view.php i made
$model->_id = $model->primaryKey;
But how I can fix it with DataProvider in index.php?
my attributes
public function attributes()
{
return [
'_id',
'first_name',
'last_name',
'email',
'created',
'brand',
'product',
'qty',
'sum'
];
}
My rules
public function rules()
{
return [
[['first_name', 'last_name', 'email', 'created',
'brand', 'product', 'qty', 'sum'
],
'safe'],
[['qty'], 'integer'],
[['sum'], 'double'],
['email', 'email'],
];
}
I think it should work like with MongoDB, but it doesn't.
if I want to delete or view or update the data being on index.php I can se only such links w/o id
http://yii2.dev/index.php?r=elastic%2Fdelete&id=
Pls help
P.S.
Here is a var_dump
array (size=5)
0 =>
object(frontend\models\Elastic)[67]
private '_id' (yii\elasticsearch\ActiveRecord) => string 'AVreA6SUvBgWLKxTzUZn' (length=20)
private '_score' (yii\elasticsearch\ActiveRecord) => float 1
private '_version' (yii\elasticsearch\ActiveRecord) => null
private '_highlight' (yii\elasticsearch\ActiveRecord) => null
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=8)
'created' => string '2017-03-12' (length=10)
'first_name' => string 'Luka' (length=4)
'last_name' => string 'Signori' (length=7)
'email' => string 'l.signori#gmail.com' (length=19)
'brand' => string 'Apple' (length=5)
'product' => string 'iPad' (length=4)
'qty' => string '35' (length=2)
'sum' => string '600.00' (length=6)
private '_oldAttributes' (yii\db\BaseActiveRecord) =>
array (size=8)
'created' => string '2017-03-12' (length=10)
'first_name' => string 'Luka' (length=4)
'last_name' => string 'Signori' (length=7)
'email' => string 'l.signori#gmail.com' (length=19)
'brand' => string 'Apple' (length=5)
'product' => string 'iPad' (length=4)
'qty' => string '35' (length=2)
'sum' => string '600.00' (length=6)
private '_related' (yii\db\BaseActiveRecord) =>
array (size=0)
empty
private '_errors' (yii\base\Model) => null
private '_validators' (yii\base\Model) => null
private '_scenario' (yii\base\Model) => string 'default' (length=7)
private '_events' (yii\base\Component) =>
array (size=0)
empty
private '_behaviors' (yii\base\Component) =>
array (size=0)
empty
you can set.good luck
$dataProvider = new ActiveDataProvider([
'query' => $query,
'key' => ['your primaryKey']
'sort' => [
'defaultOrder' => ['datetime'=>SORT_DESC]
],
]);

CakePHP: validation( ) fails

My validation fails, so my test for this message throws an ValidationException every time.
"Not all fields are filled out correct". Why? Analoguosly, it works for users (another method).
MODEL:
public $validate = array(
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Name can not be empty',
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This name is already used.',
),
),
'address' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Address can not be empty',
),
...
public function saveNewInstitution($institutionData, $userId) {
$institutionData[$this->alias]['is_active'] = 1;
$institutionData[$this->alias]['user_id'] = $userId;
$this->create();
$this->set($institutionData);
if ($this->validates()) {
return $this->save();
} else {
throw new ValidationException('Not all fields are filled out correct');
}
}
TESTclass:
public function testSaveNewInstitution() {
$data = array(
'Institution' => array(
'name' => 'Spitex Staufen',
'address' => 'Hauptweg 4',
'postcode' => '1234',
'city' => 'huuh',
'phone_number' => '123 456 78 90',
'email' => 'staufen#spitex.huuh',
'comment' => '',
'institution_type_id' => 5
));
$expected = array(
'Institution' => array(
'id' => 2,
'name' => 'Spitex Staufen',
'address' => 'Hauptweg 4',
'postcode' => '1234',
'city' => 'huuh',
'phone_number' => '123 456 78 90',
'email' => 'staufen#spitex.huuh',
'comment' => '',
'is_active' => TRUE,
'user_id' => 2,
'institution_type_id' => 5
));
$result = $this->Institution->saveNewInstitution($data, 2);
$this->assertEqual($result, $expected);
}
and all the Exceptionhandling methods like this:
public function testSaveNewInstitutionExceptionName() {
$this->setExpectedException('ValidationException');
$this->Institution->saveNewInstitution($this->__nameEmpty, 2);
}
I don't know if i got it really - is your Testclass failing or is the saveNewInstitution() function making you troubles? Did you try to check if the saveNewInstitution() is working correct by hand - put some data in a form an pass it to your function?
Maybe it's just a small thing and you have an entry with id=2 in your database an you got a duplicate key exception overwritten by your own exception method testSaveNewInstitutionExceptionName().

Resources