get dynamic value inside foreach loop - php

I'm using Codeigniter to write a shopping cart system. Tried to research but unable to figure out the way, I want to get the dynamic value "Green/Red/Yellow" in dynamic drop-down list like below:
Below is my code:
Model:
class Products_model extends CI_Model {
public function get_all() {
$result = $this->db->get('products');
foreach ($result->result() as $value) {
if ($value->option_values){
$value->option_values = explode(',', $value->option_values);
}
} return $result;
}
Controller:
class Shopping_cart extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('html');
$this->load->model('products_model');
$this->load->library('cart');
}
public function index() {
$data['records'] = $this->products_model->get_all();
$data['main'] = 'shopping_cart_view';
$this->load->view('templates/shopping_cart', $data);
}
public function add() {
//If the product is not listed, perform insert
$data = array(
'id' => $this->input->post('id'),
'qty' => $this->input->post('quantity'),
'price' => $this->products_model->get_by_id($this->input->post('id'))->price,
'name' => $this->products_model->get_by_id($this->input->post('id'))->name,
'option' => '' //I want to get the dynamic values in dropdown list and put in to this option array.
);
$this->cart->insert($data);
redirect('shopping_cart');
}
View:
<?php
//List products
foreach ($records->result() as $value) :
echo form_open('shopping_cart/add');
?>
<?php //List the dropdown if value has option i.e color/size/type
if ($value->option_name)
:?>
<?php echo form_label($value->option_name, $value->id)?>
<?php echo form_dropdown(
$value->option_name,
$value->option_values
)?>
<?php endif;?>
<?php
echo form_hidden('id', $value->id);
echo form_submit('submit', 'Add to cart');
?>
<?php echo form_close();?>
<?php endforeach; ?>
And below is $this->cart->contents() when i submitted "add to cart":
Array ( [c4ca4238a0b923820dcc509a6f75849b] => Array ( [rowid] => c4ca4238a0b923820dcc509a6f75849b [id] => 1 [qty] => 1 [price] => 100 [name] => T-shirt [option] => [subtotal] => 100 ) )
I am running out of ideas try to get the dynamic value inside dynamic loop. Any advises are really appreciated.
Thanks a lots!

I would create the array of option_values in the controller (so bring option_values as string via Model and declare an array in the controller that will contain the explode(',', option_values) ).
Then use this array as source for 'option'.
Hope this helps.

The problem is in this part:
foreach ($result->result() as $value) {
if ($value->option_values){
$value->option_values = explode(',', $value->option_values);
}
}
return $result;
$value is only valid, in the way you have done this, during the method. It's not saved to the $result. You would need to do something along these lines:
$new_result = array ();
foreach ($result->result() as $value) {
if ($value->option_values){
$value->option_values = explode(',', $value->option_values);
}
$new_result[] = $value;
}
return $new_result;
When you are going through a foreach loop like that, you disconnect the $value form $result.
There are other ways to do this, but I think that is the clearest and most understandable.

Related

How to pass data controller to view in codeigniter

I am getting user profile fields from the database and want to display in my view but don't know to do this with the master layout.
this is my model
function fetchProfile($id,$page){
$query = $this->db->query("SELECT * FROM staff_master WHERE Id='$id'");
return $query->result();
}
this is my controller:
public function edit($id,$page){
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data= array('content'=>'view_staff_edit');
$this->load->view('template_master',$data);
}
I am also trying to find a solution. I am passing user Id and another by URL (get method).
You are overwriting $data['query'] when you assign the array next:
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data= array('content'=>'view_staff_edit');
Either do:
$data= array('content'=>'view_staff_edit');
$data['query'] = $this->StaffModel->fetchProfile($id,$page); // note position
Or:
$data = array(
'content' = 'view_staff_edit',
'query' => $this->StaffModel->fetchProfile($id,$page),
);
Access in view via $query and $content.
Unrelated:
You are also missing $page in your query, and its generally a good idea to declare gets as null if not set or you will get a notice: public function edit($id=null,$page=null){
Your overriding your first declaration of variable $data what you can do is to initialize them both at the same time.
Controller
public function edit($id,$page){
$data = array(
'query' => $this->StaffModel->fetchProfile($id,$page),
'content' => 'view_staff_edit'
);
$this->load->view('template_master',$data);
}
Then access it on your View file
<h1><?php echo $content ?></h1>
<?php foreach($query as $result): ?>
<p><?php echo $result->id ?></p>
<?php endforeach; ?>
Try doing something like this:
public function edit($id,$page) {
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data['content']= 'view_staff_edit';
$this->load->view('template_master',$data);
}
YOUR MODEL
function fetchProfile($id){
return $this->db->get_where('Id' => $id)->result_array();
}
YOUR CONTROLLER
public function edit($id,$page){
$data = array(
'query' => $this->StaffModel->fetchProfile($id),
'content' => 'view_staff_edit',
);
$this->load->view('template_master',$data);
}
YOUR "template_master" VIEW
<?php foreach ($query as $res){?>
<span><?php echo $res['Id'];?></span> //User html content according to your requirements ALSO you can add all columns retrieved from database
<?php } ?>

Insert one row using different models/pages - CodeIgniter

I'm new to CodeIgniter and I'm building a simple I/O website. I have only one database, say test and only one table results, that looks like this:
screenshot of the table "results"
I have two views personal.php and songs.php. In the first one I collect the data values to be inserted into the fields 2,3, and 4, and the rest of the values are collected in the second view. They are then inserted into the table via their relevant models, personal_model and songs_model.
Now obviously, they will be inserted into 2 different rows which is not what I want. What is the trick here? How should I manage it? So far I have thought of getting the last ID but I have no idea how to do it. Thanks in advance!
personal.php (first view)
<?php echo validation_errors(); ?>
<?php echo form_open('data/personal'); ?> //passes the data to the controller that loads the personal_model.php
"some input fields"
<button type="submit" name="submit">Submit Data</button>
songs.php (second view)
<?php echo validation_errors(); ?>
<?php echo form_open('data/songs'); ?> //passes the data to the controller that loads the songs_model.php
"some input fields"
<button type="submit" name="submit">Submit Rating</button>
personal_model.php (first model)
<?php
class Personal_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function insert_personal()
{
$this->load->helper('url');
$data = array(
'age' => $this->input->post('user_age'),
'education' => $this->input->post('user_edu'),
'twitter' => $this->input->post('user_twitter'),
'facebook' => $this->input->post('user_facebook')
);
return $this->db->insert('results', $data);
}
}
songs_model.php (second model)
<?php
class Ratings_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function insert_ratings()
{
$this->load->helper('url');
#$this->load->database();
$data = array(
'score' => $this->input->post('rating'),
'song1' => $this->input->post('rnd1'),
'song2' => $this->input->post('rnd2')
);
return $this->db->insert('results', $data);
}
}
Your Controller Function should be like this.
public function personal()
{
$lastInsertedID = $this->Personal_model->insert_personal();
$this->session->set_userdata("personalID",$lastInsertedID);
}
Set the last inserted id into session in your above controller function which should be return from your Personal_model. Here is code.
public function insert_personal()
{
$this->load->helper('url');
$data = array(
'age' => $this->input->post('user_age'),
'education' => $this->input->post('user_edu'),
'twitter' => $this->input->post('user_twitter'),
'facebook' => $this->input->post('user_facebook')
);
$this->db->insert('results', $data);
return $this->db->insert_id();
}
Then update your existing row in your insert_ratings function instead of insert record. Here is code.
public function insert_ratings()
{
$data = array(
'score' => $this->input->post('rating'),
'song1' => $this->input->post('rnd1'),
'song2' => $this->input->post('rnd2')
);
$personalID = $this->session->userdata("personalID");
$this->db->where("id",$personalID);
$this->db->update('results', $data);
return $this->db->affected_rows();
}
Then no new record will insert into table while submit your song.php form it will update the existing one.

How to load selected values in multiple-dropdown in update view in yii?

I am new in yii. I have problem with fetching selected values in dropdown when updating the record.
I have dropdown with multiple selection of user's email.
When adding it is working fine, it allows me to select multiple values and can insert selected value's ids comma separated in database. But the problem is when i want to update the record it displays only 1 selected record.
Here is my code:
in my View file:
<div class="controls">
<?php echo $form->dropDownList($model, 'uid', $allUsers, array('class' => 'select2-me input-sel_large', 'multiple' => 'true', 'options' => array('' => array('selected' => true)))); ?>
<?php echo $form->error($model, 'uid') ?>
</div>
in my Controller file:
$model = new User;
$allUsers = $model->getAllUsers();
in my Model file:
public function getAllUsers() {
$arr = Yii::app()->db->createCommand()
->select('userEmail,pkUserID')
->from('tbl_user')
->queryAll();
$users = array();
if (is_array($arr)) {
foreach ($arr as $value) {
$users[$value['pkUserID']] = $value['userEmail'];
}
}
return $users;
}
Can anyone help?
Example. Hope this help you.
class YourForm extends CFormModel
{
public $uid = array(); // selected pkUserID's
}
//in action
$yourForm = new YourForm();
$yourForm->uid = array(1,2,3); // for example selected users with pk 1,2,3
$this->render('your_view', array('yourForm'=>$yourForm));
//view
/** #var CActiveForm $form */
/** #var YourForm $yourForm */
echo $form->dropDownList(
$yourForm,
'uid',
CHtml::listData(User::model()->findAll(array('order' => 'userEmail ASC')), 'pkUserID', 'userEmail'),
array('empty' => '', 'multiple'=>true))
)

Magento ProductController append categoryId to products

I am adding a mass action to add a category. I am most of the way there I only have one function left to figure out.
Clr\Categorymassaction\controllers\Adminhtml\Catalog\ProductController.php
class Clr_Categorymassaction_Adminhtml_Catalog_ProductController extends Mage_Adminhtml_Controller_Action
{
public function massCategoryAction()
{
$productIds = $this->getRequest()->getParam('product');
$cat = $this->getRequest()->getParam('Category');
if (!is_array($productIds)) {
$this->_getSession()->addError($this->__('Please select product(s).'));
$this->_redirect('*/*/index');
}
else {
$cat = $category['label']->getCategoryId();
foreach($productIds as $product) {
//Process $cat into categoryId append categoryId to $productId
$cat->setPostedProducts($product);
}
//Save product
$cat->save();
}
}
}
Clr\Categorymassaction\Model\Observer
class Clr_Categorymassaction_Model_Observer {
public function addCategoryMassAction(Varien_Event_Observer $observer)
{
$block = $observer ->getBlock();
if ($block instanceof Mage_Adminhtml_Block_Catalog_Product_Grid) {
$block->getMassactionBlock()->addItem('Clr_Categorymassaction', array(
'label' => Mage::helper('catalog')->__('Add to Category'),
'url' => $block->getUrl('*/*/massCategory', array('_current' => true)),
'additional'=> array(
'visibility' => array(
'name' =>'Category',
'class' =>'required-entry',
'label' =>Mage::helper('catalog')->__('Categories'),
'type' => 'select',
'values' => Mage::getModel('Categorymassaction/system_config_source_category')->toOptionArray(),
'renderer' => 'Categorymassaction/catalog_product_grid_render_category',
)
)
));
};
}
}
One last thing
class Clr_Categorymassaction_Model_System_Config_Source_Category
{
public function toOptionArray($addEmpty = true)
{
$options = array();
foreach ($this->load_tree() as $category) {
$options[$category['value']] = $category['label'];
}
return $options;
}
I am mostly in trouble here because I am refactoring, Flagbit_changeattributeset and Vuleticd_AdminGridCategoryFilter. I know what I need to do (at least I think I do) I just don't know how to finish this off. Thanks for your eyes and ears if you read it all.
UPDATE: The observer from Vuleticd_AdminGridCategoryFilter had this additional code
'filter_condition_callback' => array($this, 'filterCallback'),
)
)
));
};
}
public function filterCallback($collection, $column)
{
$value = $column->getFilter()->getValue();
$_category = Mage::getModel('catalog/category')->load($value);
$collection->addCategoryFilter($_category);
return $collection;
}
This was used to apply the filter to the grid. What I am trying to do is instead of using the dropdown to filter column fields; use the dropdown to trigger the ProductController to pass the selected items a new categoryid.
https://magento.stackexchange.com/questions/67234/productcontroller-for-mass-action Asked this question over at magento's stackexchange figured I would post the link here for posterity.

Using Associate Array to Pass Database Information with PHP and CodeIgniter

Issue/Question: I'm using CodeIgniter to build an event calendar, and I have included a sharing option. This option works at a base level, but only displays the users' ID (primary key) in an <ul>. This isn't ideal, and I would like to show the users' first and last names in the <ul> instead. I thought creating an associative array would work, but I'm receiving funky results. The first and last name echo out as "Array Array" when the page loads, and the URL id comes up as "Array" when you select the "Array Array" link. I'm wondering what is wrong in my logic.
Funky link generated in view:
Array Array
Funky URL that is linked to "Array Array":
http://example.com/user/shared/view/Array
Modified Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Shared extends Common_Auth_Controller {
private $end_user;
public function __construct()
{
parent::__construct();
$this->end_user = $this->ion_auth->user()->row();
$data['end_user'] = $this->end_user;
$this->load->vars($data);
$this->load->model('events_model', 'events');
}
public function index()
{
$title['title'] = 'Shared';
$this->load->model('shared_model','shared');
$data['sharers'][] = array(
'shared_owner_id' => $this->shared->get($this->end_user->id),
'owner_first_name' => $this->shared->get($this->end_user->first_name),
'owner_last_name' => $this->shared->get($this->end_user->last_name),
);
$this->load->view('public/head_view', $title);
$this->load->view('user/header_view');
$this->load->view('user/shared_view', $data);
$this->load->view('user/footer_view');
}
Modified View:
<div class="hide-on-phones">
<ul>
<?php foreach($sharers as $key => $value): ?>
<li><?php echo $value['owner_first_name']." ".$value['owner_last_name'] ?></li>
<?php endforeach; ?>
</ul>
</div>
Model:
class Shared_model extends crud_model {
public function __construct()
{
parent::__construct();
$this->pk = 'id';
$this->table_name = 'shared';
}
public function get($shared_to_user_id)
{
$this->db->where('shared_to_id', $shared_to_user_id);
$ids = parent::get_all();
$users = array();
foreach ($ids as $id)
{
$users[] = $id->owner_id;
}
return $users;
}
}
Thank you so much for your help, and let me know if there is any more information that may be required. Below are the original view and controllers that work, but are not preferable.
Original Controller:
public function index()
{
$title['title'] = 'Shared';
$this->load->model('shared_model','shared');
$data['sharers'] = $this->shared->get($this->end_user->id);
$this->load->view('user/head_view', $title);
$this->load->view('user/header_view');
$this->load->view('user/navigation_view');
$this->load->view('user/shared_view', $data);
$this->load->view('user/footer_view');
}
Original View:
<?php foreach($sharers as $s): ?>
<li><?php echo $s ?></li>
<?php endforeach; ?>
Disclaimer: I'm new to web development, and I suck at associative arrays (apparently).
Your $data['sharers'] array doesn't have arrays as $values. Therefore, the way you are calling the $value[]'s in your foreach aren't working. You have no reason for calling the foreach at this point.
<div class="hide-on-phones">
<ul>
<li><a href="<?=base_url('user/shared/view/'.$sharers['shared_pk_id'])?>">
<?=$sharers['first_name'] . ' ' . $sharers['last_name']?>
</a>
</li>
</ul>
</div>
I expect you will later on fill an array with the data, in which case you can fill it as
$data['sharers'][] = array(
'shared_pk' => $this->shared->get($this->end_user->id),
'first_name' => $this->events->get($this->end_user->first_name),
'last_name' => $this->events->get($this->end_user->last_name)
);
Which, in turn can be looped using
<div class="hide-on-phones">
<ul>
<? foreach($sharers as $sharer): ?>
<li>
<a href="<?=base_url('user/shared/view/' . $sharer['shared_pk'])?>">
<?=$sharer['first_name'] . ' ' . $sharer['last_name']?>
</a>
</li>
<? endforeach; ?>
</ul>
</div>
I've figured it out. I needed to create an associative array in my model; not my controller. Thanks to everyone for your help!
Model:
class Shares_model extends crud_model {
public function __construct()
{
parent::__construct();
$this->pk = 'id';
$this->table_name = 'shares';
}
public function get($shared_to_user_id)
{
$this->db->where('shared_to_id', $shared_to_user_id);
$ids = parent::get_all();
$users = array();
foreach ($ids as $id)
{
$users[$id->owner_id]['owner_id'] = $id->owner_id;
$users[$id->owner_id]['owner_first_name'] = $id->owner_first_name;
$users[$id->owner_id]['owner_last_name'] = $id->owner_last_name;
}
return $users;
}
}
View:
<ul>
<?php foreach($sharers as $s): ?>
<li><?php echo $s['owner_first_name']." ".$s['owner_last_name'] ?></li>
<?php endforeach; ?>
</ul>
Controller:
public function index()
{
$title['title'] = 'Shared';
$this->load->model('shares_model','shares');
$data['sharers'] = $this->shares->get($this->end_user->id);
$this->load->view('public/head_view', $title);
$this->load->view('user/header_view');
$this->load->view('user/shared_view', $data);
$this->load->view('user/footer_view');
}
If we take your $data['sharers'] array and put in values for the php, then we would get something like this:
$data['sharers'] = array(
0 => array(
'id' => 1234,
'first_name' => 'John',
'last_name' => 'Doe'
),
1 => array(
'id' => 1235,
'first_name' => 'Jane',
'last_name' => 'Doe'
)
);
So, when you loop through this in your view, you need to access these correctly:
foreach($sharers as $key => $value):
// at this point, in the first iteration of the loop
// $key is 'id', or 'first_name', or 'last_name'
// and $value is 1234, or 'John', or 'Doe'
endforeach;
So, to loop through the sharers a bit easier, you just need to update your foreach a bit. At this point, change your view to this:
<div class="hide-on-phones">
<ul>
<?php foreach($sharers as $sharer): ?>
<li>
<a href="<?php echo base_url('user/shared/view/'.$sharer['shared_pk_id']) ?>">
<?php echo $sharer['first_name']. " " .$sharer['last_name'] ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>

Categories