How can I create a production collection based on pricerange in Magento 2.
This is what i have so far:
<?php namespace Qxs\Related\Block;
class Related extends \Magento\Framework\View\Element\Template
{
protected $_productCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
\Magento\Catalog\Model\Product\Visibility $productVisibility,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
$this->productStatus = $productStatus;
$this->productVisibility = $productVisibility;
parent::__construct($context, $data);
}
public function getProductCollection()
{
//var_dump($this->currentProduct());
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*')
->addAttributeToFilter('special_price', ['from' => 0, 'to' => 1000])
->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
->setVisibility($this->productVisibility->getVisibleInSiteIds())
->setPageSize(5);
return $collection;
}
public function currentProduct()
{
return $this->_coreRegistry->registry('product');
}
}
?>
However, the code does not return a result including a price range. The result is totally empty but should return some products, how can I filter on price-range?
Thanks,
Range filters, to me work in this way, with addFieldToFilter. Have you tried it?
$orders = $this->_orderCollectionFactory->create()
->addAttributeToSelect('*')
->addFieldToFilter( 'created_at' , array('from' => $dateFrom, 'to' => $dateTo) )
->setOrder('created_at', 'desc' );
->setPageSize(200);
Related
I need the scale unit at my cart to show it at the frontend, but I do not get it.
I tried by a subscriber and to load the product, but I do not get the selected scale unit.
public function onLoadCart(OffcanvasCartPageLoadedEvent $event)
{
foreach ($event->getPage()->getCart()->getLineItems() as $item) {
$product = $this->productRepository->search(
new Criteria(
[
$item->getId()
]
),
$event->getContext()
)->first();
dd($product);
}
}
The term scale unit offset me a little at first. I assume you are looking for the ProductUnit. The ProductUnit is an association, and you need to add this to your criteria.
public function onLoadCart(OffcanvasCartPageLoadedEvent $event)
{
foreach ($event->getPage()->getCart()->getLineItems() as $item) {
$criteria = new Criteria(
[
$item->getId()
]
);
$criteria->addAssociation('unit');
$product = $this->productRepository->search(
$criteria,
$event->getContext()
)->first();
dd($product);
}
}
I am making change profile picture api in laravel .I want to update profile image in users table but not inserting or updating my images .Belew are my code please help me how to update user table .
fileUploadController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Detail;
use App\Profile;
use Illuminate\Support\Facades\DB;
use Session;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
class FileUploadController extends Controller
{
public function changeProfile(Request $request,$id){
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$updateuser = User::find($id);
if($file = $request->hasFile('image')) {
$file = $request->file('image');
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/files/' ;
$file->move($destinationPath,$fileName);
$updateuser->image = '/files/'.$fileName;
}
$updateuser->save();
return $updateuser;
}
}
public function changeProfile(Request $request,$id){
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$updateuser = User::find($id);
if($request->hasFile('image'))
{
$filewithext = $request->file('image')->getClientOriginalName();
$ext = $request->file('image')->getClientOriginalExtension();
$fileToStrore = $filewithext;
$path = $request->file('image')->storeAs('public/files',$fileToStrore);
$updateuser->image = $fileToStrore;
}
$updateuser->save();
return $updateuser;
}
This code works for me. I hope it will work for you too...
Good Luck..
This code is working for me.....
fileUploadController.php
public function changeProfile(Request $request,$id){
$updateuser = User::find($id);
if ($request->hasFile('image')) {
$images = $request->file('image');
$destinationPath = public_path('files');
$imageName = time().'.'.$images->getClientOriginalExtension();
$images->move($destinationPath, $imageName);
$updateuser->image= $imageName;
}else{
$updateuser->image= '';
}
$updateuser->update();
return ['message' => 'Image Uploaded Successfully'];
}
I'm trying to do something very different for a SilverStripe site: on several subpages are tables of data, and these tables each have their own set of column headers, and some tables have more columns than others. I want to avoid building out tables in the Rich Text Editor as that is prone to a lot of mistakes and it's a hassle to maintain over time.
What I would like to do is create a DataObject that allows for a nth number of columns and an nth number of corresponding rows. This way I can call a loop (or possibly two) inside the template where I have the HTML table structure already in place. The content managers have full control over which columns are in the tables for any give subpage, and they don't have to worry about maintaining the HTML table setup.
I've had a couple of ideas that don't produce the results I want without a) making the UI experience too complex for content managers and b) not being able to properly link the columns with the rows.
I have thought of creating a DataObject for Table Headers and one for Table Rows, but then I'm stumped on how to combine them in such a way that would make sense, especially since there could be any number of columns.
Would anyone have any suggestions on to approach this?
UPDATE: Ok, I have something going for the TableRowItem data object that may work, and is close to working. However, the issue is this now: How do I save the field values to the database when I am creating them basically on the fly? As it is now, the only field that saves to the database is the PDF file upload field, everything else is erased upon hitting "create."
<?php
class TruckBodyPdfTableRowItem extends DataObject {
private static $db = array(
);
// One-to-one relationship with gallery page
private static $has_one = array(
'TablePage'=> 'Page',
'TableColumnSet' => 'TableColumnSet',
'PDF' => 'File',
);
// tidy up the CMS by not showing these fields
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->removeFieldFromTab("Root.Main","TablePageID");
$fields->removeFieldFromTab("Root.Main","TableColumnSetID");
$fields->removeFieldFromTab("Root.Main","SortOrder");
$fields->addFieldsToTab("Root.Main", $this->getMyColumnOptions());
return $fields;
}
public function getMyColumnOptions()
{
$columnArray = [];
$Columns = DataObject::get('TableColumnSet');
foreach($Columns as $Column){
$columnArray[] = TextField::create($Column->TableColumnHeader);
}
return $columnArray;
}
// Tell the datagrid what fields to show in the table
private static $summary_fields = array(
);
public function canEdit() {
return true;
}
public function canDelete() {
return true;
}
public function canCreate(){
return true;
}
public function canPublish(){
return true;
}
public function canView(){
return true;
}
}
But those are the tricky parts: Figuring out how to map values from one DataObject into labels for another, and then auto-generating an nth number of rows based on how many columns have been created.
<?php
class TablePage extends Page
{
private static $db = array(
'H1' => 'varchar(250)',
);
private static $has_many = array(
'TableRowItems' => 'TableRowItem',
'TableColumnSets' => 'TableColumnSet'
);
private static $has_one = array(
);
public function getCMSFields()
{
$fields = parent::getCMSFields();
$fields->addFieldToTab("Root.Main", new TextField("H1"), "Content");
$gridFieldConfig = GridFieldConfig_RecordEditor::create();
$gridFieldConfig->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
// field from drawer class => label in UI
'TableColumnHeader' => 'Table Column Header'
));
$gridfield = new GridField(
"TableColumnSets",
"Table Column Sets",
$this->TableColumnSets(),
$gridFieldConfig
);
$fields->addFieldToTab('Root.Specs Table', $gridfield);
$gridFieldConfig2 = GridFieldConfig_RecordEditor::create();
$gridFieldConfig2->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
// field from drawer class => label in UI
'TableRowValue' => 'Table Row Value'
));
$gridfield2 = new GridField(
"TableRowItems",
"Table Row Items",
$this->TableRowItems(),
$gridFieldConfig2
);
$fields->addFieldToTab('Root.Specs Table', $gridfield2);
return $fields;
}
}
class TablePage_Controller extends Page_Controller
{
private static $allowed_actions = array(
);
public function init()
{
parent::init();
// You can include any CSS or JS required by your project here.
// See: http://doc.silverstripe.org/framework/en/reference/requirements
}
}
Here are the classes TableColumnSet and TableRowValue. I figured, there would be one set of column headers associated with an nth number of rows, so I figured there would be a $has_many relationship between the two classes, in that a TableColumnSet could have many TableRowValues, but there would only be one TableColumnSet for all the TableRowValues. I was hoping to associate the TableRowValues to the TableColumnSet values using a dropdown with all the column headers created but that just sounds like a bad idea. Having to manually associate every field in a row to the column headers seems tedious and potentially difficult content managers.
<?php
class TableColumnSet extends DataObject {
private static $db = array(
'SortOrder' => 'Int',
'TableColumnHeader'=>'varchar(250)'
);
// One-to-one relationship with gallery page
private static $has_one = array(
'TablePage'=> 'Page'
);
private static $has_many = array(
'TableRowItems' => 'TableRowItem'
);
// tidy up the CMS by not showing these fields
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->removeFieldFromTab("Root.Main","TablePageID");
$fields->removeFieldFromTab("Root.Main","SortOrder");
return $fields;
}
// Tell the datagrid what fields to show in the table
private static $summary_fields = array(
'TableColumnHeader' => 'Table Column Header',
);
public function canEdit() {
return true;
}
public function canDelete() {
return true;
}
public function canCreate(){
return true;
}
public function canPublish(){
return true;
}
public function canView(){
return true;
}
}
I feel like may be on to something here, at least in regards to the relationship between the column headers and rows? I'm not sure, though.
I might be off base here, since I have no experience with SilverStripe. But... my PHP / HTML table solution might apply here:
<?php
// parse your table data into this structure
$tableData = array(
"rowOne" => array(
"columnName" => "columnValue1",
"colName" => "colValue1"
// .....
),
"rowTwo" => array(
"columnName" => "columnValue2",
"colName" => "colValue2"
// .....
)
);
// now loop through the array with a printHeader parameter
$tableHTML = array(
"<table>"
);
$tableHead = array(
"<thead>"
);
$tableBody = array(
"<tbody>"
);
$printHeader = true;
foreach ($tableData as $row) {
foreach ($row as $column => $value) {
$tableRow = "<tr>";
if ($printHeader) {
$tableHead[] = "<th>".$column."</th>";
}
$tableRow .= "<td>".$value."</td>";
}
$tableBody[] = $tableRow."</tr>";
// after the first row, set printHeader to false and close the <thead>
$printHeader = false;
$tableHead[] = "</thead>";
}
// implode table header to string with linebreaks
$tableHead = implode(PHP_EOL, $tableHead);
// close table <tbody> & implode to string with linebreaks
$tableBody[] = "</tbody>";
$tableBody = implode(PHP_EOL, $tableBody);
// add all table elements together
$tableHTML[] = $tableHead;
$tableHTML[] = $tableBody;
$tableHTML[] = "</table>";
// implode table array to string
$tableHTML = implode(PHP_EOL, $tableHTML);
// print or write anywhere
echo($tableHTML);
?>
The array structure for all the steps in the loop are to keep the default server memory cleaner to remove old data. If you concat ($var .= "string";) everything as strings all the references will stay stored in memory and bog down the server when displaying large tables.
I hope this is of some help
I am not retrieving any values with a simple Doctrine PHPCR query I am executing.
In this piece of code I get all the values from field 'name':
public function getPagesAction()
{
$dm = $this->get('doctrine_phpcr.odm.default_document_manager');
$qb = $dm->createQueryBuilder();
$qb->from()->document('Foo\BarBundle\Document\StandardPage', 'p');
return $this->render(
'FooBarBundle:Toolbar:navigation.html.twig',
array('names' => $qb->getQuery()->execute())
);
}
output: home, mypage, testpage, foo
And with this code I get nothing in return:
public function getPagesAction()
{
$dm = $this->get('doctrine_phpcr.odm.default_document_manager');
$qb = $dm->createQueryBuilder();
$qb->from()->document('Foo\BarBundle\Document\StandardPage', 'p');
$qb->where()->like()->field('p.name')->literal('mypage');
return $this->render(
'FooBarBundle:Toolbar:navigation.html.twig',
array('names' => $qb->getQuery()->execute())
);
}
I am also not receiving any errors. My HTML is plain empty. The query does work when I replace 'p.name' with 'p.title'.
Here is my StandardPage.php on Gist
I have following function:
public function id_callback($idnumber){}
And I call it this way:
for($i = 1; $i <= $fieldcount; $i++)
{
add_settings_field(
'id' . $i,
'ID' . $i,
array( $this, 'id_callback' ),
'my-setting-admin',
'setting_section_id'
);
}
How can I pass $i as an argument to id_callback?
Thanks in advance.
Your code is a little abstract, as it does not come with a specific context, however i'll try to help you. You basically have to create a variable and a method that sets that variable. Then you should use that method to change the variable in the for loop. Here is a quick example of what i'm talking about (i've created an example class that replicates a simple use case):
<?php
class Example_Callback {
public $id_callback;
public function set_id_callback($id_callback) {
$this->id_callback = $id_callback;
}
public function do_something() {
// here is your $i:
$callback_id = $this->id_callback;
// here you can do something with your $callback_id
}
public function test() {
$fieldcount = 5; // usually this should come from somewhere
for($i = 1; $i <= $fieldcount; $i++) {
$this->set_id_callback($i);
add_settings_field(
'id' . $i,
'ID' . $i,
array( $this, 'do_something' ),
'my-setting-admin',
'setting_section_id'
);
}
}
}
$callback = new Example_Callback();
$callback->test();
?>