How To Insert and Update Data From Same Form using Codeigniter - codeigniter

Can Anyone Help me to write Controller,Model and View From Which There Would Be a Single form(View) That takes the Hidden Id and Controller Checks whether The Request From View have id or not and depending upon that it would insert and update the same.

Basically you just have to check if the hidden id exists in your database or not. If it doesn't then you insert, if it does you update. Generally this is how you do it:
<?php
class some_controller extends CI_Controller {
/**
* Submits the form
*
* #return boolean
*/
public function submit_form() {
$id = $this->input->post('id');
$data = array(
'somedata' => $this->input->post('somedata'),
'someotherdata' => $this->input->post('someotherdata')
);
$this->load->model('some_model');
if (!is_null($id) && $this->some_model->id_exists($id)) {
return $this->db->update('sometable', array('id' => $id), $data);
} else {
// assumes sometable autoincrements id
// otherwise $data = array_merge(array('id' => $id), $data);
return $this->db->insert('sometable', $data);
}
}
}
class some_model extends CI_Model {
/**
* Checks if id exists in sometable
*
* #return boolean TRUE if item with $id exists in sometable
*/
public function id_exists($id) {
$this->db->where('id', $id);
return $this->db->count_all_results('sometable') > 0;
}
}
Please note: good practice would call for moving the insert and update (in fact all queries) into a model. This is just an example.

Related

Eloquent relationship returning all when ID doesn't match

For some reason my relationship is fetching all from the corresponding table when I dump it, however dumping the result does not show these rows.
The slider ID does not match the slider_id within the settings table.
So the following works fine, as expected the settings is an empty array:
/**
* #return HasOne
*/
public function slider(): HasOne
{
return $this->hasOne(Slider::class)->withDefault(
(new Slider())->attributesToArray()
);
}
Result:
{
"name": "media-slider",
"settings": []
}
However when I dump within the attribute I get all the rows from the settings table, when this query should be getting all settings where the slider_id matches the current slider, which has a different ID.
<?php
namespace App\Models\Media;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
class Slider extends Model
{
/** #var string[] */
protected $appends = [ 'settings' ];
protected $defaults = [
'test' => [
'id' => 0,
'name' => 'default name',
]
];
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->attributes = $this->defaults['test'];
}
/**
* #return HasMany
*/
public function settings(): HasMany
{
return $this->hasMany(SliderSetting::class);
}
/**
* Get the slider settings, extract the value and key by the key, also
* group if multiple setting groups are required.
*
* Perform this logic here so data can be used directly by the JavaScript.
*
* #return \Illuminate\Database\Eloquent\Collection|Collection
*/
public function getSettingsAttribute()
{
dd($this->settings()->get()); // This should be empty!
return $this->settings()->get()
->groupBy('group')
->map(static function ($group) {
$group = $group->keyBy('key');
return $group->map(static function ($setting) {
return $setting->getAttribute('value');
});
});
}
}
Edit
/**
* #return HasMany
*/
public function sliderSettings(): HasMany
{
dd($this->hasMany(SliderSetting::class)->toSql());
return $this->hasMany(SliderSetting::class);
}
The above outputs:
select * from slider_settings
Shouldn't it be the following?
select * from slider_settings where slider_settings.slider_id = ?

yii2 get activerecords by relation column

I need to select ActiveRecord's that have related AR's with specific column value.
Situation: 'User' may have many 'Branches' - via junction table, and Branch is related to Department. I have department_id, and I want to select Users, that have branches from this single Department.
Department:
... $this->hasMany(Branch::className(), ['department_id' => 'id']);
Branch:
... $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('{{%user_to_branch}}',['branch_id' => 'id']);
The thing is, that I do not want to access this from Department in any way (e.g. $department->getUsers()....), but i want to define this in ActiveQuery.
So i could select Users like:
User::find()->fromDepartment(5)->all();
THANK YOU in advance !
In ActiveRecord:
/**
* #inheritdoc
* #return MyActiveRecordModelQuery the active query used by this AR class.
*/
public static function find()
{
return new MyActiveRecordModelQuery(get_called_class());
}
MyActiveRecordModelQuery:
/**
* #method MyActiveRecordModelQuery one($db = null)
* #method MyActiveRecordModelQuery[] all($db = null)
*/
class MyActiveRecordModelQuery extends ActiveQuery
{
/**
* #return $this
*/
public function fromDepartment($id)
{
$this->andWhere(['departament_id' => $id]); //or use relation
return $this;
}
}
Usage:
MyActiveRecordModelQuery::find()->fromDepartment(5)->all();
User model method
public function getBranch()
{
return $this->hasMany(Branch::className(), ['id' => 'branch_id'])
->viaTable('{{%user_to_branch}}', ['user_id' => 'id']);
}
public static function fromDepartment($id)
{
$query = self::find();
$query->joinWith(['branch'])
->andWhere(['department_id'=>$id]);
return $query->all();
}
Usage:
User::fromDepartment(5);

Yii - validate custom field

I use model which not contain attribute 'countries' because I'm saving it in relations-model via many-to-many relation. When I'm creating form in view I use multiple select for custom field 'countries'. How can I validate it from model on $model->validate()?
// protected/extensions/validators/CountryValidator.php
class CountryValidator extends CValidator
{
/**
* #inheritdoc
*/
protected function validateAttribute($object, $attribute)
{
/* #var $object CFormModel */
// for example check exist countryId in db or no
// you can use any other logic
$country = Country::model()->findByPk($object->$attribute);
if (null != $country) {
$object->addError($attribute, 'country not found');
}
}
...
// in your model
public function rules()
{
return array(
array('countryId', 'ext.validators.CountryValidator'),
...
// in config
'import' => array(
'ext.validators.*',
...
How to use:
$yourModel = new YourModel();
$yourModel->countryId = -1;
$yourModel->validate();
print_r($yourModel->getErrors()); die();

pivot table in laravel 4 insertion

hey guys im new in laravel and i was trying to insert into my pivot table. i have this structure in my database
the departments table belongs to many categories and same as category so i have this models
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Departments extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'departments';
protected $fillable = ['department_name'];
public $timestamps = false;
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
public function categories()
{
return $this->belongsToMany('Categories');
}
}
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Categories extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'categories';
protected $fillable = ['name'];
public $timestamps = false;
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
public function department()
{
return $this->belongsToMany('Departments');
}
}
then i have a query in my controller like this
$messages = array(
'required' => 'Please Fill the required field',
'unique' => 'Name Already exist'
);
$catName = Input::get('categoryName');
$deptId = Input::get('deptId');
$validation = Validator::make(Input::all(),[
'categoryName' => 'required|unique:categories,name' ], $messages);
if($validation->fails()){
return array('error' =>$validation->messages()->all() );
}else{
$findDepartment = Departments::find($deptId);
$saveCat = $findDepartment->categories()->insert(array('name' => $catName));
}
but then when i checked the tables it adds up on the categories table but nothing is added in the category_department. do i miss any codes? and also i had an error last time I was trying to migrate my pivot table the error was this.
can you help me guys on what i am missing? tnx for the help in advanced.
First, you should name your model classes as singular: Category, Department.
Then try to declare your relationships with the pivot table name:
public function categories()
{
return $this->belongsToMany('Category', 'category_department');
}
and
public function departments()
{
return $this->belongsToMany('Departments', 'category_department');
}
now, to insert new data, try attach:
$findDepartment = Department::find($deptId);
$category = Category::where('name', '=', $catName)->first();
$saveCat = $findDepartment->categories()->attach($category->id);

Can't make a new Insertion - Laravel Eloquent ORM

I can't Insert into this table and this drives me crazy
This is the error Msg I get
var_export does not handle circular references
open: /var/www/frameworks/Scout/vendor/laravel/framework/src/Illuminate/Database/Connection.php
* #param Exception $e
* #param string $query
* #param array $bindings
* #return void
*/
protected function handleQueryException(\Exception $e, $query, $bindings)
{
$bindings = var_export($bindings, true);
$message = $e->getMessage()." (SQL: {$query}) (Bindings: {$bindings})";
Here is my Full Mode
<?php
namespace Models;
use Illuminate\Database\Eloquent\Collection;
class Student extends \Eloquent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'students';
/**
* The rules used to validate new Entry.
*
* #var array
*/
protected $newValidationRules = array(
'studentCode' => 'unique:students,code|numeric|required',
'studentName' => 'required|min:2',
'dateOfBirth' => 'date',
'mobile' => 'numeric'
);
/**
* Relation with sessions (Many To Many Relation)
* We added with Created_at to the Pivot table as it indicates the attendance time
*/
public function sessions()
{
return $this->belongsToMany('Models\Session', 'student_session')->withPivot('created_at')->orderBy('created_at', 'ASC');
}
/**
* Get Student Subjects depending on attendance,
*/
public function subjects()
{
$sessions = $this->sessions()->groupBy('subject_id')->get();
$subjects = new Collection();
foreach ($sessions as $session) {
$subject = $session->subject;
$subject->setRelation('student', $this);
$subjects->add($subject);
}
return $subjects;
}
/**
* Insert New Subject
* #return Boolean
*/
public function insertNew()
{
$this->validator = \Validator::make(\Input::all(), $this->newValidationRules);
if ($this->validator->passes()) {
$this->name = \Input::get('studentName');
$this->code = \Input::get('studentCode');
if ($this->save()) {
return \Response::make("You have registered the subject successfully !");
} else {
return \Response::make('An Error happened ');
}
} else {
Return $this->validator->messages()->first();
}
}
}
I am just trying to insert a new row with three Columns (I call the insertNew function on instance of Student)
1- ID automatically incremented
2- Special Code
3- Name
And I got this above Msg
What's I have tried till now :
removing all relations between from this model and other models
that has this one in the relation
Removed the validation step in insertNew()
Removed the all Input class calls and used literal data instead.
note that I use similar Inserting function on other Models and it works flawlessly
Any Comments , Replies are appreciated :D
Solution
I solved it and the problem was that I am accessing the validator
$this->validator = \Validator::make(\Input::all(), $this->newValidationRules);
And it was because I forgot that
/**
* The validator object.
*
* #var Illuminate\Validation\Validator
*/
protected $validator;
I had a similar problem. But to me, changing this code:
if ($this->validator->passes()) {
$this->name = \Input::get('studentName');
$this->code = \Input::get('studentCode');"
to this:
if ($this->validator->passes()) {
$this->setAttribute ("name" , \Input::get('studentName'));
$this->setAttribute ("code" , \Input::get('studentCode'));"
solved it.

Resources