i already tried different ways and some post here
the 1st data is working savings to acadans_tbl but the update who's user login is not working.
view_file
<td><input type="text" name="assessval" id="assessval" value="1"></td>
Controller
$data1 = array(
'Studnum' => $this->session->userdata['snum'],
'Department' => $this->session->userdata['dept'],
'Course' => $this->session->userdata['course'],
'answer1' => $this->input->post('answer1'),
'answer2' => $this->input->post('answer2'),
'answer3' => $this->input->post('answer3'),
'answer4' => $this->input->post('answer4'),
'answer5' => $this->input->post('answer5'),
'answer6' => $this->input->post('answer6'),
'answer7' => $this->input->post('answer7'),
'answer8' => $this->input->post('answer8'),
'answer9' => $this->input->post('answer9'),
'answer10' => $this->input->post('answer10')
);
$data2 = array(
'assessval' => $this->input->post('assessval')
);
if ($this->Questions_model->create_ans($data1, $data2)) {
MODEL
public function create_ans($data1, $data2) {
$this->db->insert('acadans_tbl', $data1);
$data2['assesed'] = $this->db->insert_id();
$this->db->insert('users', $data2);
}
In your Controller, you write:
$data2 = array(
'assessval' => $this->input->post('assessval')
);
Its mean that you will insert the value from $this->input->post('assessval') to field assessval in the database. So, you have to ensure in the users table you have assessval field.
And in your model, just insert to the database:
$this->db->insert('users', $data2);
Related
I have 3 tables (2 + pivot) :
categories
id
admin_id
created_at
updated_at
deleted_at
langs
id
langname_fr
langname
....
lang_sector
lang_id
sector_id
sectname
sectshortname
....
I created a form which allow to create several entries depending the number of languages i defined ...
{!! Form::open( array('route' => 'maps.store','method' => 'POST') ) !!}
<fieldset>
<legend>Nom du secteur</legend>
#foreach($langs as $lang)
<div class="form-group m-form__group">
{{ Form::label( 'Nom du secteur en ' . $lang->langname_fr) }}
{{ Form::text('sectname_lang_' . $lang->id, '' , [ 'class' => 'form-control m-input' ]) }}
</div>
<div class="form-group m-form__group">
{{ Form::label( 'Nom abrégé du secteur en ' . $lang->langname_fr ) }}
{{ Form::text('sectshortname_lang_' . $lang->id, '', [ 'class' => 'form-control m-input' ]) }}
</div>
#endforeach
</fieldset>
...
{!! Form::close() !!}
If i want to create an entry in my database, i have to create several entries ...
public function sectorCreate(Request $request) {
Sector::create(array(
'admin_id' => Auth::guard('admin')->user()->id,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
));
$sector = Sector::all()->last();
$sector_id = Sector::all()->last()->id;
$countLang = Lang::count();
for ($i = 1; $i <= $countLang; $i++) {
$insertSector[$i] = $sector->langs()->attach(
$sector_id,
[
'lang_id' => $i,
'sectname' => $request->input('sectname_lang_' .$i),
'sectname_slug' => Str::slug($request->input('sectname_lang_' .$i)),
'sectshortname' => $request->input('sectshortname_lang_' .$i),
'sectdescription' => $request->input('sectdescription_lang_' .$i),
'sectshortdescription' => $request->input('sectshortdescription_lang_' .$i),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
'deleted_at' => NULL
]
);
}
return redirect()->route('admin.home')->with('success', 'Secteur créé');
}
Now my issue is to know how i can update the values of the database and to delete the entry ... I tried to read the documentation but i'm not sure i understood it.
For example
lang_id sector_id sectname sectshortname
-------------------------------------------------------
1 1 longname1 shortname1
2 1 longname2 shortname2
After update i would like to update sectname and sectshortname ... I have made several trials using sync, syncWithoutDetaching and updateExistingPivot without success...
I also add constraints by considering lang_id and sector_id as a primary key ...
UPDATE ----------------------------------------------------------
I modified the update method using sync and syncWithoutDetaching
public function update(Request $request, $id)
{
$sector = Sector::findOrFail($id);
$countLang = Lang::count();
$langs = Lang::all();
foreach ($langs as $lang) {
$lang_id = $lang->id;
}
for ($i = 1; $i <= $countLang; $i++) {
$insertSector[$i] = $sector->langs()->sync(
$sector->id,
$lang_id,
[
'sectname' => $request->input('sectname_lang_' .$i),
'sectname_slug' => Str::slug($request->input('sectname_lang_' .$i)),
'sectshortname' => $request->input('sectshortname_lang_' .$i),
'sectdescription' => $request->input('sectdescription_lang_' .$i),
'sectshortdescription' => $request->input('sectshortdescription_lang_' .$i),
'updated_at' => Carbon::now(),
'deleted_at' => NULL
]
);
}
return $insertSector;
//return redirect()->route('maps.index')->with('success', 'updated');
}
The Documentation states the following:
When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:
$user->roles()->attach($roleId, ['expires' => $expires]);
You got this part correct. Now for updating (and or deleting):
Deleting
$user->roles()->detach([1, 2, 3]);
This removes associated records and clears the intermediate table.
Syncing Associations
You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:
$user->roles()->sync([1, 2, 3]);
You may also pass additional intermediate table values with the IDs:
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
If you do not want to detach existing IDs, you may use the syncWithoutDetaching method:
$user->roles()->syncWithoutDetaching([1, 2, 3]);
Conclusion
Use sync, and set the attributes again. If you just want to update a few records, use the syncWithoutDetaching.
Update
Change your update code to this:
$insertSector[$i] = $sector->langs()->sync(
$lang_id =>
[
'sectname' => $request->input('sectname_lang_' .$i),
'sectname_slug' => Str::slug($request->input('sectname_lang_' .$i)),
'sectshortname' => $request->input('sectshortname_lang_' .$i),
'sectdescription' => $request->input('sectdescription_lang_' .$i),
'sectshortdescription' => $request->input('sectshortdescription_lang_' .$i),
'updated_at' => Carbon::now(),
'deleted_at' => NULL
]
);
You passed both the sector->id and the $lang_id where you only needed to pass the $lang_id with attributes for the intermediate table.
Finally thanks to Douwe de Haan i finally solved my issue for creating an entry with pivot table ... i guess i understood a little bit how it work now
Here is the method :
public function store(Request $request)
{
Sector::create(array(
'admin_id' => Auth::guard('admin')->user()->id,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
));
$sector = Sector::all()->last();
$countLang = Lang::count();
$langs = Lang::all();
foreach ($langs as $lang) {
$lang_id[] = $lang->id;
}
for ($i=0 ; $i < $countLang; $i++) {
$insertSector[$i] = $sector->langs()->syncWithoutDetaching(
[$lang_id[$i] =>
[
'sectname' => $request->input('sectname_lang_' .$lang_id[$i]),
'sectname_slug' => Str::slug($request->input('sectname_lang_' .$lang_id[$i])),
'sectshortname' => $request->input('sectshortname_lang_' .$lang_id[$i]),
'sectdescription' => $request->input('sectdescription_lang_' .$lang_id[$i]),
'sectshortdescription' => $request->input('sectshortdescription_lang_' .$lang_id[$i]),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
'deleted_at' => NULL
]
]
);
}
return redirect()->route('maps.index')->with('success', 'Secteur créé');
}
For updating :
public function update(Request $request, $id)
{
$sector = Sector::findOrFail($id);
$countLang = Lang::count();
$langs = Lang::all();
foreach ($langs as $lang) {
$lang_id[] = $lang->id;
}
for ($i=0 ; $i < $countLang; $i++) {
$insertSector[$i] = $sector->langs()->updateExistingPivot(
$lang_id[$i],
[
'sector_id' => $request->input('sector_id'),
'sectname' => $request->input('sectname_lang_' .$lang_id[$i]),
'sectname_slug' => Str::slug($request->input('sectname_lang_' .$lang_id[$i])),
'sectshortname' => $request->input('sectshortname_lang_' .$lang_id[$i]),
'sectdescription' => $request->input('sectdescription_lang_' .$lang_id[$i]),
'sectshortdescription' => $request->input('sectshortdescription_lang_' .$lang_id[$i]),
'updated_at' => Carbon::now(),
'deleted_at' => NULL
]
);
}
return $insertSector;
//return redirect()->route('sectors.index')->with('success', 'Secteur mis à jour');
}
I am using Codeigniter 3.x and want to see an update_batch query, but not run it, while I am debugging the code.
This works for an update_batch:
$this->db->update_batch("`" . $this->fullGamesTable . "`", $fullGames, 'gameid');
and updates the database, but I want to view the update and not actually do the update.
Thanks.
Can you do like this
$data = array(
array(
'opt_id' => $hoptid1,
'q_id' => $hid,
'opt_val' => $sin_yes,
'opt_crct' => $sin_yescrt,
'opt_mark' => '1'
),
array(
'opt_id' => $hoptid2,
'q_id' => $hid,
'opt_val' => $sin_no,
'opt_crct' => $sin_nocrt,
'opt_mark' => '1'
)
);
$this->db->update_batch('option', $data, 'opt_id');
Try this
public function update_batch()
{
$data = $this->db->select('id,description')->from('insert_batch')->group_by('url')->get()->result_array();
$batch_update = [];
foreach ($data as $key => $value) {
$value['description'] = 'description';
$batch_update[] = [
'id' =>$value['id'],
'description' => $value['description']
];
}
echo "<pre>"; print_r($batch_update);
$this->db->update_batch('insert_batch',$batch_update,'id');
}
Can anyone help on editable column in gridview.I am using Yii2 and stuck with it.
I can't save data in my model.I can post from gridview column.
In my grid view:
$gridColumns= [
'patient_no',
'category_name',
'sdv_text',
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'sdv_status',
'pageSummary' => true,
'editableOptions'=> [
'header' => 'profile',
'format' => Editable::FORMAT_BUTTON,
'inputType' => Editable::INPUT_DROPDOWN_LIST,
'data'=> $StatusList,
]
],
// 'date_sdv_performed',
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'date_sdv_performed',
'editableOptions' => [
'header' => 'Date Sdv Performed',
'inputType'=>\kartik\editable\Editable::INPUT_WIDGET,
'format'=>\kartik\datecontrol\DateControl::FORMAT_DATE,
'widgetClass'=> 'kartik\datecontrol\DateControl',
],
],
[
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'comments',
'hAlign' => 'top',
'vAlign' => 'middle',
'width'=>'100px',
'headerOptions' => ['class' => 'kv-sticky-column'],
'contentOptions' => ['class' => 'kv-sticky-column'],
'pageSummary' => true,
],
];
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout'=>"{items}\n{pager}",
'pjax'=>true,
'toolbar' => [
'{export}',
'{toggleData}'
],
'responsive'=>true,
'hover'=>true,
'columns' => $gridColumns
]);
In my controller action:
public function actionMonitoring($site_name)
{
$this->layout = 'sdv-carolina-main';
$Countries = new Countries;
$model = new Flagging;
$searchModel = new FlaggingSearch();
$dataProvider = $searchModel->monitoringsearch($site_name);
$allocatedsites = new AllocatedSites;
if (Yii::$app->request->post('hasEditable'))
{
$model = $this->findModel($model['flagging_id']);
$out = Json::encode(['output'=>'', 'message'=>'']);
$post = [];
$posted = current($_POST['Flagging']);
$post['Flagging'] = $posted;
if ($model->load($post)) {
$model->save();
$output = '';
if (isset($posted['sdv_status']))
{
$output = $model->sdv_status;
}
$out = Json::encode(['output'=>$output, 'message'=>'']);
}
echo $out;
return;
}
return $this->render('monitoring',
[
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'Countries' => $Countries,
'model'=>$model,
'allocatedsites' => $allocatedsites,
]);
}
The problem is I can't update my model because of I can't get the id.
I just need the id to update specific row.How can I get the id while using editable column?
Thanks in advance.
Actually the solution is easy. I just need the id of that specific row to update that.And in my ajax post I got something like this:
Flagging[0][status] NO
_csrf TlhyUm5kajAoNxgVNy0/ZCoyHApZUlNUFh0rB1gRPGoAFSIdGSAifQ==
editableIndex 0
editableKey 13
hasEditable 1
and found the editableKey is the id of that specific row!
Now in my controller I write down this code given below:
$_id=$_POST['editableKey'];
$model = $this->findModel($_id);
Here $_id is the posted editableKey value which is the id of the specific row.
and with the id I use it to get the specific model and just update data based on that id.
I have the following query
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
How would i return the id of the row just inserted?
Cheers,
Instead of doing a raw query, why not create a model...
Call it Conversation, or whatever...
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
Which will return an id...
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
This method requires that the id of the table be auto-incrementing, so watch out for that...
The last method, is that you can just return the last inserted mysql object....
Like so...
$result = DB::connection('mysql')->pdo->lastInsertId();
So if you choose that last road...
It'll go...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question.
Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
You can use DB::getPdo()->lastInsertId().
Using Eloquent you can do:
$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;
$new->save();
$the_id = $new->id; //the id of created row
The way I made it work was I ran an insert statement, then I returned the inserted row ID (This is from a self-learning project to for invoicing):
WorkOrder::create(array(
'cust_id' => $c_id,
'date' => Input::get('date'),
'invoice' => Input::get('invoice'),
'qty' => Input::get('qty'),
'description' => Input::get('description'),
'unit_price' => Input::get('unit_price'),
'line_total' => Input::get('line_total'),
'notes' => Input::get('notes'),
'total' => Input::get('total')
));
$w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
return $w_id;
When my model goes to validate my form
it always come as false,
it doesn't save in the database.
I dont understand why this isn't working, it was working until I unbind on a few of my functions.
Here is my invoice model, it's supposed to check if there is to/biller in relationships_users table (relationship model).
<?php
class Invoice extends AppModel{
var $name='Invoice';
public $belongsTo = array(
'Relationship' =>array(
'className' => 'Relationship',
'foreignKey' =>'relationship_id',
)
);
var $validate = array(
'to' => array(
'relationshipExists' => array(
'rule' => array(
'relationshipExists'),
'message' => 'sorry you dont have a relationship with that user.'
),
),
);
public function relationshipExists($check){
$relationshipExists=$this->Relationship->find('count', array(
'conditions' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
// get the value from the passed var
)
)
);
if ($relationshipExists>0) {
return TRUE;
}
else
return FALSE;
}
Here is my function in the invoices table
public function addinvoice(){
$this->set('title_for_layout', 'Create Invoice');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
if($this->request->is('post')){
($this->Invoice->set($this->request->data));
if($this->Invoice->validates(array('fieldList'=>array('to','Invoice.relationshipExists')))){
$this->Invoice->save($this->request->data);
$this->Session->setFlash('The invoice has been saved');
}}else {
$this->Session->setFlash('The invoice could not be saved. Please, try again.');
}
}
What it's supposed to do is to check that to/biller are in the relationships_users table and then save the invoice to the invoice table, otherwise throw a message.
The conditions array seems strange to me:
'conditions' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
// get the value from the passed var
)
That would search for Relationships with both partyone and partytwo set to to. You probably want to check if either of them is set to to:
'conditions' => array(
'OR' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
)
// get the value from the passed var
)