Cakephp 3.0 REST API add conditions in API response - cakephp

Can we set conditions in xml response. Like there is status fields in database that is in numeric like 0,1,2,3 and we want to show it like below
0 for => Complete
2 for => Cancelled
2 for => Return
5 for => Refund.
How can we add a new fields in xml response if the fields does not exist in database ?

Lets suppose you are fetching the sales report from Sales table in Cakephp 3.0 Using rest API.
If you want to customize, rename, add few fields in response of Rest API You can do it like below
REST API URL will be something like below
https://example.com/api/index.json?fromdate_utc=2016-10-03&todate_utc=2016-10-03
And functino in controller be something like below:-
public function index($fromdate = null, $todate = null)
{
//set date range for
if(!empty($_GET['fromdate_utc']) && !empty($_GET['todate_utc'])){
// if from amd to date are same add +1 day in to date to get result
$to_date = date('Y-m-d', strtotime($_GET['todate_utc'] . ' +1 day'));
$dateRage = array('Sales.SalesDate >= ' => $_GET['fromdate_utc'], 'Sales.SalesDate <=' => $to_date);
}else{
$dateRage = array();
}
$conditions = array(
'and' => array($dateRage),
);
//$this->Auth->allow();
$sales = $this->Sales->find('all', array(
'conditions' => $conditions
))
->select(['SalesNo', 'SalesDate', 'TotalValue', 'TotalDiscount', 'NetTotal', 'PaymentMode', 'Status'])
->where(['StoreId' => '8','Status !=' => '2','Status !=' => '4'])->andWhere(['Status !=' => 1])->andWhere(['Status !=' => 4]);
//->limit(3);
$salesResponse = array();
//echo '<br/>Count no of output => '.$sales->count();
if($sales->count() >0 ){
foreach($sales as $key=>$salesData){
//re generate the array as per your requirements
$salesResponse[$key]['SalesNo'] = $salesData->SalesNo;
$salesResponse[$key]['SalesDate'] = $salesData->SalesDate;
$salesResponse[$key]['TotalValue'] = $salesData->TotalValue;
$salesResponse[$key]['TotalDiscount'] = $salesData->TotalDiscount;
$salesResponse[$key]['NetTotal'] = $salesData->NetTotal;
$salesResponse[$key]['SaleTax'] = 0; // add new fields that does not exist in database
$salesResponse[$key]['PaymentMode'] = $salesData->PaymentMode;
// change the status from numeric to character and pass it to response
if($salesData->Status == 5){
$salesResponse[$key]['Status'] = 'Refund';
}elseif($salesData->Status == 3){
$salesResponse[$key]['Status'] = 'Return';
}elseif($salesData->Status == 2){
$salesResponse[$key]['Status'] = 'Cancelled';
}elseif($salesData->Status == 0){
$salesResponse[$key]['Status'] = 'Complete';
}
}
}else{
$salesResponse = array('Error ! sorry not found any record.');
}
$this->set([
'sales' => $salesResponse,
'_serialize' => ['sales']
]);
}

If you're okay with having a slightly different name for the status in the XML, you could create a virtual field called, for example, status_text. Add a protected function _getStatusText in your Sale entity class which returns the desired text based on the status integer, and also add protected $_virtual = ['status_text']; to the Sale class, and you should start getting the status text in your XML.

Related

Drupal - Get custom taxonomy fields

I am trying to get a custom field assigned to taxonomy. I have tried this:
$vid = 'zeme';
$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
$terms is now storing all the terms from the vocabulary called 'zeme'. The problem is when I print this variable, it doesnt show the custom field that I need to get.
Any idea how can I get this custom field?
My code looks like this:
$vid = 'zeme';
$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
$term_data[] = array(
'id' => $term->tid,
'name' => $term->name
);
}
Here is the loadTree function official documentation :
TermStorage::loadTree
When you use the loadTree function, it will only get you the minimal datas to save execution time. You can see there is a $load_entities parameter set to false by default.
bool $load_entities: If TRUE, a full entity load will occur on the
term objects. Otherwise they are partial objects queried directly from
the {taxonomy_term_data} table to save execution time and memory
consumption when listing large numbers of terms. Defaults to FALSE.
So if you want to get all the datas of each of your taxonomy terms, you have to set $load_entities to true.
$vid = 'zeme';
$terms =\Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadTree($vid, 0, null, true);
Found this way from this post Get custom fields assigned to taxonomy:
$contact_countries = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('contact_country');
$terms = array();
foreach($contact_countries as $contact_countrie) {
$terms[] = array(
'contact_country' => $contact_countrie->name,
'contact_phone' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_phone')->getValue()[0]['value'],
'contact_flag' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_category_flag')->entity->uri->value,
);
}
Very usefull!
public function getTaxonomyBuild(){
$terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('faq_sec');
foreach($terms as $term) {
$term_data[] = array(
'name' => $term->name,
'img' => file_create_url(\Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term->tid)->get('field_sec_img')->entity->uri->value),
);
}
return $term_data;
}
good solution

Datagridmapper Symfony Custom Callback With Join Entity

I am using sonata admin as a back-end for my project.
I am trying to filter records, which have NULL value in database and whose column is from another entity.
Have two entities: One is Medical second one is User.
In Medical I am trying to put a search filter for 'isLanguagePurchase', which is in User entity.
Code :
$datagridMapper->add('user.isLanguagePurchase', '', array('label' => 'Is Language Purchase','callback' => function($queryBuilder, $alias, $field, $value) {
if ($value['value'] == '1') {
$queryBuilder->andWhere($alias . '.isLanguagePurchase = 1');
}
if ($value['value'] == '0') {
$queryBuilder->andWhere($alias . '.isLanguagePurchase IS NULL');
$queryBuilder->orWhere($alias . '.isLanguagePurchase = 0');
}
},'field_type' => 'choice','field_options' => array('choices'=> array('Yes' => 1, 'No' => 0))));
However, it is only searching 0 and 1 value records, not for NULL value records.

update multiple array values with multiple ids in laravel 5.1

My query as follows
$dueid = array('1','2');
for($n = 0; $n< count($post['percentage']); $n++) {
$due=invoiceduedates::whereIn('id',$dueid)
->update(array(
'percentage' => $post['percentage'][$n],
'amount'=>$post['pamount'][$n],
'date' => $post['date'][$n]
)
);
}
But in table,at 1st and 2nd ids the 2nd array data is getting updated.Please help me to sort it out.
I don't know what you what to get... but in this way it's normal that you get what you get. I can only sugest you to try like this:
$dueid = array('1','2');
$dues = invoiceduedates::whereIn('id',$dueid)->get();
for($n = 0; $n< count($post['percentage']); $n++) {
$due = $dues->find($dueid[$n+1]);
$due->update(array(
'percentage' => $post['percentage'][$n],
'amount'=>$post['pamount'][$n],
'date' => $post['date'][$n]
)
);
}

How do I use fixed fields in CakeDC's csvUpload behavior in Util plugin

I am using the csvUpload behavior of the Utils plugin by CakeDC, on a CakePHP 2.2.1 install.
I have it working great it's processing a rather large csv successfully. However there are two fields in my table / Model that would be considered fixed, as they are based on ID's from from associated models that are not consistent. So I need to get these fixed values via variables which is easy enough.
So my question is, how do I use the fixed fields aspect of csvUpload? I have tried that following and many little variation, which obviously didn't work.
public function upload_csv($Id = null) {
$unique_add = 69;
if ( $this->request->is('POST') ) {
$records_count = $this->Model->find( 'count' );
try {
$fixed = array('Model' => array('random_id' => $Id, 'unique_add' => $unique_add));
$this->Model->importCSV($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
} catch (Exception $e) {
$import_errors = $this->Model->getImportErrors();
$this->set( 'import_errors', $import_errors );
$this->Session->setFlash( __('Error Importing') . ' ' . $this->request->data['Model']['CsvFile']['name'] . ', ' . __('column name mismatch.') );
$this->redirect( array('action'=>'import') );
}
$new_records_count = $this->Model->find( 'count' ) - $records_count;
$this->Session->setFlash(__('Successfully imported') . ' ' . $new_records_count . ' records from ' . $this->request->data['Model']['CsvFile']['name'] );
$this->redirect(array('plugin'=>'usermgmt', 'controller'=>'users', 'action'=>'dashboard'));
}
}
Any help would be greatly appreciated as I have only found 1 post concerning this behavior when I searching...
I made my custom method to achieve the same task. Define the following method in app\Plugin\Utils\Model\Behavior
public function getCSVData(Model &$Model, $file, $fixed = array())
{
$settings = array(
'delimiter' => ',',
'enclosure' => '"',
'hasHeader' => true
);
$this->setup($Model, $settings);
$handle = new SplFileObject($file, 'rb');
$header = $this->_getHeader($Model, $handle);
$db = $Model->getDataSource();
$db->begin($Model);
$saved = array();
$data = array();
$i = 0;
while (($row = $this->_getCSVLine($Model, $handle)) !== false)
{
foreach ($header as $k => $col)
{
// get the data field from Model.field
$col = str_replace('.', '-', trim($col));
if (strpos($col, '.') !== false)
{
list($model,$field) = explode('.', $col);
$data[$i][$model][$field] = (isset($row[$k])) ? $row[$k] : '';
}
else
{
$col = str_replace(' ','_', $col);
$data[$i][$Model->alias][$col] = (isset($row[$k])) ? $row[$k] : '';
}
}
$is_valid_row = false;
foreach($data[$i][$Model->alias] as $col => $value )
{
if(!empty($data[$i][$Model->alias][$col]))
{
$is_valid_row = true;
}
}
if($is_valid_row == true)
{
$i++;
$data = Set::merge($data, $fixed);
}
else
{
unset($data[$i]);
}
}
return $data;
}
And you can use it using:
$csv_data = $this->Model->getCSVData($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
Here $csv_data will contain an array of all of those records from the csv file which are not empty and with the fixed field in each record index.
So as I was telling Arun, I answered my own question and figured it out. I was looking to broad instead of really examining what was in front of me. I started running some debugging and figured it out.
First of all, $unique_add = 69 is seen as an int, duh. In order for it to be added to the csv it need to viewed as a string. So it simply becomes, $unique_add = '69'.
I couldn't enter the value of $Id directly into the fixed array. So I just had to perform a simple find to get the value I needed.
$needed_id = $this->Model->find('first', array(
'condition'=>array('Model.id'=>$Id)
)
);
$random_id = $needed_id['Model']['id'];
Hopefully this won't be needed to help anyone because hopefully no one else will make this silly mistake. But one plus... Now there's actually more than one post on the internet documenting the use of fixed fields in the CakeDC Utils plugin.

Wordpress: Create pages through database?

Currently I am working on a new traveling website, but am having problems with 1 thing:
I have a list with all the country's, regions and city's i want to publish. How do I quickly create a page for all of them like this:
Every page should be a subpage like: country/region/city
Every page should have a certain page template
Please let me know, thanks in advance for your time and information!
You can do something like this.
<?php
// $country_list = get_country_list(); // returns list, of the format eg. array('India' => 'Content for the country India', 'Australia' => 'Content for the country Australia')
// $region_list = get_region_list($country); // Get the list of regions for given country, Assuming similar format as country.
// $city_list = get_city_list($region); // Get the list of cities for given region, Assuming similar format as country
/* Code starts here...*/
$country_list = get_country_list();
foreach($country_list as $country_title => $country_content) {
$country_template = 'template_country.php';
$country_page_id = add_new_page($country_title, $country_content, $country_template);
// validate if id is not 0 and break loop or take needed action.
$region_list = get_region_list($country_title);
foreach($region_list as $region_title => $region_content) {
$region_template = 'template_region.php';
$region_page_id = add_new_page($region_title, $region_content, $region_template, $country_page_id);
// validate if id is not 0 and break loop or take needed action.
$city_list = get_city_list($region_title);
foreach($city_list as $city_title => $city_content) {
$city_template = 'template_city.php';
add_new_page($city_title, $city_content, $city_template, $region_page_id);
}
}
}
function add_new_page($title, $content, $template_file, $post_parent = 0) {
$post = array();
$post['post_title'] = $title;
$post['post_content'] = $content;
$post['post_parent'] = $post_parent;
$post['post_status'] = 'publish'; // Can be 'draft' / 'private' / 'pending' / 'future'
$post['post_author'] = 1; // This should be the id of the author.
$post['post_type'] = 'page';
$post_id = wp_insert_post($post);
// check if wp_insert_post is successful
if(0 != $post_id) {
// Set the page template
update_post_meta($post_id, '_wp_page_template', $template_file); // Change the default template to custom template
}
return $post_id;
}
Warning: Make sure that the is executed only once or add any validation to avoid duplicate pages.

Resources