Retrieving data from database for comparison - laravel

I am able to retrieve items and its details from the database but what i want to do is, when i get an item, i compare its quantity to a certain number.
Controller
$item = Item::all();
if($item->quantity = 5)
{
return $response;
}
else
{
//
}
What is happening here is, it actually sets 5 to the item's quantity but instead i want to get the quantity of the item selected and compare if it is equal to 5. How do i do this?

You are assigning the value with a single '=' since it's an assignment operator.
Instead, compare the values with '=='
$item = Item::all();
if($item->quantity == 5)
{
return $response;
}
else
{
//
}

Related

Modify single Item of Laravel Collection without mapping every single item

I loop trough an eloquent Collection and I want to add the data to another Collection called "$tagCollection". If an entry with the same tag_id already exists I only want to increase the rating-column for the existing entry.
At the moment it looks like this. Has anyone an Idea?
$tagCollection = collect();
$entries->each(function($entry) use($tagCollection){
$tagId = $entry->tag_id;
//something like this
if($tagCollection->contains('tag_id', $tagId)){
$tagCollection->update ('rating' => $oldRating + 0.5)
} else{
$tagCollection->push(array(
'tag_id' => $tagId,
'rating' => 0.35
));
}
});
I also tried to use ->pull() to remove the Item out of the Collection and then push it again with the new rating but I also do not know how
Can you do it with array instead of collection? For example:
$tagArray = [];
$entries->each(function ($entry) use (&$tagArray) {
if (isset($tagArray[$entry['tag_id']])) {
$tagArray[$entry['tag_id']] += 0.5;
} else {
$tagArray[$entry['tag_id']] = 0.35;
}
});
If the end goal is to update all the entries present in $entries that belong to a specific $tagId, then you can do this
$entryIds = $entries->where('tag_id',$tagId)->pluck('id')->toArray();
Entry::whereIn('id', $entryIds)->update(['rating' => \DB::raw('rating + 0.5')]);
And thats it.

Minimum one field required in a list of multiple fields in magento admin form

How to validate minimum one field required in a list of multiple fields in magento admin form.
Form Field includes text box,select fields in admin form.
if(Validation) {
Validation.addAllThese([ ['validation-myown','Please insert proper word',function(v,r){ var a = Validation.get('IsEmpty').test(v);
if(a == false){
return true;
}else{
return false;
}
} ], [ ] ]) }
You can try this using jquery:
$("#FORMID").submit(function(){
var elemcount=0;
$(this).find('input[type=text], select').each(function(){
if($(this).val() != "") elemcount+=1;
});
// If the value of elemcount variable is 0, all elements are empty.
// Your select should have a default value as blank.
// If it is not so you have to add separate code for select and input.
});

Laravel 5 - Display different views based on database query

I have the following database design
I have several different Documents I want a user to be able to create. Each document has its own view for the creation of the document, or the editing.
If the document they are trying to create has already been created, they should see the edit page for that document.
At the moment, I have the following
public function create(Project $project)
{
$documentTypesCreated =
$project->document()
->join('document_type', 'documents.id', '=', 'document_type.documentId')
->select('document_type.documentId', 'document_type.name')
->get();
$documentLink = $_GET['documentType'];
if($documentTypesCreated->isEmpty()){
return View::make($documentLink.'Doc.create', compact('project'));
} else {
foreach($documentTypesCreated as $documentName) {
if($documentName->name != $documentLink) {
return View::make($documentLink.'Doc.create', compact('project'));
} else {
$document = Document::find($documentName->documentId);
return View::make($documentLink.'Doc.edit', compact('project', 'document'));
}
}
}
}
Breaking this up, I am doing the following:
Firstly, I get all the Documents that have been created for a Project
$documentTypesCreated =
$project->document()
->join('document_type', 'documents.id', '=', 'document_type.documentId')
->select('document_type.documentId', 'document_type.name')
->get();
I then get the Document the user is trying to create from the URL
$documentLink = $_GET['documentType'];
So lets say that the query returns that this Project has
DocumentA
DocumentB
And the documentLink shows that I am trying to create DocumentB.
Because DocumentB has already been created, I need the edit page for this Document. Firstly, I check if the query returned and Documents
if($documentTypesCreated->isEmpty()){
return View::make($documentLink.'Doc.create', compact('project'));
} else {
}
If it didnt, it will show the create page for the chosen Document. If it did, the else statement will kick in.
Within the else statement, I loop through all the Documents the query returned
foreach($documentTypesCreated as $documentName) {
}
I then do the following, and this is where my logic is failing
if($documentName->name != $documentLink) {
return View::make($documentLink.'Doc.create', compact('project'));
} else {
$document = Document::find($documentName->documentId);
return View::make($documentLink.'Doc.edit', compact('project', 'document'));
}
If the document Name from the query is not equal to the document I am trying to create, then I show the create page for that Document. Otherwise, I show the edit page.
Now lets get back to where I chose DocumentB. I know that I have already created this Document, so I should see its edit page. However, because DocumentA is the first result returned in the query, the above statement looks like the following
if("DocumentA" != "DocumentB") {
return View::make($documentLink.'Doc.create', compact('project'));
} else {
$document = Document::find($documentName->documentId);
return View::make($documentLink.'Doc.edit', compact('project', 'document'));
}
So it is going to show the create page for DocumentB, not the edit page. If DocumentB was the first result returned, then the edit page would be displayed.
I Hope this makes sense. How can I get it displaying the correct view for the document?
Thanks
Controller
Base on your query - you may set these variables manually
$create = true;
$edit = false;
Logic
if ($query == 'any logic') {
$create = true;
$edit = false;
}else{
$create = false;
$edit = edit;
}
Then, send them over to your view.
View
#if($create == true)
//.. Show Create Form
#else
// .. Show Edit Form
#stop
Then, your view will render base the result of your query. I hope this help !

Magento grid, getting incorrect total value

I created a grid. Issues is i am getting total number of records incorrectly. But all the records are in the grid.
I tried in grid.html $this->getCollection()->getSize() code and it returns the incorrect value.
But count($this->getCollection()) returns the correct value. How can i solve this issues with $this->getCollection()->getSize().
Can anyone help me please.
Thank You
This is the classic case of using a group by clause or a having clause (or both) on your collection. Magento's getSelectCountSql function does not account for the group by or the having clause because of its poor frontend performance. Instead it generally uses indeces and statistics. However, if you would like to you can override your collection's getSelectCountSql as follows:
public function getSelectCountSql($select) {
$countSelect = clone $select;
$countSelect->reset(Zend_Db_Select::ORDER);
$countSelect->reset(Zend_Db_Select::LIMIT_COUNT);
$countSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
if ($select->getPart(Zend_Db_Select::HAVING)) {
//No good way to chop this up, so just subquery it
$subQuery = new Zend_Db_Expr("(".$countSelect->__toString().")");
$countSelect
->reset()
->from(array('temp' => $subQuery))
->reset(Zend_Db_Select::COLUMNS)
->columns('COUNT(*)')
;
} else {
$countSelect->reset(Zend_Db_Select::COLUMNS);
// Count doesn't work with group by columns keep the group by
if (count($select->getPart(Zend_Db_Select::GROUP)) > 0) {
$countSelect->reset(Zend_Db_Select::GROUP);
$countSelect->distinct(true);
$group = $select->getPart(Zend_Db_Select::GROUP);
$countSelect->columns("COUNT(DISTINCT ".implode(", ", $group).")");
} else {
$countSelect->columns('COUNT(*)');
}
}
return $countSelect;
}
This should return the correct number from getSize

Magento- configurable products options order to match the order they are in the attribute set

I have a magento site I'm building (1.6) my site has a bunch of configurable options with 6 or so attributes set as dropdowns for the customer to pick from. After saving a configurable product the order of the attributes changes. I've been able to find what I think is happening, it is reordering them according to the attribute id not the order I have them set up in the attribute set. I need to find a way to get magento to keep the order of the attributes the same as they are in the attribute set. Any help is greatly appreciated.
Trick is pretty simple.
Just drag'n'drop them in product->edit->associatedProduct tab ;)
The order of attributes from this page is saved to catalog_product_super_attribute table.
I was also looking for the same and finally i found this and it works for me hope it will work for others too.
From Admin Panel > Catalog > Attributes > Manage Attributes select the one like if you want to make it like for the capacity 4GB > 8GB > 16GB and so on then do this small changes.
Select Manage Label / Options > Manage Options (values of your attribute) and if you already created the variables just add the position manually, like:
4GB - 1
8GB - 2
16GB - 3
Save and flush the cache.
That's it, now it should show the attributes as per the position that you assign.
It is an old question but I have found a solution right now having the same problem.
If you are still interesting in changing the order of the configurable attribute you may want to look into this method:
Mage_Catalog_Model_Product_Type_Configurable::getConfigurableAttributes()
getConfigurableAttributes() load the collection of attributes.
The first time the collection is loaded, before saving the configurable, there is no position value, so I think the attribute ID rules on the display order.
If you want to alter this order you can only add a sort for attribute_id after the ->orderByPosition() and revert the order ( this will preserve the position functionality )
For example, here I have added ->setOrder('attribute_id','DESC')
public function getConfigurableAttributes($product = null)
{
Varien_Profiler::start('CONFIGURABLE:'.__METHOD__);
if (!$this->getProduct($product)->hasData($this->_configurableAttributes)) {
$configurableAttributes = $this->getConfigurableAttributeCollection($product)
->orderByPosition()
->setOrder('attribute_id','DESC')
->load();
$this->getProduct($product)->setData($this->_configurableAttributes, $configurableAttributes);
}
Varien_Profiler::stop('CONFIGURABLE:'.__METHOD__);
return $this->getProduct($product)->getData($this->_configurableAttributes);
}
OR
In case you want to modify the order in more radical way, you can also act on this method:
Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Config::getAttributesJson()
This is basically calling the getConfigurableAttributes().
To understand if this is the first configurable load, you can check all the attributes in the array $attributes to see if they all have a position ==0 and then proceed with a manual reorder )
Example
I'm omitting all the module creation and the rewrite part.
Here an example modifying getAttributesJson() in order to have the color attribute always on the top.
public function getAttributesJson()
{
$attributes = $this->_getProduct()->getTypeInstance(true)
->getConfigurableAttributesAsArray($this->_getProduct());
if (!$attributes) {
return '[]';
} else {
// == START ==
// checking if I can re-order
if ($this->isNoSavedPosition($attributes)) {
$attributes = $this->attributeReorder($attributes);
}
// == END ==
// Hide price if needed
foreach ($attributes as &$attribute) {
if (isset($attribute['values']) && is_array($attribute['values'])) {
foreach ($attribute['values'] as &$attributeValue) {
if (!$this->getCanReadPrice()) {
$attributeValue['pricing_value'] = '';
$attributeValue['is_percent'] = 0;
}
$attributeValue['can_edit_price'] = $this->getCanEditPrice();
$attributeValue['can_read_price'] = $this->getCanReadPrice();
}
}
}
}
return Mage::helper('core')->jsonEncode($attributes);
}
public function isNoSavedPosition($attributes)
{
foreach ($attributes as $attribute) {
if (isset($attribute['position']) && $attribute['position'] != 0) {
return false;
}
}
// there is no position saved
// - this is the first time the configurable is loaded
// - (the position is saved on second save action)
return true;
}
public function attributeReorder($attributes)
{
// we want the Color attribute to be always on the top
$newAttributesOrderArray = array();
foreach ($attributes as $key => $attribute) {
if (isset($attribute['label']) && $attribute['label'] == 'Color') {
$newAttributesOrderArray[] = $attribute;
unset($attributes[$key]);
}
}
$newAttributesOrderArray = array_merge($newAttributesOrderArray,$attributes);
return $newAttributesOrderArray;
}

Resources