EXTjs 3.4.0 render a ID field in grid with NAME - javascript

I have a EXTjs grid, which displays some fields from my custome tables in database..
Reports.grid.Reports = function(config) {
config = config || {};
Ext.applyIf(config,{
id: 'reports-grid-reports'
,url: Reports.config.connectorUrl
,baseParams: { action: 'mgr/reports/getList' }
,save_action: 'mgr/reports/updateFromGrid'
,fields: ['id','name','filename','remark','year','resourceID','typeID','visible']
and then :
{
header: 'Type ID'
,dataIndex: 'typeID'
,sortable: true
,width: 100
}
My types table has typeid and name.. my grid displays the number, How can I tell it to display the coresponding name for that id in the table instead?
I also got a combobox which I use in update window:
Reports.combo.Types = function(config) {
config = config || {};
Ext.applyIf(config,{
name: 'typeID'
,hiddenName: 'typeID'
,displayField: 'name'
,valueField: 'id'
,fields: ['name','id']
,listWidth: 380
,pageSize: 20
,url: Reports.config.connectorUrl
,baseParams: {
action: 'mgr/reports/gettypelist2', 'combo': true
}
});
Reports.combo.Types.superclass.constructor.call(this,config);
};
Ext.extend(Reports.combo.Types,MODx.combo.ComboBox);
Ext.reg('combo-modx-types',Reports.combo.Types);
Using ,displayField: 'name' makes combo display name instead of the id.. how can I do the same thing in grid?

If I understand the question correctly, I believe you would need to customise the getList processor rather than in the ExtJS directly. Override the afterIteration() function. Something along the lines of:
public function afterIteration(array $list) {
$rows = array();
foreach ($list as $row){
// This calls a custom getName() function that gets the name from the other table
$row['typeID'] = $this->getName($row['id']);
$rows[] = $row;
}
return $rows;
}
and maybe your getName() function could be something like:
private function getName($id) {
$otherTable = $this->modx->getObject('TABLE_ALIAS_HERE', array('internalKey' => $id));
$name = $otherTable->get('name');
return $name;
}

Related

Laravel cannot retrieve data from multiple model with Ajax

Hi I am beginner with Ajax at the Laravel. I wanted to fetch data with Laravel Eagerload function to my blade modal.
This is my Expenses Model
protected $fillable = [
'name',
'surname',
'email',
'password',
'status',
'role',
];
protected $hidden = [
'password',
'remember_token',
];
public function Expense () {
return $this->hasMany(ExpensesModel::class);
}
This is my Expenses Model
`
{
use HasFactory;
protected $table = 'expenses';
protected $fillable = [
'id',
'emp_id',
'expense_input_date',
'expense_type',
'expense_category',
'reason',
'status'
];
public function UserExpense () {
return $this->belongsTo(User::class, 'emp_id' );
}
My controller
This is My controller function
public function edit (Request $request) {
$req_id = array('id' => $request->id);
if($request->ajax()) {
$employee = ExpensesModel::with('UserExpense')->where('id' ,$req_id)->first();
return response()->json($employee);
}
}
This is my blade script
`
function editFunc(id){
$.ajax({
type:"POST",
url: "{{ url('/expenses/advancedtable/edit') }}",
data: { id: id },
dataType: 'json',
success: function(res){
$('#EmployeeModal').html("Edit Employee");
$('#employee-modal').modal('show');
$('#id').val(res.id);
$('#emp_id').val(res.name);
$('#expense_input_date').val(res.expense_input_date);
$('#expense_type').val(res.expense_type);
$('#expense_category').val(res.expense_category);
$('#expense_slip_no').val(res.expense_slip_no);
$('#expense_amount').val(res.expense_amount);
$('#currency').val(res.currency);
$('#description').val(res.description);
}
});
}
I tried everyting but it does not work. I wanted to retrive user name from User Model by using foreign key on the Expenses model emp_id.
is there something I missed somewhere can you help me with this.
Thank you.
Here how its work.
First of all change relationship in your User and Expenses model like this.
// User Model
public function userExpense() {
return $this->hasMany(ExpensesModel::class,'emp_id','id');
}
// ExpensesModel
public function user() {
return $this->hasOne(User::class,'id','emp_id');
}
Then change your controller function.
// controller function
public function edit (Request $request) {
$req_id = $request->id;
$employeeExpense = ExpensesModel::with('user')->where('id' ,$req_id)->first();
return response()->json($employeeExpense);
}
Then change your ajax sucess function.
// ajax sucsess function
success: function(res) {
console.log(res); // to view your response from controller in webbrowser's console
$('#EmployeeModal').html("Edit Employee");
$('#employee-modal').modal('show');
$('#id').val(res.id);
$('#emp_id').val(res.user.name); // it will print user name
$('#expense_input_date').val(res.expense_input_date);
$('#expense_type').val(res.expense_type);
$('#expense_category').val(res.expense_category);
$('#expense_slip_no').val(res.expense_slip_no);
$('#expense_amount').val(res.expense_amount);
$('#currency').val(res.currency);
$('#description').val(res.description);
}
when you use 'with' eloqunt method it will add relationship function name to your query result, so you want to get user details then you should be do like res.user.userfield this is applicable for hasOne only.
For other relationship you will refer to this https://laravel.com/docs/9.x/eloquent-relationships

Multiple Model on same ActiveForm yii2

have multiple model on same form
I dont want to save data on both model but i just want to display one variable on view file
I have 2 tables
Organiser and Event
Organiser will log in and Create Event
Now there are few fields which are common in both tables
so when logged in user click on Create Event button i want to display address from Organiser table on the form
This is what i have done until now
which may not be the right approach
so let me know if that can be achieved any other simpler way
public function actionCreate()
{
$model = new Event();
$model2 = $this->findModel2(Yii::$app->user->id);
if ($model->load(Yii::$app->request->post())) {
if($_POST['User']['address'] == null)
{
$model->location = $model2->address;
}
else{
$model->location = $_POST['User']['address'];
}
$model->is_active = 1 ;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'model2' => $model2
]);
}
}
protected function findModel2($id)
{
if (($model2 = User::findOne($id)) !== null) {
return $model2;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
And here is my _form.php code
<?php $form = ActiveForm::begin([
'options' => [
'id' => 'create-event-form'
]
]); ?>
<?= $form->field($model, 'interest_id')->dropDownList(
ArrayHelper::map(Areaintrest::find()->all(),'id','area_intrest'),
['prompt'=> 'Select Event Category']
) ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?php
if ($model->isNewRecord){
echo $form->field($model2,'address')->textInput(['class' => 'placepicker form-control'])->label('Location');
}
else
echo $form->field($model,'location')->textInput(['class' => 'placepicker form-control']);
?>
<di"form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-danger' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
Now the problem here seems is that when it comes to saving part throws error saying unknown property address because that field doesnt exists in the database table Event
i just want that data to display it on the location field of my create form
so what should i do here
Here is the table structure
Organiser Event
organiser_id event_id
username organiser_id
clubname title
image location
email
firstname
lastname
address
Error page says something like this
Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: common\models\Event::address
And here is my Event model
class Event extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'event';
}
public function rules()
{
return [
[['organiser_id', 'interest_id', 'title', 'location'], 'required'],
[['organiser_id', 'interest_id'], 'integer'],
[['title', 'location'], 'string', 'max' => 255],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'organiser_id' => 'Organiser ID',
'interest_id' => 'Event Type',
'title' => 'Event Title',
'location' => 'Location'
];
}
public function getOrganiser()
{
return $this->hasOne(User::className(), ['organiser_id' => 'organiser_id']);
}
}
Here is my User model represent Organiser table and model name in frontend model SignUp.php
class SignupForm extends Model
{
public $username;
public $address;
public $password;
public $password_repeat;
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['address', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
[['file'], 'file', 'extensions'=>'jpg, gif, png'],
['password', 'required'],
['password', 'string', 'min' => 6],
['password_repeat', 'compare', 'compareAttribute' => 'password'],
];
}
public function attributeLabels()
{
return [
'password_repeat' => 'Confirm Password',
'address' => 'Address',
'username' => 'Username',
];
}
public function signup()
{
if ($this->validate()) {
$user = new User();
$model = new SignupForm();
$user->address = $this->address;
$user->username = $this->username;
$user->setPassword($this->password);
$user->generateAuthKey();
if ($user->save()) {
return $user;
}
}
return null;
}
}
So i want to display the organiser.address on the Create event form in the field location
Hope you can understand it now
thank you
May be your function should look like
public function actionCreate()
{
$event= new Event();
$user= $this->findModel2(Yii::$app->user->id);
$event->location = $user->address;
if ($event->load(Yii::$app->request->post()) && $event->save()) {//active can set by default validator
return $this->redirect(['view', 'id' => $event->id]);
}
return $this->render('create', [
'event' => $event
]);
}
And in form you show location always. Then you can use it in update and create as well without ifs in view. Hope this will help you.

MySQL table update using jQuery/AJAX

I have a main php file and a javascript file. I want to update each field in my form by using jQuery/AJAX. I have all the right database update sql, etc. It's my jQuery that is wrong. I have a table tahts called profiles. Here are the column names:
As of now, when I click the update button, it redirects me to a blank page, with the updated information displayed in the page url. When I check my database, nothing has been saved.
This is a wordpress plugin
Here is my code
jQuery update
jQuery(document).ready(function ($) {
eventHandlers = function () {
$('#cm-list').delegate('.update', 'click', function (event) {
event.preventDefault();
var row = $(this).parent()[0],
htmid = row.id,
id = htmid.replace('no_', ''),
fname = $('.fname', row).val(),
lname = $('.lname', row).val(),
sex = $('.sex', row).val(),
nationality = $('.nation', row).val(),
position = $('.position', row).val(),
json = { 'id': id, 'fname': fname, 'lname': lname, 'sex': sex, 'nationality': nation, 'position': position };
if (fname.length > 1) {
$.post(ajaxurl, { action: 'updateprofile', 'pro_data': json }, function (data) {
if (data) {
$.jGrowl(custom.profile_name + fname + lname + custom.edited, { header: custom.yes });
}
});
}
else {
$.jGrowl(custom.err, { header: custom.no });
}
});
},
cm_init = function () {
eventHandlers();
};
cm_init();
});
Php code just to show you my sql
My function updateprofile() is inside __construct()
add_action(wp_ajax...... ajax hooks
function update() {
if (!isset($_POST['pro_data'])) {
return;
}
$this->db_update($_POST['pro_data']);
}
function db_update($input) {
global $wpdb;
$result = $wpdb->update($wpdb->prefix . CM_PROTBL,
array('fname' => $input->fname,
'lname' => $input->lname,
'sex' => $input->sex,
'nationality' => $input->nationality,
'position' => $input->position
),
array('id' => $input->id),
array('%s',
'%s',
'%s',
'%s',
'$s'
),
array('%d')
);
if ($this->return_result($result)) {
$this->renderprofile($input);
}
}
function renderprofile($input) {
$output = array(
'fname' => $input->fname,
'lname' => $input->lname,
'sex' => $input->sex,
'nationality' => $input->nationality,
'position' => $input->position
);
$this->renjson($output);
}
Unable to find answers for this so any help is appreciated!
Edit: At the moment, no errors with the jQuery. When I click the update button. It brings me to a blank page, with the url containing the information I submitted, which is useless to me. I want it to update instantly and alert the user, etc.
Edit: Getting uncaught syntaxerror: unexpected token if now, If I take out the semi-colon. If I leave it in after the json variable, it gives me unexpected token error, how to solve this?
Edit: I have now fixed this error, it was my mistake, I had an extra bracket. It's not going to a white blank page now. The text is coming up, e.g. Profile John has been modified. But still nothing has changed in the database.

Autocompleting a form in PHP/Javascript

I have been trying to make an autocomplete script for the whole day but I can't seem to figure it out.
<form method="POST">
<input type="number" id="firstfield">
<input type="text" id="text_first">
<input type="text" id="text_sec">
<input type="text" id="text_third">
</form>
This is my html.
what I am trying to do is to use ajax to autocomplete the first field
like this:
and when there are 9 numbers in the first input it fills the other inputs as well with the correct linked data
the script on the ajax.php sends a mysqli_query to the server and asks for all the
data(table: fields || rows: number, first, sec, third)
https://github.com/ivaynberg/select2
PHP Integration Example:
<?php
/* add your db connector in bootstrap.php */
require 'bootstrap.php';
/*
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
*/
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
Legacy Version:
In my example i'm using an old Yii project, but you can easily edit it to your demands.
The request encodes in JSON. (You don't need yii for this tho)
public function actionSearchUser($query) {
$this->check();
if ($query === '' || strlen($query) < 3) {
echo CJSON::encode(array('id' => -1));
} else {
$users = User::model()->findAll(array('order' => 'userID',
'condition' => 'username LIKE :username',
'limit' => '5',
'params' => array(':username' => $query . '%')
));
$data = array();
foreach ($users as $user) {
$data[] = array(
'id' => $user->userID,
'text' => $user->username,
);
}
echo CJSON::encode($data);
}
Yii::app()->end();
}
Using this in the View:
$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID',
'options' => array(
'minimumInputLength' => '3',
'width' => '348px',
'placeholder' => 'Select Person',
'ajax' => array(
'url' => Yii::app()->controller->createUrl('API/searchUser'),
'dataType' => 'json',
'data' => 'js:function(term, page) { return {q: term }; }',
'results' => 'js:function(data) { return {results: data}; }',
),
),
));
The following Script is taken from the official documentation, may be easier to adopt to:
$("#e6").select2({
placeholder: {title: "Search for a movie", id: ""},
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection // omitted for brevity, see the source of this page
});
This may be found here: http://ivaynberg.github.io/select2/select-2.1.html
You can optain a copy of select2 on the github repository above.

Extjs - Combo with Templates to Display Multiple Values

I am working on Extjs 4.1. I did implement an autocomplete feature for the text box. I'm now able to search for student's first or last name by entering a term, for example: Mat, and the result in text field would be:
Mathio,Jay << student's first and last name
Mark,Matt << student's first and last name
Then, I made some changes on the query so that i can get the subjects too when i search for one:
Mathio,Jay << student's first and last name
Mark,Matt << student's first and last name
Mathematics << subject
Here is my new query:
Query to search in multiple tables + Specify the returned value
Now, what i need is reconfigure the other parts so the field can display both cases, names and subjects
Here is my combo config:
,listConfig: {
loadingText: 'Loading...',
tpl: Ext.create('Ext.XTemplate',
'<tpl for=".">',
'<tpl if="l_name.length == 0"> ',
'<div class="x-boundlist-item">{f_name}<p><font size="1">Last Name: Unknown </font></p></div>',
'<tpl else>',
'<div class="x-boundlist-item">{f_name}<p><font size="1">{l_name}</font></p></div>',
'</tpl>',
'</tpl>'
),
and my model:
Ext.define("auto", {
extend: 'Ext.data.Model',
proxy: {
type: 'ajax',
url: 'auto.php',
reader: {
type: 'json',
root: 'names',
autoLoad: true,
totalProperty: 'totalCount'
}
},
fields: ['f_name','l_name'
, {
name : 'display',
convert : function(v, rec) {
return rec.get('f_name') + ',' + rec.get('l_name');
}
}
]
});
I tried many times but still can't reach a good way to do it.
IMO you'd better use a simple model with only a 'name' field, and populate this field on the server-side. From your previous question, the server code would look like (in your query processing loop):
if (isset($row[2])) { // if the query returned a subject name in the row
$name = 'Subject: ' . $row[2];
} else if (isset($row[1])) { // if we have the last name
$name = 'Student: ' . $row[0] . ', ' . $row[1];
} else { // we have only the first name
$name = 'Student: ' . $row[0] . ' (Uknown last name)';
}
$names[] = array(
'name' => $name,
);
On the client-side, you would use a model with a single name field, and configure your combo box accordingly:
// Your simplified model
Ext.define('Post', {
extend: 'Ext.data.Model'
,fields: ['name']
,proxy: {
// Your proxy config...
}
});
Ext.widget('combo', {
displayField: 'name'
,valueField: 'name'
// Remaining of your combo config...
});
However, if you really want to mix students and subjects data in one single model, here are the modification you should do on your current code. First, you need to retrieve the subject name from the server. That means changing your server code to something like:
$names[] = array('f_name' => $row[0], 'l_name' => $row[1], 'subject' => $row[2]);
Then you need to add this field in your model on the client side, and adapt your display field's convert method to account for subject:
Ext.define('Post', {
extend: 'Ext.data.Model'
,fields: ['f_name', 'l_name',
'subject', // Add the subjet field to the model
{
name: 'display'
// Adjust your convert method
,convert: function(v, rec) {
var subject = rec.get('subject'),
lastName = rec.get('l_name'),
firstName = rec.get('f_name');
if (!Ext.isEmpty(subject)) {
return subject;
} else {
if (Ext.isEmpty(lastName)) {
return firstName + ' (Unknown last name)';
} else {
return firstName + ', ' + lastName;
}
}
}
}
]
,proxy: {
// Your proxy config...
}
});
Finally, since you already do that work in the display field of the model, you should use it as the displayField of the combo instead of doing it again in the combo's template.
E.g. combo config:
{
displayField: 'display'
,valueField: 'display'
// Remaining of your combo config...
}

Categories

Resources