Update status column on basis of multiple id in one table - javascript

i have subjects table with status column and parent_id column so from view page if i click on active button change the status to active/inactive..
So now if i click on subject active button it should change status of that child subjects too..
here is my code:
public function updateStatus(subject $subject)
{
$subject_id = $subject->id;
$subjects = Subject::where(['parent_id' => $subject_id])->get();
$subjects->status = !$subjects->status;
$subjects->save();
return redirect()->route('subject.index');
}
I am storing the main id in parent_id column.So if i change status of main id it should change status of related parent_id column status also. if it is 1 it should change to 0. if it is 0 it should change to 1.
Can anyone help me to solve this..TIA

If I understood correctly, first, you need to add parent data to your query:
$subjects = Subject::where('parent_id', $subject_id)->orWhere('id', $subject_id)->get();
Since this is a collection, you should create a loop to update each item. BTW, Laravel may have a built-in function for this, but I don't know.
foreach($subjects as $subject) {
$subject->update([
'status' => !$subject->status
]);
}

All you have to do is execute two queries, one for update status 0 where status is 1 :
Subject::where('parent_id', $subject_id)->where('status', 1)->update(['status' => 0]);
and other for change status 0 to 1 for the id you received
Subject::where('parent_id', $subject_id)->where('status', 0)->update(['status' => 1]);
So finally your code will be look like :
public function updateStatus(subject $subject)
{
$subject_id = $subject->id;
$subject = Subject::where('parent_id', $subject_id)->where('status', 1)->update(['status' => 0]);
$subject = Subject::where('parent_id', $subject_id)->where('status', 0)->update(['status' => 1]);
return redirect()->route('subject.index');
}

Related

Pass variable with subvariable from JQuery to Flask app

I have a Flask that uses WTForms and Jquery to take from the user "input" fields in a form and shows "select" fields to the user. Jquery is used to filter the select fields shown to the user based on what they enter in the input fields. In order to filter the select fields, I need to take what the user enters in the input fields and send it to the Flask app.
These are the form fields -
class TableName(FlaskForm):
schema = StringField('Schema', validators=[DataRequired()], id = 'schema_name')
table = StringField('Table', validators=[DataRequired()], id = 'table_name')
class QaForm(FlaskForm):
test_table_in = FormField(TableName, id = 'test_table')
prod_table_in = FormField(TableName, id = 'prod_table')
This is the JQuery -
$(function() {
var tables = {
test_table: $('test_table_in-schema_name').val() + "." + $('test_table_in-table_name').val(),
prod_table: $('prod_table_in-schema_name').val() + "." + $('prod_table_in-table_name').val()
};
var fields = {
test: [$('#select_test_join_key'), $('#select_test_dimensions')],
prod: [$('#select_prod_join_key'), $('#select_prod_dimensions')]
};
fields.test.forEach(item => updateFields(tables.test_table, item));
fields.prod.forEach(item => updateFields(tables.prod_table, item));
function updateFields(table, field) {
var send = {
table: tables.table
};
$.getJSON("{{url_for('_get_fields') }}", send, function(data) {
//do something
});
}
});
When the user enters a "test_table", the test table should get passed to _get_fields() and when the user enters a prod_table, that value should get sent to _get_fields(). Test_table and prod_table are two form fields, each consisting of two subfields, "schema" and "table" that are combined to create one field in the format "schema.table".
Function _get_fields() in Flask view to receive the table name -
#app.route('/_get_fields/')
def _get_fields():
table = request.args.get('table', type=str)
fields_query = f"""select column_name AS Fields from information_schema.columns WHERE
table_name = '{table}' group by 1 limit 10;"""
conn.execute(fields_query)
result = conn.fetchall()
return jsonify(result)
Potential errors:
It's the request_args.get() function in the Flask view that I believe is not referring correctly to the JQuery variables. I've tried 'test_table', 'prod_table', and others but none of these have worked so far. I'm using the "name" of the input form elements to create the table variables - I'm wondering if that may be a part of the issue as well. Any thoughts or suggestions?

ForkJoin() issue on Angular

Hello I am currently working on an UI and I need to print for each 'digId' a value that I retrieved in an unique JSON response.
In the case below, I have 3 incidents and I did a fork to have access to the 3 JSON response.
digId='4149';
digId2='4719';
digId3='4309';
ngOnInit(): void {
const parallel$ = Observable.forkJoin(
this.http.get('http://ninjaopsapi?tablename=REF_OPS_ALARM&babylonref=' + this.digId),
this.http.get('http://ninjaopsapi?tablename=REF_OPS_ALARM&babylonref=' + this.digId2),
this.http.get('http://ninjaopsapi?tablename=REF_OPS_ALARM&babylonref=' + this.digId3)
);
parallel$.subscribe( data => {
this.alarms = data, console.log(data);
})
}
My goal is to print the element circled in blue for example: Capture
But with this code below in my html, I retrieve the element [0] for the three incidents and I can't put an additionnal [0] to select only one.
<div *ngFor= "let alarm of alarms">
<div [(ngModel)]="digId" ngDefaultControl>
<div>{{alarm[0].alertMessage}}</div>
</div>
</div>
Is it possible to print the first element of the first element in an array when the .subscribe is done with a "forkJoin()" ?
Thank you
UPDATE
I only changed {{alarm[0][0].alertMessage}} by {{alarms[0][0].alertMessage}} and delete the loop *ngFor="let alarm of alarms
and it works well ! Thank you
You could simply do
parallel$.subscribe( data => {
this.alarms = data.map(x => x[0]);
});
<div>{{alarm.alertMessage}}</div>

Yii2: Change Gridviews' DataProvider on button click

I have 3 seperate dataProviders for my Gridview, one with Saved data, one with Unsaved data and one with both.
Now this is what I'm trying to accomplish:
If you click on saved, the dataProvider changes to the one with saved data.
I'm trying it like this:
<?php
if($i == 1){
$dataProvider = $dataProviderSaved;
} elseif($i == 2) {
$dataProvider = $dataProviderNotsaved;
} else {
$dataProvider = $dataProviderBoth;
};
\yii\widgets\Pjax::begin(['id' => 'gridview', 'timeout' => false,
'enablePushState' => false, 'clientOptions' => ['method' => 'POST']]) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
//regular gridview..
\yii\widgets\Pjax::end(); ?>
Javascript:
var i = $i;
$("#saved").click(function(){
i=1;
$.pjax.defaults.timeout = false;//IMPORTANT
$.pjax.reload({container:"#gridview"});
});
', \yii\web\View::POS_READY);
So, I've just read that changing PHP variables inside JS is 'impossible'.
How would I accomplish this?
Is there a better way?
Do I need 3
DataProviders? (This means 3 find()'s inside of the controller)
If I understood properly you don't need 3 dataProviders. You should use GridView's FilterSelector option to treat that external element as part of GridView's filter.
For example
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'filterSelector' => "input[name='ModelSearch[_selection]'],",
...
Then, in your Filter Model you filter depending on that value
switch($this->_selection) {
case 'Saved':
$query->andFilterWhere([...]);
break;
case 'Unsaved':
$query->andFilterWhere([...]);
break;
case 'Both':
$query->andFilterWhere([...]);
break;
Don't forget to add the _selection attribute to your Model class and to rules() as 'safe' in the Search Model class.
You can try in two ways:
The first the simpler you assign to each button (saved, unsaved, both) the call of three separate cation of your controller
that invoke each a respective view connected to a single gridview each of these latter with the appropriate dataprovider
The second consists of controller you have the three dataprovider different as this example
return $this->render('viewYourView', [
'/modelContribuente' =>$modelContribuente,
'dataProviderOne' => $providerOne,
'dataProviderTwo' => $providerTwo,
'dataProviderThree' => $providerThree,
]);(
In a single View you can create your three gridview everyone who uses the dataprovider appropriate and then visalizzare or hide gridviewn with JQuery functions controlled by buttons

How to remove the item in session using javascript for codeigniter?

I am working on a shopping cart php(codeigniter) project. So I have add the item in the session like the code following. The problem is, I would like to remove the item in session in the checkout page.
But of course I can not call the php function to remove the session in javascript , that means , when the remove button is click , how can I do (not restrict to use ajax, simple is the best), I can remove the item in session ? Thanks
if ($this->form_validation->run()) {
if ($this->session->userdata('purchase') !== false)
$purchase_list = $this->session->userdata('purchase');
else
$purchase_list = array();
$purchase = array(
'id' => $product[0]['id'],
'quantity' => $this->input->post('quantity')
);
if ($this->input->post('opt1') !== false)
$purchase['opt1'] = $this->input->post('opt1');
if ($this->input->post('opt2') !== false)
$purchase['opt2'] = $this->input->post('opt2');
array_push($purchase_list, $purchase);
$this->session->set_userdata('purchase', $purchase_list);
redirect('cart');
}
You can define a function in your controller to unset the session e.g.
class Controllername extends CI_Controller {
function index(){}
function reset_session(){
$sesion_variable = 'name_of_session';
$this->session->unset_userdata($session_variable);
}
}
And you can call that via CURL or ajax. On checkout page
from CodeIgniter's session class documentation
This assumes you understand your cart and will know where to actually unset session data in your checkout scenery.
you can set the value of desired item in your session using this syntax:
$this->session->set_userdata('purchase', null); // will set the purchase session data to null
you only know which key to set to null though

Outputting status as a number, code to change colour

I have added a 'status' column into my table and inputed numbers for them to be shown along with the id and content.
$res_array = array();
// fetch all the entires one by one
while($row=mysql_fetch_array($res)){
// put query result in php array
$array = array('id' => $row['id'],
'content' => $row['content'],
'status'=> $row['status']);
// add into the big array
$res_array[] = $array;
// update the list view
for (var i=0; i< res.length; i++){
$("<li/>", {"id": res[i].id, "text": res[i].content + res[i].status}).appendTo(todo.list);
// Extend the width if msg is too long
if(res[i].content.length >= 35){
$('#'+res[i].id).css("height","50px");
}
}
Above you can see how it is being displayed, i still cannot get teh if statement to change the colour of the content.
I want the content to change colour depending on the status number.
I dont know the code but i would imageine it would be an if statement for the status, but i need help
Thanks in advance.
If you have a finite and defined list of status codes then I would suggest simply adding them to a CSS class such as status5 and then define the colors/style for each of the status codes you return as a basic CSS rule
.status5 { color: red }

Categories