Codeigniter post data from declared variable - sql

function index_post() {
$sql = "SELECT id_so FROM so_detail ORDER BY id_so DESC LIMIT 1";
$last_id2 = $this->db->query($sql)->result();
foreach ($last_id2 as $row) {
$last_id = $row->id_so;
}
//echo $last_id;
$data = array(
'id_so' => $this->post($last_id),
'id_product' => $this->post('id_product'),
'harga' => $this->post('harga'),
'harga_dasar'=> $this->post('harga'),
'modal' => $this->post('modal'),
'pajak' => $this->post('pajak'),
'qty' => $this->post('qty'),
'keterangan' => $this->post('keterangan'),
'create_user'=> $this->post('create_user'),
'create_time'=> $this->post('create_time'),
'update_user'=> $this->post('create_user'),
'update_time'=> $this->post('create_time'));
$insert = $this->db->insert('so_detail', $data);
if ($insert) {
$this->response($data, 200);
} else {
$this->response(array('status' => 'fail', 502));
}
}
i got a problem that the posted id_so is "null". when i echo $last_id it show correct id ex: 120. but when i call it to $this->post($last_id), it just be null..
How to post id_so with a string that already declared before ($last_id) ??

there are many array in $last_id2 variable.data will insert multiple time based on your last_id2.try this:
foreach ($last_id2 as $row) {
$data = array(
'id_so' =>$row->id_so,
'id_product' => $this->post('id_product'),
'harga' => $this->post('harga'),
'harga_dasar'=> $this->post('harga'),
'modal' => $this->post('modal'),
'pajak' => $this->post('pajak'),
'qty' => $this->post('qty'),
'keterangan' => $this->post('keterangan'),
'create_user'=> $this->post('create_user'),
'create_time'=> $this->post('create_time'),
'update_user'=> $this->post('create_user'),
'update_time'=> $this->post('create_time'));
}
$this->db->insert_batch('so_detail',$data);

Related

First page of product got retrieved with rest admin api in shopify

I have almost 300 products in my development store.
But when I use product.json to retrieve, only 250 products are retrieved.
Please help me in solving this.
I have followed this link
My code is
$nextPageToken = null;
do {
$response = $this->shopify->call1('GET', '/admin/api/2019-07/products.json?
limit=250&page_info='.$nextPageToken.'&rel=next' );
foreach($response['resource'] as $product):$images = array();
foreach ($product['images'] as $image):
$images[] = $image['src'];
endforeach;
$products[] = array(
'shop' => $this->session->userdata('id'),
'handle' => $product['handle'],
'title' => $product['title'],
'product' => $product['id'],
'vendor' => $product['vendor'],
'type' => $product['product_type'],
'images' => json_encode($images),
'published_at' => $product['published_at']
);
endforeach;
$this->load->model('shop_products_model');
if ($this->shop_products_model->update($products)) {
$this->load->model('customers/customers_model');
$updated = array(
'shop' => $this->session->userdata('shop'),
'products_updated' => date('Y-m-d H:i:s')
);
$this->customers_model->update($updated);
return true;
} else {
return false;
}
$nextPageToken= isset($response['next']['page_token']) ? $response['next']
['page_token'] : null;
} while($nextPageToken != null);

Prestashop: How to filter in HelperList

Hello I try to filter a List in the Backoffice. It shows the filter, it also saves it after clicking on search, but nothing is happening. Same with pagination.
$schueler = $this->getAllSchuelerbyDiplom($id_diplom);
$diplom_name = $this->getDiplomNamebyID($id_diplom);
$fields_list = array(
'id_schueler' => array(
'title' => 'ID',
'align' => 'center',
'class' => 'fixed-width-xs',
'search' => true),
'customer_name' => array(
'title' => $this->l('ID Customer')),
'id_gruppe' => array(
'title' => $this->l('ID Gruppe')),
'name' => array(
'title' => $this->l('Name'),
'filter_key' => 'name'.$diplom_name),
'vorname' => array(
'title' => $this->l('Vorname')),
'punkte' => array(
'title' => $this->l('Punkte')),
'bestanden' => array(
'title' => $this->l('Bestanden'),
'active' => 'toggle',
'class' => 'fixed-width-xs',
'type' => 'bool'),
'date_added' => array(
'title' => $this->l('Datum'),
'class' => 'fixed-width-xs',
'type' => 'date'),
);
$helper = new HelperList();
$helper->table = 'no-idea-what-this-is-for';
$helper->title = $diplom_name;
$helper->shopLinkType = '';
$helper->actions = array('view', 'edit', 'delete');
$helper->listTotal = count($schueler);
$helper->identifier = 'id_schueler';
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name .'&diplom_name=' . $diplom_name;
return $helper->generateList($schueler, $fields_list);
What is wrong with my code? What is $helper->table for? I tried different things there, but nothing helps...
EDIT
public function getAllSchuelerbyDiplom($id_diplom) {
$query = new DbQuery();
$query->select('s.*, CONCAT(c.firstname,\' \',c.lastname) AS customer_name');
$query->from($this->table_name.'_schueler', 's');
$query->leftJoin('customer', 'c', 's.id_customer = c.id_customer');
$query->where('s.id_diplom = ' . (int)$id_diplom);
return Db::getInstance()->ExecuteS($query);
}
The problem is that HelperList object itself will only display filters being used but won't filter the actual data list for you.
In your $this->getAllSchuelerbyDiplom($id_diplom); method I assume you execute SQL query to retrieve all rows, however you need modify it to account for any filters, paginations (page number and rows per page) or ordering. You have to check GET/POST values or values set in cookie to detect them.
$helper->table sets the table name and list actions are prepended with that name so they are distinct from any other lists you might have on the page.
Edit:
Example of setting pagination and page
public function getPage()
{
// $tableName must be equal to what you set in $helper->table
// Check if page number was selected and return it
if (Tools::getIsset('submitFilter'.$tableName)) {
return (int)Tools::getValue('submitFilter'.$tableName);
}
else {
// Check if last selected page is stored in cookie and return it
if (isset($this->context->cookie->{'submitFilter'.$tableName})) {
return (int)$this->context->cookie->{'submitFilter'.$tableName};
}
else {
// Page was not set so we return 1
return 1;
}
}
}
public function getRowsPerPage()
{
// $tableName must be equal to what you set in $helper->table
// Check if number of rows was selected and return it
if (Tools::getIsset($tableName. '_pagination')) {
return (int)Tools::getValue($tableName. '_pagination');
}
else {
// Check if number of rows is stored in cookie and return it
if (isset($this->context->cookie->{$tableName. '_pagination'})) {
return (int)$this->context->cookie->{$tableName. '_pagination'};
}
else {
// Return 20 rows per page as default
return 20;
}
}
}
public function getAllSchuelerbyDiplom($id_diplom) {
$query = new DbQuery();
$query->select('s.*, CONCAT(c.firstname,\' \',c.lastname) AS customer_name');
$query->from($this->table_name.'_schueler', 's');
$query->leftJoin('customer', 'c', 's.id_customer = c.id_customer');
$query->where('s.id_diplom = ' . (int)$id_diplom);
// Limit the result based on page number and rows per page
$query->limit($this->getRowsPerPage(), ($this->getPage() - 1) * $this->getRowsPerPage());
return Db::getInstance()->ExecuteS($query);
}
You can place a p(Tools::getAllValues()); d($this->context->cookie->getAll(); after you generate a list then set a filter in your list and it will show you all the variables you need to create filters and ordering.

Yii CJuiAutoComplete widget: event of empty response message

If the response does not contain data about the city, I want to see the output message. Also i want to change css of text in textfield when I get an empty response.
I have:
View:
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name'=>'city_id',
'value'=>'',
'source'=>CController::createUrl('/PromouterCity/autoComplete'),
'options'=>array(
'showAnim'=>'fold',
'minLength'=>'0',
'select'=>'js:function( event, ui ) {
$("#city_id").val( ui.item.name );
$("#selectedvalue").val( ui.item.id);
return false;
}',
),
'placeholder' => "Search...",
),
));
Controller:
public function actionAutoComplete(){
$match=$_GET['term'];
if(!empty($match)){
$match = addcslashes($match, '%_');
$q = new CDbCriteria( array(
'condition' => "name LIKE :match",
'params' => array(':match' => "$match%")
));
$query = City::model()->findAll($q);
}else{
$query=array(
'0'=>array(
'id'=>'1',
'name'=>'London',
)
);
}
$list = array();
foreach($query as $q){
$data['label']=$q['name'];
$data['id']= $q['id'];
$data['name']= $q['name'];
$list[]= $data;
unset($data);
}
echo CJSON::encode($list);
Yii::app()->end();
}
Decision:
'response'=> 'js:function( event, ui ) {
if (ui.content.length === 0) {
$("#empty-message").text("your message");
} else {
$("#empty-message").empty();
}
}',

Yii select2 - returned data cannot be selected

I have been looking into select2 and yii and have managed to load data via json request/response.
The issue I'm faced with is when I try to select an entry of the returned data, I can not.
Where am I going wrong ? The data returnd by the action is json formatted as CustomerCode and Name
Widget code in form
$this->widget('bootstrap.widgets.TbSelect2', array(
'asDropDownList' => false,
'name' => 'CustomerCode',
'options' => array(
'placeholder' => 'Type a Customer Code',
'minimumInputLength' => '2',
'width' => '40%',
'ajax' => array(
//'url'=> 'http://api.rottentomatoes.com/api/public/v1.0/movies.json',
'url'=> Yii::app()->getBaseUrl(true).'/customer/SearchCustomer',
'dataType' => 'jsonp',
'data' => 'js: function (term,page) {
return {
term: term, // Add all the query string elements here seperated by ,
page_limit: 10,
};
}',
'results' => 'js: function (data,page) {return {results: data};}',
),
'formatResult' => 'js:function(data){
var markup = data.CustomerCode + " - ";
markup += data.Name;
return markup;
}',
'formatSelection' => 'js: function(data) {
return data.CustomerCode;
}',
)));
code snipped from controller action SearchCustomer
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderJSON(Customer::model()->searchByCustomer($term));
renderJSON function from base controller class
protected function renderJSON($data)
{
header('Content-type: application/json');
echo $_GET['callback'] . "(";
echo CJSON::encode($data);
echo ")";
foreach (Yii::app()->log->routes as $route) {
if($route instanceof CWebLogRoute) {
$route->enabled = false; // disable any weblogroutes
}
}
Yii::app()->end();
}
Appreciate any help on this
i try.
change
'dataType' => 'jsonp' to 'dataType' => 'json'
and check json format
https://github.com/ivaynberg/select2/issues/920

Yii CForm, Nested Forms Ajax Validation

I have created the following nested forms array;
return array(
'elements' => array(
'contact' => array(
'type' => 'form',
'elements' => array(
'first_name' => array(
'type' => 'text',
),
'last_name' => array(
'type' => 'text',
)
),
),
'lead' => array(
'type' => 'form',
'elements' => array(
'primary_skills' => array(
'type' => 'textarea',
),
),
),
),
'buttons' => array(
'save-lead' => array(
'type' => 'submit',
'label' => 'Create',
'class' => 'btn'
),
)
);
i have view page like this
echo $form->renderBegin();
echo $form['lead'];
echo $form['contact'];
echo $form->buttons['save-lead'];
echo $form->renderEnd();
my actionCreate is like this
$form = new CForm('application.views.leads.register');
$form['lead']->model = new Lead;
$form['contact']->model = new Contact;
// how can i perform ajax validation only for $form['contact']
$this->performAjaxValidation($model);
//if contact form save btn is clicked
if ($form->submitted('save-lead') && $form['contact']->validate() &&
$form['lead']->validate()
) {
$contact = $form['contact']->model;
$lead = $form['lead']->model;
if ($contact->save()) {
$lead->contact_id = $contact->id;
if ($lead->save()) {
$this->redirect(array('leads/view', 'id' => $lead->id));
}
}
}
ajax validation method is
protected function performAjaxValidation($model)
{
if (isset($_POST['ajax']) && $_POST['ajax'] === 'contact') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
so my question is how can i perform ajax validation on $form['contact'] and $form['lead'] elements individually?
You can have several forms in a page but they should not be nested.
Nested forms are invalid.
You should make your own validation
in actionCreate and actionUpdate of your controller you must add (i have main model "Invoice" and secondary "InvoiceDetails", and there could be more than 1 form for InvoiceDetails). But of course forms cannot be nested!
public function actionCreate()
{
...
$PostVar = 'Invoices';
if (Yii::app()->request->isAjaxRequest)
{ // if ajax
$this->performAjaxValidation($model, strtolower($PostVar) . '-form');
$PostVar = ucfirst($PostVar);
if (isset($_POST[$PostVar]))
{
$model->attributes = $_POST[$PostVar];
$dynamicModel = new InvoiceDetails(); //your model
$valid = self::validate($model, $dynamicModel);
if (!isset($_POST['ajax']))
{
if (isset($_POST['InvoiceDetails']))
{
$allDetails = array();
$allDynamicModels = $_POST['InvoiceDetails'];
//your own customization
foreach ($allDynamicModels as $key => $value)
{
$InvDet = InvoiceDetails::model()->findByPk($_POST['InvoiceDetails'][$key]['id']);
if (!isset($InvDet))
{
$InvDet = new InvoiceDetails();
}
$InvDet->attributes = $_POST['InvoiceDetails'][$key];
$InvDet->save();
$allDetails[] = $InvDet;
}
}
$model->invoicedetails = $allDetails;
if ($model->save())
{
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
}
else
{
echo CJSON::encode(array('status' => 'error saving'));
Yii::app()->end();
}
}
// Here we say if valid
if (!isset($valid))
{
echo CJSON::encode(array('status' => 'success'));
}
else
{
echo $valid;
}
Yii::app()->end();
}
else
{
$this->renderPartial('_form', ...);
}
}
else
{
// not AJAX request
$this->render('_form', ...));
}
Nested Forms are invalid. You can use scenarios to validate the form at different instances.
Example:
`if ($form->submitted('save-lead'){
$form->scenario = 'save-lead';
if($form->validate()) {
$form->save();
}
} else {
$form->scenario = 'contact';
if($form->validate()){
$form->save();
}
}
$this->render('_form', array('form'=>$form);`