I have a question about using form_dropdown().
The code below works, but i am unsure about if I have to do the new array in the view or is there a better way of doing it with the array $games - passed from $data['games']?
Should I be doing all the processing in the controller and sending over a ready array to populate the dropdown?
I tried this in the view: echo form_dropdown('games', $games); but got the error "Object of class stdClass could not be converted to string", I think it's because its an array of objects and I have to convert it?
TABLE: GAMES
GM_ID - int
GM_NAME - var
MODEL:
class Test_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_game_names()
{
$queryg = $this->db->query("SELECT * FROM games");
return $queryg->result();
}
}
CONTROLLER
class Test extends CI_Controller {
public function index()
{
$this->load->model('test_model');
$data['games'] = $this->test_model->get_game_names();
$this->load->view('view_test',$data);
}
}
VIEW
$this->load->helper('form');
echo form_open('send');
$list = array(); //is this the best way to do it??
foreach($games as $row)
{
$list[$row->GM_ID] = $row->GM_NAME; //is this the best way to do it??
}
echo form_dropdown('games', $list); //then pass this array?
echo form_close();
You are correct that it needs to be converted from an object to an array, the keys are your input values, and the array values are the text displayed in the <option> when you use form_dropdown(). The way you are doing it is fine, and I personally recommend it.
Reason: The form controls and HTML/text output are view logic. For instance, what if you want to do this instead?:
$list[''] = 'Please select a game';
foreach($games as $row)
{
$list[$row->GM_ID] = ucfirst(htmlspecialchars($row->GM_NAME));
}
That's just my perspective, it really doesn't matter too much, but usually as a rule - HTML and presentation logic should be in the view.
Aside: your function name get_game_names() is confusing because it returns more than just names. Also for simplicity's sake, you're using ActiveRecord so you can just do this:
function get_games()
{
return $this->db->get('games')->result();
}
Related
Hello i try do next logic
i have two class
abstract class Repository {
}
class HomeRepository extends Reposytory {
public function getMyAwesome() {
return array()
}
}
i dont wish get array, i wish get object, but i wish do some little magic,
i create hydrator class, his create object from array
now this seems like
public function getMyAwesome()
{
$awesomes = $this->adapter->table('awesome')->get();
$result = [];
foreach ($awesomes as $aw) {
$result[] = $this->hydrator->hydrate($aw);
}
return $result;
}
but i dont wish do this in child class, i wish enter this to parent, or gate
another word i wish see in my child class next code
public function getMyAwesome()
{
return $this->adapter->table('awesome')->get(); //MUST BE HYDRATED
}
How i can do that?
Okay, answer is very simple. Must use Proxy Class
How exactly does CI custome object works ?
As per CI documentation You can also pass a string to result() which represents a class to instantiate for each result object (note: this class must be loaded)
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $row)
{
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}
}
This is a very nice feature yet what Ci does is it will return an array of User objects and set attributes from row to it.
i have a problem with it that i want to have more control on what attributes to be publicly accessed and what to be modified before setting/getting.
how can i accomplish this ? can i tell CI to pass all attributes to constructor so that class can populate its own data ?
example class User
class User{
private $data=array();
protected $CI;
//public $id,$name,$dob,$gender,$role,$username,$password,$salt,$picture,$lastactive;
function __construct($data=null)
{
$this->data = $data; // i want to save data to a private var and allow attr. throu getters only
}
function set_password($p){
$this->generateSalt();
$this->data->password = $p.$this->data->salt;
}
}
In a nutshell::
I want to use custom_result_object but i dont want codeigniter to populate class attributes for me, instead i want the class to receive those attrs and populate it him self the way he this its appropriate.
I found your question while looking for a solution for myself.
After digging a bit in the documentation I managed to figure it out:
class user_item {
// you can declare all the attributes you want as private
private $id,$name,$dob,$gender,$role,$username,$password,$salt,$picture,$lastactive;
function __construct(){
// you can use the constructor to format data as needed
$this->username = strtouppper($this->username);
}
public function set_password($p){
$this->generateSalt();
$this->password = $p.$this->salt;
}
public function get_password(){
return $this->password;
}
}
Once set up, you can instantiate this class from $this->db->result()
class User_model extends CI_Model {
public function get_user($id){
return $this->db->get_where('users', array('id' => $id), 1)->result('user_item');
}
}
And call any public method or attribute of the class as needed
class Users extends CI_Controller {
function __construct(){
$this->load->model('user');
}
public function profile($user_id){
var $myUser = $this->user->get_user($user_id);
$myUser->set_password('myPassword');
echo $myUser->get_password();
}
}
I have simplified the code to make it clearer, but you get the idea.
this example controller using result array and object
if ($this->session->userdata('id_jurusan') ==1) {
$where=array('id_jurusan'=>$this->session->userdata('id_jurusan'));
$value = $this->session->userdata('id_jurusan');
$value2 = $this->session->userdata('username');
$data['rule']=$this->guru_mod->get_where($where,'forward_changing')->result();
$data['fuzzy']=$this->guru_mod->get_data_all('fuzzy')->result();
$data['artikel']=$this->guru_mod->get_data_all('artikel')->result();
$data['kondisi']=$this->guru_mod->get_where($where,'kondisi')->result();
$data['artikel2'] = $this->guru_mod->get_data_all2('artikel','id_jurusan',$value);
$data['riwayat_rule'] = $this->guru_mod->get_data_all2('forward_changing','username',$value2);
$data['kondisi_rule'] = $this->guru_mod->get_data_all2('kondisi','id_jurusan',$value);
$this->load->view('guru/daftar_rule',$data);
}
I thought about using an actual ORM like Doctrine, then I figured its download link was even broken...and all tutorials online dated back to 2011. Also I'll have to write yaml files.
Then I start off by trying to write my own model class in ORM style.
I just fill it up with fields and save it to database, which is easy.
But I encounter a problem trying to retrieve data from database.
class User extends CI_Model {
public $id;
public $email;
public $displayName;
public function save() {
.....
}
public function search_by_email($email) {
$user = new User();
$this->db->select('email')->from('user')->where('email', $email);
$result = $this->db->get();
if ($result->num_rows()==0) {
return false;
}else {
foreach ($result->result() as $field) {
}
}
}
I know normally in CodeIgniter, you return $query->result(), well as ORM custom, I'm trying to return an object...Is there a way to do this? What function should I use?
result takes a string that represents a class that it will instantiate and assigned the result data (each field as a property of the object):
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $row)
{
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}
regarding your comment, i'm pretty sure that codeigniter has no idea about anything regarding the class you pass to the result method. It looks like it just instantiates it and sets property and valuefor each column/value returned from the db:
$this->custom_result_object[$class_name][$i] = new $class_name();
foreach ($this->{$_data}[$i] as $key => $value)
{
$this->custom_result_object[$class_name][$i]->$key = $value;
}
One ORM that works quite well with codeIgniter is php-activerecord which is based off the rails active record model.
The function your trying to copy "search_by_email" is done through a
Late static binding method.
So you might see functions that are called like so:
Object::find_by_email()
Object::search_by_email()
im using codeigntier framework im trying to solve a problem to do with retrieving information from a database for example:
model.php:
public function read(){
$query = $this->db->get('table');
return $query->result();
}
controller.php:
public function doSomething () {
$exampleArray['name'] = "Bob's Database";
$getModel = $this->load->model('model','getData');
$modelData = $this->getData->read();
// i want to assign the the $modelData to a array element like so
$exampleArray['modelData'] = $modelData // here's where im stuck :(
}
thanks for your help!!
p.s. this is not an error, its just a question :)
}
If you want to be able to access $exampleArray outside of that method, you'll have to do one of two things:
a) set it as a class variable
class MyClass {
public $exampleArray;
.
.
.
}
then refer to it using
$this->exampleArray['index']
or b) pass it by reference into your doSomething() function:
public function doSomething(&$exampleArray) { ... }
The php manual has a section on variable scope that should help you better understand this.
I'm using codeigniter and in controller folder, I created a php file like :
NOTE: connects database automaticly.
<?php
class Book extends CI_Controller {
$query = $this->db->get('books');
foreach ($query->result() as $row) {
function $row->book_name() {
echo $row->book_name;
}
}
}
?>
I tried to create functions by fetching book names from the database but I can not. By using $variable in function name, is it possible to create function? If not, How can create it in a quick way? Thanks...
Absolutely.
$myfunction = function($a,$b,$c) {return $a+$b+$c;};
This is an example of an anonymous function. It has no name, but it can be accessed by $myfunction(1,2,3).
I'm not entirely sure what you're trying to do in your example... Should just echo $row->book_name alone be enough? Or are you trying to define a function with the same name as a book? In the latter case, you can use variable variables: ${$row->book_name} = function... - it's probably not a good idea though.
I think you may be interested in __call().
If a call is made to a method in a class that does not exist, the __call() method is invoked and you can handle the call from there.
Store the books in an array as you read the results, and add a __call method to your class. When the method is accessed, you can search the array for the book based on the name of the function called and act appropriately.
class Book extends CI_Controller {
protected $_books = array();
public function __construct() {
$query = $this->db->get('books');
foreach ($query->result() as $row) {
$this->_books[] = $row->book_name;
}
}
public function __call($name, $arguments) {
if (in_array($name, $this->_books)) {
echo $name;
} else {
ehco 'I do not have this book!';
}
}
}
Just keep in mind PHP's rules for naming methods, a valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. No spaces are allowed so keep that in mind.
Is it create_function() that you are searching for?
But seriously, it took me a minute to google it..