How to make dynamic drop down in php? - codeigniter

I want to make a dynamic drop down in CI.I had done it in CI by directly passing the values from model With its design by concatenation the html.. But now i want it without the html i.e. the function just only should return the array ...
my before function was something like this...
function category() {
$sql = $this->db->query("select * from ss_category where parent_id='0'");
$result = $sql->result();
//print_r($result);die();
$output = array();
foreach ($result as $ra) {
$output=$this->get_child($ra->cat_id);
}
//print_r($output);die();
return $output;
}
function get_child($parent_id) {
//echo "select * from ss_category where parent_id=" . $parent_id;
$sql = $this->db->query("select * from ss_category where parent_id=" . $parent_id);
$r = $sql->result();
if (!empty($r)) {
foreach ($r as $s) {
$this->get_child($s->cat_id);
}
//print_r($child);
}
//print_r($r);
}
I want to make drop down something like this..
-parent 1
-child 1
-subchild 1
-child 2
-child 3
-subchild 1
-parent 2
-child 1
My table structure is like this..
+---------------------------------------------------------------+
| cat_id category_name cat_slug parent_id level description |
+---------------------------------------------------------------+
| 1 Elecotronics Electronics 1 description |
+---------------------------------------------------------------+

function parent_sort($categories)
{
foreach($categories as $item)
$childs[$item->parent_id][] = $item;
foreach($categories as $item)
if (isset($childs[$item->category_id]))
$item->childs = $childs[$item->category_id];
return $childs[0];
}

Related

Laravel : how to use pivot table for taggable system

I want create tag for posts
for example I created three new tags but submit a only a row in TaggablesTable
Tags Table:
id | name |
--------------
1 | first|
2 | two |
3 | three|
taggables Table:
tag_id|taggable_id|taggable_type
-------------------------------
3 | 1 |post
public function store(Request $request)
{
$data = $request->all();
$post = Post::create($data);
if ($post && $post instanceof Post) {
$tags = $request->input('tags');
foreach ($tags as $tag){
$newTag =Tag::firstOrCreate(['name'=>$tag]);
$tags= $newTag->id;
}
$post->tags()->sync($tags);
return redirect()->back();
}
}
How can it be done?
You are overwriting tags every time the loop runs. Map seems like an easier approach to your problem.
$data = $request->all();
$post = Post::create($data);
$tags = collect($request->input('tags'))->map(function (string $tag) {
return Tag::firstOrCreate(['name'=>$tag])->id;
})->all();
$post->tags()->sync($tags);
return redirect()->back();

Laravel 5.5 recursive function to create menu

I have created a mysql table as below:
id | menuname | parentid
---+-------------------+---------
1 | dashboard | 0
2 | Content | 0
3 | Home Page Content | 2
4 | Banners | 2
5 | Settings | 0
6 | Block Content | 3
7 | Site Content | 3
So that the menu structure will look like:
dashboard
Content
Home Page Content
Block Content
Site Content
Banners
Settings
I have the controller:
public function index() {
$data = array();
$permissionRecord = Permission::all();
$this->categoryTree($permissionRecord);
dd('-end-);
$data['permissionRecord'] = $permissionRecord;
return view('Administrator.permission.permissionAdd',$data);
}
function categoryTree($permissionRecord, $parent_id = 0, $sub_mark = '')
{
foreach($permissionRecord as $row) {
echo $sub_mark.$row->name;
$this->categoryTree($permissionRecord, $row->id, $sub_mark.'---');
}
}
But this show the data :
Dashboard---Dashboard------Dashboard---------Dashboard------------Dashboard---------------Dashboard------------------Dashboard---------------------Dashboard------------------------Dashboard---------------------------Dashboard------------------------------Dashboard---------------------------------Dashboard------------------------------------Dashboard
Please note, I dd() inside the controller and did not passed the data to the view.
You've not accounted for the parent ID:
function categoryTree($permissionRecord, $parent_id = 0, $sub_mark = '')
{
foreach($permissionRecord as $row) {
if ($row->parentid == $parent_id) {
echo $sub_mark.$row->name;
$this->categoryTree($permissionRecord, $row->id, $sub_mark.'---');
}
}
}
Try that and see what happens - Note I've wrapped the recursive function call in an if() that checks if the current records parentId is equal to the parent ID passed into the method.
To get it to display the items in an indented list:
public function categoryTree($permissionRecord, $parent_id = 0)
{
$html = '<ul>';
foreach($permissionRecord as $row) {
if ($row->parentid == $parent_id) {
$html .= '<li>' . $row->menuname;
$html .= $this->categoryTree($permissionRecord, $row->id, $html);
$html .= '</li>';
}
}
$html .= '</ul>';
return $html;
}
Then just call:
$html = $this->categoryTree($permissionRecord);
Example of it working with a unit test

Codeigniter Model Function and query Not working

Iam try to run a query in codeigniter model.Its working but when I echo model function query is like below.
SELECT * FROM `table1` WHERE `id` = '17'
SELECT * FROM `table1` WHERE `id` = '20'
SELECT * FROM `table1` WHERE `id` = '21'
SELECT * FROM `table1` WHERE `id` = '22'
SELECT * FROM `table1` WHERE `id` = '23'
My model function is given below
function get_quick_navi_menu($q_code)
{
$this->db->select("*");
$this->db->where('q_id',$q_code);
$this->db->from("table0");
$q = $this->db->get();
//echo $this->db->last_query();
$final = array();
if ($q->num_rows() > 0)
{
foreach ($q->result() as $row) {
$this->db->select("*");
$this->db->from("table1");
$this->db->where("id",$row->id);
$q = $this->db->get();
echo $this->db->last_query();
if ($q->num_rows() > 0) {
$row->children = $q->result();
}
array_push($final, $row);
}
}
I want to run query like below
SELECT * FROM `table1` WHERE `id` = '17,18,19..'
Table Structure
Table0
id q_id value1
1 2 4
2 2 5
3 2 6
Table1
t1_id id value1 value2
1 1 2 2
2 2 5 6
3 3 8 12
View
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1" style="margin-left: 1px; opacity: .9;">
<?php foreach ($menus as $menu) { ?>
<li class="dropdown-submenu"><?php echo $menu->title;?>
<ul class="dropdown-menu"> <?php
if (isset($menu->children)) {
foreach ($menu->children as $child) {?>
<li><?php echo $child->menu_item;?></li> <?php
}
}
?></ul></li><?php } ?>
</ul>
Controller
$menus = $this->Home_model->get_quick_navi_menu($q_code);
$data = array('menus' => $menus);
Required Output
Selecting value1 and value2 from table1 according to id from table0.
How to solve this please help.
Use this function in controller
public function getTableData()
{
$this->db->select('GROUP_CONCAT(id) as id');
$tbl0 = $this->db->get('table0')->row_array();
if($tbl0) {
$ids = explode(',', $tbl0['id']);
$this->db->where_in('id', $ids);
$tbl1 = $this->db->get('table1')->result_array();
echo "<pre>"; print_r($tbl1);
}
}
Hope this will help you;
Get all ids in an array name here ids and use where_in outside the loop
public function get_quick_navi_menu($q_code)
{
$this->db->select("*");
$this->db->where('q_id',$q_code);
$this->db->from("table0");
$q = $this->db->get();
$final = array();
if ($q->num_rows() > 0)
{
foreach ($q->result() as $key => $row)
{
$ids[$key] = $row->id;
$data[$key] = $row;
}
$this->db->select("*");
$this->db->from("table1");
$this->db->where_in("id",$ids);
$q = $this->db->get();
//echo $this->db->last_query();
if ($q->num_rows() > 0)
{
if ( ! empty($data))
{
foreach ($data as $key => $item)
{
$item->children = $q->result();
$final[] = $item;
}
}
}
}
return $final;
/*print_r($final);*/
}
In your controller class:
make sure you have loaded your model and database in controller or in autoload.php
$q_code = 'q_code_value';
$data['menus'] =$this->Home_model->get_quick_navi_menu($q_code);
/* pass the $data in the view like this*/
$this->load->view('your_view_file_path',$data);
In your view :
<div><?php print_r($records);?></div>
For more : https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data

Getting data from model to controller

I do have a question : I cannot pass the data from model to controller
You can see some of my codes, please help me.
It does not work!
this is my model "mymodel.php"
....
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
if($query){
foreach ($query->result() as $row);
}
$t = "EXAMPLE/{$row->code}";
function wandad() {
return $t;
}
.....
and this is my controller mycont.php
...
$this->load->model('mymodel');
$data['new'] = $this->Mymodel->wandad();
$this->load->view('myview',$data);
...
and this is my view myview.php
....
echo $new;
.....
Clearly you The model is not written properly and to corrent this simple do this
1.) I put a default value on $t
2.) I put the query >> loop on the inside function
wandad
so it can be executed once called from controller
function wandad() {
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
$t = "";
if($query){
foreach ($query->result() as $row){
$t = "EXAMPLE/{$row->code}".'<br>';
}
}
return $t;
}
Here are several issues into your model
Your Foreach function doesn't do anything
$t is not in the same namespace than wandad()
Function wandad is not defined into your model class
I'm not sure of what you wanna get with wandad() function but here's a pattern.
function yourFunction()
{
/* This will return the full query as an array */
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1")->result_array();
/* Store variable in the same class */
$this->t = "EXAMPLE/".$query[0]['code'];
/* Close yourFunction() */
}
public function wandad() {
return $this->t;
}
Then into your controller, do that instead :
$this->load->model('mymodel');
$this->mymodel->yourFunction();
$data['new'] = $this->mymodel->wandad();
$this->load->view('myview',$data);
#Touki his foreach actually does something. It will set the variable $row with the last row that is returned from the query. Not the best way to do it ... But it's a way. Better would be to use a limit in the query.
There is a small mistake in your code #Ernesto.that is
foreach ($query->result() as $row){
$t. = "EXAMPLE/{$row->code}".'<br>';
}
but your code was simply nice

Magento Product Attribute Get Value

How to get specific product attribute value if i know product ID without loading whole product?
Mage::getResourceModel('catalog/product')->getAttributeRawValue($productId, 'attribute_code', $storeId);
A way that I know of:
$product->getResource()->getAttribute($attribute_code)
->getFrontend()->getValue($product)
you can use
<?php echo $product->getAttributeText('attr_id') ?>
Please see Daniel Kocherga's answer, as it'll work for you in most cases.
In addition to that method to get the attribute's value, you may sometimes want to get the label of a select or multiselect. In that case, I have created this method which I store in a helper class:
/**
* #param int $entityId
* #param int|string|array $attribute atrribute's ids or codes
* #param null|int|Mage_Core_Model_Store $store
*
* #return bool|null|string
* #throws Mage_Core_Exception
*/
public function getAttributeRawLabel($entityId, $attribute, $store=null) {
if (!$store) {
$store = Mage::app()->getStore();
}
$value = (string)Mage::getResourceModel('catalog/product')->getAttributeRawValue($entityId, $attribute, $store);
if (!empty($value)) {
return Mage::getModel('catalog/product')->getResource()->getAttribute($attribute)->getSource()->getOptionText($value);
}
return null;
}
It seems impossible to get value without loading product model. If you take a look at file app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php you'll see the method
public function getValue(Varien_Object $object)
{
$value = $object->getData($this->getAttribute()->getAttributeCode());
if (in_array($this->getConfigField('input'), array('select','boolean'))) {
$valueOption = $this->getOption($value);
if (!$valueOption) {
$opt = new Mage_Eav_Model_Entity_Attribute_Source_Boolean();
if ($options = $opt->getAllOptions()) {
foreach ($options as $option) {
if ($option['value'] == $value) {
$valueOption = $option['label'];
}
}
}
}
$value = $valueOption;
}
elseif ($this->getConfigField('input')=='multiselect') {
$value = $this->getOption($value);
if (is_array($value)) {
$value = implode(', ', $value);
}
}
return $value;
}
As you can see this method requires loaded object to get data from it (3rd line).
First we must ensure that the desired attribute is loaded, and then output it. Use this:
$product = Mage::getModel('catalog/product')->load('<product_id>', array('<attribute_code>'));
$attributeValue = $product->getResource()->getAttribute('<attribute_code>')->getFrontend()->getValue($product);
Try this
$attribute = $_product->getResource()->getAttribute('custom_attribute_code');
if ($attribute)
{
echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
}
You don't have to load the whole product.
Magentos collections are very powerful and smart.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('entity_id', $product->getId());
$collection->addAttributeToSelect('manufacturer');
$product = $collection->getFirstItem();
$manufacturer = $product->getAttributeText('manufacturer');
At the moment you call getFirstItem() the query will be executed and the result product is very minimal:
[status] => 1
[entity_id] => 38901
[type_id] => configurable
[attribute_set_id] => 9
[manufacturer] => 492
[manufacturer_value] => JETTE
[is_salable] => 1
[stock_item (Varien_Object)] => Array
(
[is_in_stock] => 1
)
This one works-
echo $_product->getData('ATTRIBUTE_NAME_HERE');
You can get attribute value by following way
$model = Mage::getResourceModel('catalog/product');
$attribute_value = $model->getAttributeRawValue($productId, 'attribute_code', $storeId);
$orderId = 1; // YOUR ORDER ID
$items = $block->getOrderItems($orderId);
foreach ($items as $item) {
$options = $item->getProductOptions();
if (isset($options['options']) && !empty($options['options'])) {
foreach ($options['options'] as $option) {
echo 'Title: ' . $option['label'] . '<br />';
echo 'ID: ' . $option['option_id'] . '<br />';
echo 'Type: ' . $option['option_type'] . '<br />';
echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
}
}
}
all things you will use to retrieve value product custom option cart order in Magento 2: https://www.mageplaza.com/how-get-value-product-custom-option-cart-order-magento-2.html
You could write a method that would do it directly via sql I suppose.
Would look something like this:
Variables:
$store_id = 1;
$product_id = 1234;
$attribute_code = 'manufacturer';
Query:
SELECT value FROM eav_attribute_option_value WHERE option_id IN (
SELECT option_id FROM eav_attribute_option WHERE FIND_IN_SET(
option_id,
(SELECT value FROM catalog_product_entity_varchar WHERE
entity_id = '$product_id' AND
attribute_id = (SELECT attribute_id FROM eav_attribute WHERE
attribute_code='$attribute_code')
)
) > 0) AND
store_id='$store_id';
You would have to get the value from the correct table based on the attribute's backend_type (field in eav_attribute) though so it takes at least 1 additional query.
If you have an text/textarea attribute named my_attr you can get it by:
product->getMyAttr();

Resources