I am new in codeIgniter and I having a bit of trouble with my database and dropdown menu.
Here is my function to get the information I need...
protected $tbl_name = 'club';
public function get($id = 0, $object = TRUE)
{
// select * from users where id = 0
// check if id is provided
if($id) {
// id provided - retrieve a specific user
$query = $this->db->get_where($this->tbl_name, array('id' => $id));
// check if object type is requested
if($object) {
// object is requested
$data = $query->row();
}
else {
// array is requested
$data = $query->row_array();
}
}
else {
// id not provided - retrieve all users
$query = $this->db->get($this->tbl_name);
// check if object type is requested
if($object) {
// object is requested
$data = $query->result();
}
else {
// array is requested
$data = $query->result_array();
}
}
return $data;
}
Here is where I call it in my controller
$data['clubname'] = $this->club_model->get();
and this is in my view for the dropdown
<tr><td><?php echo form_label('Club Name: ', 'clubname'); ?></td><td><?php echo form_dropdown('clubname', $clubname['name']); ?></td><td><?php echo form_error('clubname'); ?></td></tr>
but I get these errors
A PHP Error was encountered
Severity: Notice
Message: Undefined index: name
Filename: individual/individual_club.php
Line Number: 7
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: helpers/form_helper.php
Line Number: 331
What Am I doing wrong?
The problem lies in your form_dropdown('clubname', $clubname['name']) call. The second parameter is wrong. form_dropdown expects an array. See the documentaiton
From your query's results, you would need to build an array of clubs. Something along the lines of :
// array is requested
$data = array();
foreach ($query->result_array() as $row)
{
$data[$row['club_id']] = $row['club_name'];
}
Replace club_id and club_name with your table's column names for the name and id of the clubs. After that, change your form_dropdown to form_dropdown('clubname', $clubname).
Like this, $clubname is an array of clubs.
Hope this helps!
Related
Trying to save data while open page but stuck at error :
"Method Illuminate\Database\Eloquent\Collection::save does not exist."
I have 2 database :
Buffalodata
Buffalomilkrecord
From 2nd table i need to get the avg of totalmilk and update the same to main database (1). This help me to show updated avgmilk data on dashboard front page.
Route:
Route:: get('buffalo-details', 'App\Http\Controllers\BuffalodataController#buffalodetails');
BuffalodataController Controller :
public function buffalodetails()
{
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')->pluck('buffaloID')->toArray();
foreach ($buffalidforavgmilk as $id )
{
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->sum('totalmilk');
$avgbuffalocount = Buffalomilkrecord::where('buffaloID',$id)->count();
$getavg = $milkperid / $avgbuffalocount;
$data = Buffalodata::find($buffalidforavgmilk);
$data->avgmilk = ($getavg);
$data->save ();
// dump([$milkperid,$avgbuffalocount,$getavg,$data,$id]);
}
return view ('pages.Buffalo.BuffaloDetails',[---------]);
}
Thanks again in Advance
When you pass an Array to ::find(), it returns a Collection, which doesn't have a save() method. This is your code:
// This is an Array of `buffaloID` values
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')->pluck('buffaloID')->toArray();
...
// `$data` is now a `Collection` of `Buffalodata` instances
$data = Buffalodata::find($buffalidforavgmilk);
// This now fails, as `Collection` doesn't have a `save()` method
$data->save();
You can rewrite your code as follows:
Buffalodata::whereIn('buffaloID', $buffalidforavgmilk)->update(['avgmilk' => $getavg]);
This will update all records in a single call. If you want to iterate, that's an option too:
$data = Buffalodata::find($buffalidforavgmilk);
foreach ($data as $record) {
$record->avgmilk = $getavg;
$record->save();
}
Or, since you have $id already:
$record = Buffalodata::find($id);
$record->avgmilk = $getavg;
$record->save();
I am trying to update data from the product table. But, when I try to update laravel, it gives me an error which says call to a member function fill() on array. When I debug $data I got an array of key and values.
I have the following code:
public function update(Request $request,Products $product)
{
$this->products = $this->products->find($product->id);
if(!$this->products){
request()->session()->flash('error','Product not found!');
return redirect()->route('product.index');
}
$rules = $this->products->getRules('update');
$this->products = $request->validate($rules);
$data = $request->all();
$data['added_by'] = $request->user()->id;
$data['image'] = explode(',',$data['related_images'])[0];
$this->products->fill($data); //Getting error here
$status = $this->products->save();
if($status){
$request->session()->flash('success','Product updated successfully.');
} else {
$request->session()->flash('error','Sorry! there was problem updating product.');
}
return redirect()->route('product.index');
}
I want the fill() function to work so that it can update my data on the product table.
The line below is overwriting your products with an array of the keys that passed validation. You can fix it by removing the assignment (if there are errors, a 422 error will still be returned)
$this->products = $request->validate($rules);
// change to
$request->validate($rules);
I am working in Codeigniter and I want to hide ID from URL.
my current URL is:
www.localhost/CI/services/1/ac_repair
but need this type of URL in codeigniter:
www.localhost/CI/services/ac_repair
View Page Code:
<?=anchor('services/' . $ser->s_id . '/' . url_title($ser->s_title,'_') ,'View Service');?>
Controller Code:
public function services()
{
$this->load->model('ServicesModel', 'ser_model');
$s_id = $this->uri->segment(2, 0);
if($s_id){
$get_service = $this->ser_model->get_ser($s_id);
return $this->load->view('public/detail', compact('get_service') );
}
else
{
// $services = $this->articles->articles_list( $config['per_page'], $this->uri->segment(3) );
$get_services['result'] = $this->ser_model->all_services_list();
// $this->load->view('public/services', ['services'=>$services]);
$this->load->view('public/services', $get_services);
}
}
Model Code here:
public function get_ser($id)
{
// $q = $this->db
$q = $this->db->select('*')
->from('services')
->where( ['s_id' => $id] )
->get();
if ( $q->num_rows() )
return $q->row();
return false;
}
but need this type of URL in codeigniter:
www.localhost/CI/services/ac_repair
If you want this functionality you have to be able to use your title ac_repair in place of the id. This means the title needs to be marked as unique and therefore not contain any duplicates.
The following pseudo-code should give you an idea:
function services($url_title = null) {
if (!is_null($url_title)) {
// get ser would use title instead of $id
$this->db->where('title', $url_title);
} else {
// all rows
}
}
Other methods would be "hacky" and I cannot think of any off the top of my head that I would consider usable.
Side note: you should never be returning in a view
i am trying to update this and shows Trying to get property of non-object .how to solve this can anybody help me
$data['dotdprod'] = $this->Product_model->get_products($data['dotdcat']->id, '5', '0', 'sort_price', 'ASC');
and model is:
function get_products($category_id = false, $limit = false, $offset = false, $by=false, $sort=false)
{
//if we are provided a category_id, then get products according to category
if ($category_id)
{
$this->db->select('category_products.*, products.*, LEAST(IFNULL(NULLIF(saleprice, 0), price), price) as sort_price', false)->from('category_products')->join('products', 'category_products.product_id=products.id')->where(array('category_id'=>$category_id, 'enabled'=>1));
$this->db->order_by($by, $sort);
$result = $this->db->limit($limit)->offset($offset)->get()->result();
return $result;
}
else
{
//sort by alphabetically by default
$this->db->order_by('name', 'ASC');
$result = $this->db->get('products');
return $result->result();
}
}
There error is warning you that you are trying to access a property on something that doesn't have properties.
When you try to access $data['dotdcat']->id, this assumes that $data['dotdcat'] is an object. If it isn't, then the error you see is thrown.
I'm not sure where the error is thrown, but anywhere you are using the arrow operator -> - php assumes the left side of that operator is an object.
I have a problem related to CActiveForm::validate(). I have a form and and sending data to database using Ajax, my form contains a multiple selectable drop-down list. In data saving section of controller produced the following error initially
mb_strlen() expects parameter 1 to be string, array given (.../framework/validators/CStringValidator.php:84)
and after updating framework to newer version, that error gone, and got the below validation message instead.
Category Ids is invalid.
If the form is fully filled(I mean all the rules in the model satisfied), it will not produce any such bug or error message.
controller action
public function actionCompany() {
$model = new Company;
if (isset($_POST['Company'])) {
$model->attributes = $_POST['Company'];
$category_ids = "";
if (is_array($_POST['Company']['category_ids']))
$category_ids = implode(',', $_POST['Company']['category_ids']);
$model->category_ids = $category_ids;
if ($model->validate()) {
/*$temp = Company::model()->findByPK($model->id);
if ($temp !== null) {
$model = $temp;
}*/
$model->save();
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
} else {
$error = CActiveForm::validate($model);
if ($error != '[]')
echo $error;
}
}
}
Model rules
public function rules()
{
return array(
array('...., category_ids,...', 'required'),
array('..., category_ids, ...', 'length', 'max'=>255),
....
.....
array('...., category_ids,...', 'safe', 'on'=>'search'),
);
}
What is actually I'm missing?
By default, CActiveForm::validate($model) loads the model attributes from $_POST and overrides current attribute values, thus destroying your transformed values. Pass false as the third argument to avoid this.