So I have website based on Laravel framework. I have table and the filter for table to filter the items - http://prntscr.com/ccht0f.
When I filter them by anything all works good, but when I change the page filtering disapers from session. http://prntscr.com/cchutt - http://prntscr.com/cchuyo. Looks like pagination destroys all sessions.
My code:
public function filters(Request $request)
{
$filter_item_acquisition_forms = [null];
$filter_collections = [null];
$filter_origin_dates = [null];
$order_by = request()->query('order_by', 'id');
$dir = request()->query('dir', 'desc');
$storage_items = StorageItem::with(
'authorClassification',
'placeClassification',
'classificationValueOrigin',
'classificationValueOriginDate',
'classificationValueItemAcquisitionForm',
'classificationValueCollection',
'classificationValuesMaterials',
'classificationValuesTechnique',
'employeeClassificationsRestorers',
'userLastUpdatedBy.employeeClassification',
'userResponsibleUser.employeeClassification',
'attachments'
);
$storage_items = $storage_items->id($request->filter_id)
->acceptanceId($request->filter_acceptance_id)
->acceptanceNumber($request->filter_acceptance_number)
->acceptanceDate($request->filter_acceptance_date)
->mainInventoryNumber($request->filter_main_inventory_number_from, $request->filter_main_inventory_number_to)
->scientificInventoryNumber($request->filter_scientific_inventory_number)
->imageInventoryNumber($request->filter_image_inventory_number)
->itemCosts($request->filter_item_costs_from, $request->filter_item_costs_to)
->originDate($request->filter_origin_date)
->updatedAt($request->filter_updated_at_from, $request->filter_updated_at_to)
->addingDate($request->filter_added_from, $request->filter_added_to)
->itemAcquisitionForm($request->filter_item_acquisition_form)
->collection($request->filter_collection)
->employee($request->filter_employee)
->isInExposition($request->filter_is_in_exposition)
->isRestored($request->filter_is_restored)
->haveAttachments($request->filter_have_attachments)
->haveNotCosts($request->filter_have_not_costs)
->searchInField($request->filter_search_in_field, $request->filter_word_or_phrase);
$storage_items = $storage_items->orderBy($order_by, $dir)->paginate(20);
foreach ($storage_items as $storage_item) {
if ($storage_item->classificationValueItemAcquisitionForm != null) {
$filter_item_acquisition_forms[$storage_item->classificationValueItemAcquisitionForm->id] = $storage_item->classificationValueItemAcquisitionForm->value;
}
if ($storage_item->classificationValueCollection != null) {
$filter_collections[$storage_item->classificationValueCollection->id] = $storage_item->classificationValueCollection->value;
}
if (!is_null($storage_item->classificationValueOriginDate)) {
$filter_origin_date[$storage_item->classificationValueOriginDate->id] = $storage_item->classificationValueOriginDate->value;
}
}
$request->flash();
return view('panel.storage_items.filters')->with([
'storage_items' => $storage_items,
'current_order_query' => compact('order_by', 'dir'),
'employees' => [null] + EmployeeClassification::lists('employee', 'id')->toArray(),
'filter_what_to_look_for' => [
'storage-items' => trans('fields.storage_items'),
'storage-item-acceptances' => trans('fields.storage_items_acceptances'),
'archive-objects' => trans('fields.archive_objects'),
'archive-documents' => trans('fields.archive_documents'),
'archive-docs-acceptance-acts' => trans('fields.archive_documents_acceptance_acts')
],
'filter_item_acquisition_forms' => $filter_item_acquisition_forms,
'filter_collections' => [null] + Classification::findOrFail(2)->classificationValues()->lists('value', 'id')->toArray(),
//'filter_collections' => $filter_collections,
'filter_origin_dates' => $filter_origin_dates,
'filter_search_in_field' => [
trans('fields.storage_items') => [
'item_name' => trans('fields.item_name'),
'author' => trans('fields.author'),
'about_the_author' => trans('fields.about_author'),
'item_description' => trans('fields.item_description'),
'content_description' => trans('fields.content_description'),
'item_history' => trans('fields.item_history'),
'branding_notes' => trans('fields.branding_notes'),
'damage_characteristics' => trans('fields.damage_characteristics'),
'published' => trans('fields.published'),
'exhibited' => trans('fields.exhibited'),
'inquiries' => trans('fields.inquiries')
],
trans_choice('fields.attachments', 0) => [
'attachment_name' => trans('fields.name'),
'attachment_description' => trans('fields.description')
]
]
]);
}
So I fixed it myself.
Solution:
I got the collection ID from request and stored it in variable.
$filter_collection = $request->filter_collection;
Passed variable to the view
->with('filter_collection', $filter_collection)
And changed my pagination to pass collection ID to next page
{{ $storage_items->appends(['filter_collection' => $filter_collection])->links() }}
Related
Working on an element-api.php file from a Craft CMS project. Has a lot of helper functions. I added a category called disciplines. I'm trying to expose the values for each entry.
Here's the whole helper function I'm working on:
// Get all projects, by date, newest first
function getAllProjects() {
$caseStudies = [];
$query = \craft\elements\Entry::find();
$query->section('caseStudies');
$query->orderBy('postDate desc');
foreach ($query->all() as $page) {
$isPublic = $page->public;
$parent = $page->getSection()->handle;
if ($isPublic) {
$serviceData = [];
foreach ($page->modules->all() as $module) {
switch ($module->type->handle) {
case 'service':
$service = $module->service->one();
if ($service) {
$serviceData[] = [
'id' => $service->service->one()->id,
'title' => $service->service->one()->title,
];
}
break;
}
}
$coverColor = [
'r' => $page->coverColor ? $page->coverColor->r : 0,
'g' => $page->coverColor ? $page->coverColor->g : 0,
'b' =>$page->coverColor ? $page->coverColor->b : 0,
];
$caseStudies[] = [
'id' => $page->id,
'title' => $page->title,
'meta' => [
'navigationColor' => $page->navigationColor->value,
'title' => $page->metaTitle ? $page->metaTitle : $page->title,
'description' => $page->metaDescription,
],
'slug' => $page->slug,
'postDate' => date("d-m-Y",$page->postDate->getTimestamp()),
'json' => UrlHelper::url("work/{$page->slug}.json"),
'parent' => $parent,
'headline' => $page->headline,
'client' => $parent === 'caseStudies' ? $page->client->one()->title : null,
'services' => $serviceData,
'discipline' => array_map(function (CategoryModel $category) {
return [
'id' => $category->id,
'title' => $category->title,
];
}, $page->discipline->find()),
'cover' => handelImages($page->cover->all()),
'coverColor' => $coverColor,
'coverVideo' => [
'source' => $page->coverVideo
]
];
}
}
return $caseStudies;
}
Everything works except in the caseStudies array I have added this line:
'discipline' => array_map(function (CategoryModel $category) {
return [
'id' => $category->id,
'title' => $category->title,
];
}, $page->discipline->find()),
which returns the error: Argument 1 passed to {closure}() must be an instance of CategoryModel, instance of craft\elements\Category given
site is at Craft 3.3.15. Element-Api plugin is 2.6.0
'dispiplines' => array_map('strval', $page->discipline->all())
This worked. Found a tag example right on the github page https://github.com/craftcms/element-api
API result:
php laravel
the article_user and article_title is repeated.
i use transformer to transform my data.
public function transform(ArticleComment $comments)
{
$articleInfo = $comments->article;
$user = UserInfo::select('real_name')->find($articleInfo->created_user_id);
return [
'article_user' => $user->real_name,
'article_title' => $articleInfo->title,
'is_evaluator' => $comments->is_evaluation,
'comment_created_user' => $comments->user,
'created_at' => $comments->created_at,
'comment_content' => $comments->content,
'replied_comment' => $comments->reply,
'replied_user' => $comments->repliedUser,
];
}
}
i want it like this
article_info:{
article_user: "",
article_title: "",
}
article_comment:{
content: "",
is_evaluator: 0,
...
}
how to optimize it ?
what should i do ?
the response
You can use simple arrays to format your response. In your case it should be:
public function transform(ArticleComment $comments)
{
$articleInfo = $comments->article;
$user = UserInfo::select('real_name')->find($articleInfo->created_user_id);
return [
'article_info' => [
'article_user' => $user->real_name,
'article_title' => $articleInfo->title
],
'article_comment' => [
'is_evaluator' => $comments->is_evaluation,
'comment_created_user' => $comments->user,
'created_at' => $comments->created_at,
'comment_content' => $comments->content,
'replied_comment' => $comments->reply,
'replied_user' => $comments->repliedUser
]
];
}
I've just started laravel and when I try to get values from database it's fine. But when I try to return the values, it's just empty. Here's the code:
public function index()
{
$collection = [];
Leg::chunk(200, function ($data) {
foreach ($data as $val) {
$collection[] = [
'fixture_id' => $val->fixture_id,
'ops_leg_id' => $val->ops_leg_id,
'designator' => $val->designator,
'operator' => $val->operator,
'flight_number' => $val->flight_number,
'dep_airport' => $val->dep_airport,
'arr_airport' => $val->arr_airport,
'ac_registration' => $val->ac_registration,
'ac_code' => $val->ac_code,
'sta_at' => $val->sta_at,
'std_at' => $val->std_at,
'ata_at' => $val->ata_at,
'atd_at' => $val->atd_at,
'deleted' => $val->deleted
];
}
});
return array($collection);
}
Edit: My output of the webpage is just [[]]
The inline function does not return anything
public function index()
{
Leg::chunk(200, function ($data) {
$collection = [];
foreach ($data as $val) {
$collection[] = [
'fixture_id' => $val->fixture_id,
'ops_leg_id' => $val->ops_leg_id,
'designator' => $val->designator,
'operator' => $val->operator,
'flight_number' => $val->flight_number,
'dep_airport' => $val->dep_airport,
'arr_airport' => $val->arr_airport,
'ac_registration' => $val->ac_registration,
'ac_code' => $val->ac_code,
'sta_at' => $val->sta_at,
'std_at' => $val->std_at,
'ata_at' => $val->ata_at,
'atd_at' => $val->atd_at,
'deleted' => $val->deleted
];
}
return array($collection);
});
}
I never used generators in PHP. I understand the way to use it :
Foreach an array to do some tasks for each value like greping a specific line into a big file to remove some caracteres..
What I need :
I need to retrieve all bands from my dabatase. Sure I have the 'limit' argument to don't exceed the PHP's memory (there're 30 000 bands..).
I have to filters values and return a new array to the client into my REST API.
What I want to know :
Is it interesting for me to create a method into a trait called 'generator' to perform the code bellow ?
In all cases, I have to create a new array to return it into my method
$bands = Models\Bands::find($bandsParameters);
$json = [];
foreach ($bands as $band) {
$followers = $band->getFollowers();
$followersArr = [];
foreach ($followers as $follower) {
$followerImage = $follower->getImage();
$followerObj = (object)[
'id' => $follower->id,
'username' => $follower->username,
'image' => $followerImage->url,
'online' => $follower->online,
'createdOn' => $follower->createdOn,
'updatedOn' => $follower->updatedOn,
'lastLogin' => $follower->lastLogin,
];
$followersArr[] = $followerObj;
}
$info = $band->getInfo($bandInfoParameters)->getFirst();
$bandObj = (object)[
'id' => $band->id,
'name' => $band->name,
'style' => $band->styles,
'country' => $band->country,
'summary' => isset($info->summary) ? $info->summary : null,
'followers' => $followersArr,
'createdOn' => $band->createdOn,
'updatedOn' => $band->updatedOn,
'authoredBy' => $band->authoredBy,
'updatedBy' => $band->updatedBy,
];
$json[] = $bandObj;
}
return ['key' => 'bands', 'value' => $json];
I want to insert data into my database. I am using codeigniter framework to build my app.
When I click on submit button,It don't give any error just reload the same page and data in not inserted in database.
Following my code to insert data into database -
public function addSale($saleDetails = array(), $items = array(), $warehouse_id)
{
foreach($items as $data){
$product_id = $data['product_id'];
$product_quantity = $data['quantity'];
$this->updateProductQuantity($product_id, $warehouse_id, $product_quantity);
}
// sale data
$saleData = array(
'reference_no' => $saleDetails['reference_no'],
'warehouse_id' => $warehouse_id,
'biller_id' => $saleDetails['biller_id'],
'biller_name' => $saleDetails['biller_name'],
'customer_id' => $saleDetails['customer_id'],
'customer_name' => $saleDetails['customer_name'],
'date' => $saleDetails['date'],
'note' => $saleDetails['note'],
'internal_note' => $saleDetails['internal_note'],
'inv_total' => $saleDetails['inv_total'],
'total_tax' => $saleDetails['total_tax'],
'total' => $saleDetails['total'],
'total_tax2' => $saleDetails['total_tax2'],
'tax_rate2_id' => $saleDetails['tax_rate2_id'],
'inv_discount' => $saleDetails['inv_discount'],
'discount_id' => $saleDetails['discount_id'],
'user' => $saleDetails['user'],
'shipping' => $saleDetails['shipping']
);
if($this->db->insert('sales', $saleData)) {
$sale_id = $this->db->insert_id();
$addOn = array('sale_id' => $sale_id);
end($addOn);
foreach ( $items as &$var ) {
$var = array_merge($addOn, $var);
}
if($this->db->insert_batch('sale_items', $items)) {
return true;
}
}
return false;
}
Based on https://ellislab.com/codeigniter/user-guide/database/examples.html , it seems to me, that you are missing a line -> $this->db->insert('sales', $saleData); . You do have it inside an if statement, but if statement will not execute it as a code, but check if it returns true.
$saleData = array(
'reference_no' => $saleDetails['reference_no'],
'warehouse_id' => $warehouse_id,
'biller_id' => $saleDetails['biller_id'],
'biller_name' => $saleDetails['biller_name'],
'customer_id' => $saleDetails['customer_id'],
'customer_name' => $saleDetails['customer_name'],
'date' => $saleDetails['date'],
'note' => $saleDetails['note'],
'internal_note' => $saleDetails['internal_note'],
'inv_total' => $saleDetails['inv_total'],
'total_tax' => $saleDetails['total_tax'],
'total' => $saleDetails['total'],
'total_tax2' => $saleDetails['total_tax2'],
'tax_rate2_id' => $saleDetails['tax_rate2_id'],
'inv_discount' => $saleDetails['inv_discount'],
'discount_id' => $saleDetails['discount_id'],
'user' => $saleDetails['user'],
'shipping' => $saleDetails['shipping']
);
$this->db->insert('sales', $saleData);
This should work. You can also check if it succeeds like this ->
return ($this->db->affected_rows() != 1) ? false : true;