Datagridmapper Symfony Custom Callback With Join Entity - sonata-admin

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.

Related

Update records of database table : Laravel

I need to update the database table according to the edited data.
controller
public function update(Request $request)
{
$subscriptionplan = SubscriptionPlan::find($request->id);
$subscriptionplan->update($request->all());
return back();
}
But nothing happens when I submit the form. When I use dd($request->all()); at the beginning of the function, it correctly shows the edited data as follows.
array:10 [▼
"_method" => "patch"
"_token" => "gOCL4dK6TfIgs75wV87RdHpFZkD7rBpaJBxJbLHF"
"editname" => "SUP_EVA_001"
"editdesc" => "des"
"editprice" => "1000.050"
"editlimit" => "1"
"editperunit" => "20.000"
"editexceedunit" => "30.000"
"productid" => "1"
"id" => "1"
]
But database has not been updated.
My table name is Table: subscription_plans and model is SubscriptionPlan
These are the table columns:
protected $fillable = [
'name',
'description',
'price',
'usage_limit',
'charge_per_unit',
'charge_per_unit_exceed',
'is_limit_exceed_considered',
'product_id'
];
Any idea on how to solve it or what I have done wrong?
If your solution did not work, try the 1by1 like this.
public function update(Request $request)
{
$subscriptionplan = SubscriptionPlan::find($request->id);
$subscriptionplan->_method = $request->_method;
$subscriptionplan->_token = $request->_token;
$subscriptionplan->editname = $request->editname;
$subscriptionplan->editdesc = $request->editdesc;
$subscriptionplan->editprice = $request->editprice;
$subscriptionplan->editlimit = $request->editlimit;
$subscriptionplan->editperunit = $request->editperunit;
$subscriptionplan->editexceedunit = $request->editexceedunit;
$subscriptionplan->productid = $request->productid;
$subscriptionplan->save();
return back();
}
In order for Laravel to automatically fill the model attributes, the indexes of the array passed to the fill method must correspond to your model attributes names.
Also, instead of
$subscriptionplan->update($request->all());
Use
$subscriptionplan->fill($request->all());
Then save the subscription plan with $subscriptionplan->save();

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

Cakephp 3.0 REST API add conditions in API response

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.

Yii2 ignore first database result

is there any way to ignore the first result record in Yii2 at a query? I have a list of numbers that represents a client. For designing purposes i had to query the first record separatly but now i have it duplicated. My questin is how can I query in Yii2 to ignore the first result?
Regards,
Gábor
The second find is the query where i need to ignore the first result:
public function actionGeneratePage() {
public function actionGeneratePage() {
$behivott = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(1)
->all();
$sorszamok = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(4)
->all();
$reklam = Reklam::find()->all();
return $this->render('generatePage', [
'sorszamok' => $sorszamok,
'reklam' => $reklam,
'behivott' => $behivott,
]);
}
You use offset() to skip the first record:
$sorszamok = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(4)
->offset(1)
->all();
Also you can use a single query to get both $behivott and $sorszamok with array_shift:
$sorszamok = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(5)
->all();
$behivott = array_shift($sorszamok);

Using array for MySQL Select Statement

Apologies in advance if i use the wrong definition of a word...I am using SimpleCart to pass $.Post variables to a PHP page. If i print the array i get
Array ( [currency] => CAD [shipping] => 0 [tax] => 1.69 [taxRate] => 0.13 [itemCount] => 3 [item_name_1] => Dinner Plate [item_quantity_1] => 1 [item_price_1] => 5 [item_options_1] => code: 110 [item_name_2] => Side Plate [item_quantity_2] => 1 [item_price_2] => 4 [item_options_2] => code: 125 [item_name_3] => Mixing Bowl [item_quantity_3] => 1 [item_price_3] => 4 [item_options_3] => code: 66 )
What I am struggling with (and going around in circles) is a method to do the following..
Explode the [item_options] variable to strip out the CODE: part of the value and just leave the numeric section.
concatenate these values into a string so i can use a SELECT statement to only pull records that have an ID passed in the [item.options].
I understand how to explode a single parameter, but cannot work out how to loop through the array, explode the key and create the value i need for the SQL.
Any help or pointers to relevant tutorials would be much appreciated
$codes = array();
foreach ($_POST as $key => $value) { // Loop through the $_POST array
if (preg_match('/^item_options_/', $key)) { // And validate the value
$item_arr = explode(' ', $value);
$item_id = $item_arr[1]; // Get the ID number from the value
if (is_numeric($item_id)) { // Validate it
$codes[] = $item_id; // Add it to the array we're building
}
}
}
$codes_string = implode(', ', $codes); // Concatenate them into a string that can be used in a SQL IN clause
$sql = "SELECT * from table WHERE id IN ($codes_string)"; // Build the SQL

Resources