I am currently testing the facebook marketing API to use it to get data from campaigns for a custom dashboard.
I am able to get data out from the ad account, but for some, for me, unknown reason a am getting Call to a member function getData() on a non-object while getting data. It will output some data before exiting.
I am testing with this
if($_SESSION["facebook_access_token"]) {
Api::init(
'XXXXXXXXXX',
'XXXXXXXXXXXXXXXXX',
$_SESSION["facebook_access_token"]
);
$account = new AdAccount('act_XXXXXXXXXXXXX');
$campaigns = $account->getCampaigns(array(
CampaignFields::NAME,
CampaignFields::OBJECTIVE,
CampaignFields::EFFECTIVE_STATUS,
CampaignFields::CONFIGURED_STATUS
), array(
CampaignFields::EFFECTIVE_STATUS => array(
ArchivableCrudObjectEffectiveStatuses::ACTIVE
),
));
foreach($campaigns as $campaignset) {
$cid = $campaignset->getData()['id'];
$campaign = new Campaign($cid);
$insights = $campaign->getInsights(array(
InsightsFields::CAMPAIGN_NAME,
InsightsFields::ADSET_NAME
));
var_dump($insights->current()->getData());
}
}
It will output this
array (size=48)
'account_id' => null
'account_name' => null
'action_values' => null
'actions' => null
'actions_per_impression' => null
'ad_id' => null
'ad_name' => null
'adset_id' => null
'adset_name' => null
'call_to_action_clicks' => null
'campaign_id' => null
'campaign_name' => string 'Svendborg - Mødsparnord – kopi' (length=33)
'cost_per_action_type' => null
'cost_per_total_action' => null
'cost_per_unique_click' => null
'cost_per_inline_link_click' => null
'cost_per_inline_post_engagement' => null
'cpm' => null
'cpp' => null
'ctr' => null
'date_start' => string '2015-11-05' (length=10)
'date_stop' => string '2015-12-07' (length=10)
'frequency' => null
'impressions' => null
'inline_link_clicks' => null
'inline_post_engagement' => null
'product_id' => null
'reach' => null
'relevance_score' => null
'social_clicks' => null
'social_impressions' => null
'social_reach' => null
'spend' => null
'total_action_value' => null
'total_actions' => null
'total_unique_actions' => null
'unique_clicks' => null
'unique_ctr' => null
'unique_social_clicks' => null
'video_avg_pct_watched_actions' => null
'video_avg_sec_watched_actions' => null
'video_complete_watched_actions' => null
'video_p100_watched_actions' => null
'video_p25_watched_actions' => null
'video_p50_watched_actions' => null
'video_p75_watched_actions' => null
'video_p95_watched_actions' => null
'website_ctr' => null
and some other campaigns, but it will always stop with the above mentioned error at the same spot every time. But I cannot see what's wrong.
This is because one of our campaign does not have insights data on your query. You could handle that as exception in the loop.
However, I want to promote a best practice for this. In your use case, you should really use the level parameter from the ad account, unless you have hundreds campaigns under that account.
$adAccount = new AdAccount('<AD_CAMPAIGN_ID>');
$params = array(
'level' => AdsInsightsLevelValues::Campaign,
'date_preset' => InsightsPresets::LAST_7_DAYS,
);
$insights = $adAccount->getInsights(null, $params);
print_r($insights);
This way you don't even need a for loop.
And we also have a tool to guide you generate code in the Getting Started session in https://developers.facebook.com/apps/[app_id]/marketing-api/
Basically you can pick metrics and the wizard will generate a working code for you. (It is only generating Java code for now, but code pattern is the same)
Related
I do have a resource (DeviceResource) in my Laravel API which contains another resource (SimcardResource). There is a OnetoOne relationship between those resources but sometimes a device has no associated simcard.
If this is the case my DeviceResource returns for the simcard null instead of an empty json object.
I do need an empty json object because I present information called from my API in my Vue frontend by accessing an object e.g. like device.simcard.phone_number
My DeviceResource class looks like this:
public function toArray($request)
{
return [
'id' => $this->resource->id,
'model' => $this->resource->model,
'device_name' => $this->resource->device_name,
'operating_system' => $this->resource->operating_system,
'os_version' => $this->resource->os_version,
'emei' => $this->resource->emei,
'device_password' => $this->resource->device_password,
'purchase_date' => $this->resource->purchase_date,
'associated_worker' => $this->resource->associated_worker,
'remarks' => $this->resource->remarks,
'device_status_id' => $this->resource->device_status_id,
// 'simcard' => $this->resource->simcard ?: (object)[],
'simcard' => SimcardResource::make($this->whenLoaded('simcard')) ?: (object)[],
];
}
The commented section:
'simcard' => $this->resource->simcard ?: (object)[]
Works perfectly but returns all fields from my simcard table but I only need fields defined in my SimcardResource class so I tried the following:
'simcard' => SimcardResource::make($this->whenLoaded('simcard')) ?: (object)[]
But it still returns null instead of an empty json object.
Okay maybe its not the best solution but my DeviceResource class now looks like this:
public function toArray($request)
{
if (is_null($this->resource->simcard)) {
return [
'id' => $this->resource->id,
'model' => $this->resource->model,
'device_name' => $this->resource->device_name,
'operating_system' => $this->resource->operating_system,
'os_version' => $this->resource->os_version,
'emei' => $this->resource->emei,
'device_password' => $this->resource->device_password,
'purchase_date' => $this->resource->purchase_date,
'associated_worker' => $this->resource->associated_worker,
'remarks' => $this->resource->remarks,
'device_status_id' => $this->resource->device_status_id,
'simcard' => (object) [],
];
} else {
return [
'id' => $this->resource->id,
'model' => $this->resource->model,
'device_name' => $this->resource->device_name,
'operating_system' => $this->resource->operating_system,
'os_version' => $this->resource->os_version,
'emei' => $this->resource->emei,
'device_password' => $this->resource->device_password,
'purchase_date' => $this->resource->purchase_date,
'associated_worker' => $this->resource->associated_worker,
'remarks' => $this->resource->remarks,
'device_status_id' => $this->resource->device_status_id,
// 'simcard' => $this->resource->simcard ?: (object)[],
'simcard' => SimcardResource::make($this->whenLoaded('simcard')),
];
}
}
It is Laravel resource default behaviour that if you do not have any data than resource will also return you the null resource object. You have to manage it yourself in other way like by defining each parameter has null value that's it.
Laravel introduce best ways,for example whenLoaded,but try this
... ?? json_encode(new stdClass)
im working with lravel 7 project
before i used to work with xampp 7.3.21 / PHP 7.3.21 and everything is so good
ive upgraded to xampp 7.4.9 / PHP 7.4.9 and i get
Trying to access array offset on value of type null
in the most of my porject
and this is example
public function show
(
$id,
// selects
$selects_names,
$selects_languages,
$selects_models,
$selects_policies,
$selects_types,
$selects_ranks,
// end selects
)
{
return view('curd.show',compact
(
'id'
// select
'selects_names',
'selects_languages',
'selects_models',
'selects_policies',
'selects_types',
'selects_ranks',
// end selects
));
}
and this is the blade code
#if($selects_names)
#foreach($selects_names as $key => $selects_name)
#include(
'treats.show_selects',
[
'name' => $selects_name,
'language' => $selects_languages[$key],
'model' => $selects_models[$key],
'policy' => $selects_policies[$key] ?? null,
'show_type' => $selects_types[$key],
'rank' => $selects_ranks[$key] ?? null,
]
)
#endforeach
#endif
and always get the above error
most of my program is included from the code above they are treate function and now most of it now working
Some key in $select_names is probably not in the other arrays.
Define a default value for the other arrays as you did for $select_policies and $select_ranks:
[
'name' => $selects_name,
'language' => $selects_languages[$key] ?? '',
'model' => $selects_models[$key] ?? null,
'policy' => $selects_policies[$key] ?? null,
'show_type' => $selects_types[$key] ?? null,
'rank' => $selects_ranks[$key] ?? null,
]
So I'm using the following array to pass in $record params , but I'm getting errors when a particular return from the API is null.
Here is the array:
$office->load([
'post_title' => $record->office,
'location_id' => $record->location_id,
'location' => $record->location,
'business_unit' => $record->business_unit,
'type_id' => $record->type_id,
'brand_id' => $record->brand_id,
]);
My $record->brand_id is being returned as null and it crashes my whole script, is there a way that I can output null as a string and wrap the $record->brand_id in something?
Update:
I ended up configuring the needed brand_id as $record->brand_id ?? $default_value which worked great!
If you know which values may be null and have no impact on API output you can try operators checking null values, like null coalescing operator (??).
$default_value = 'default';
$office->load([
'post_title' => $record->office,
'location_id' => $record->location_id,
'location' => $record->location,
'business_unit' => $record->business_unit,
'type_id' => $record->type_id,
'brand_id' => $record->brand_id ?? $default,
]);
I have the following code in my laravel controller file.
$j_decode->$data['_kfdTourDate']->available = ($j_decode->$data['_kfdTourDate']->available+$totalincrement);
and I am getting the following error.
ErrorException in BookingsController.php line 325: Array to string
conversion in BookingsController.php line 325 at
HandleExceptions->handleError('8', 'Array to string conversion',
'D:\XAMPP\htdocs\lara\app\Http\Controllers\BookingsController.php',
'325', array('request' => object(Request), 'id' => '0', 'rules' =>
array(), 'validator' => object(Validator), 'data' => array('_kpnID' =>
'153290', '_kfnTourID' => '2', '_kfdTourDate' => '2017-03-16',
'nAdults' => '2', 'nChildren' => '1', 'nInfants' => '0', 'nBabies' =>
'2', 'nFOC' => '2', 'nPriceAdult' => '74.25', 'nPriceChild' => '49.5',
'nPriceInfant' => '0', 'nPriceBaby' => '0', 'nTotalPrice' => '148.5',
'tGuestName' => 'Yuhiko Nishioka', 'tGuestOrigin' => 'Unknown',
'tEnquirySourceWhat' => 'Unknown', 'tStatus' => 'Confirmed',
'_kfnAgentID' => '0', '_kfnPersonID' => '0', '_kfnInvoiceID' => '0',
'nAgentCommissionPercent' => '0', 'nDiscount_percent' => '0',
'nDiscount_fixed' => '0', 'tNotes' => '4WD Tour package/Rezdy, applied
discount', 'tInitials' => 'JD', 'CreatedOn' => '2017-01-21 15:08:00',
'ModifiedOn' => '2017-01-21 15:10:00', 'tTicketNumber' => 'Rezdy',
'_kfnOrganisationID' => '0'), 'schedule' => object(Collection),
'j_decode' => object(stdClass), 'update_id_data' => object(stdClass),
'totalincrement' => '3')) in BookingsController.php line 325
Interesting part that it's working on the linux server when I upload it to my host. I have PHP Version 7.0.13 on localhost and PHP Version 5.6.30 on the server.
How can this line cause an Array to string conversion error?
I am not willing to downgrade my php version on localhost as I have other codes that php5 is not supporting.
The whole code in controller:
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost( $request );
$schedule = DB::table('schedule')
->where('id','=',$data['_kfnTourID'])
->get();
if(isset($_SESSION['bookingiddata']))
{
print_r ($j_decode= json_decode($schedule[0]->data));
$update_id_data = json_decode($_SESSION['bookingiddata']);
$totalincrement = $update_id_data->nAdults+$update_id_data->nChildren+$update_id_data->nInfants+$update_id_data->nFOC;
//$j_decode->$data['_kfdTourDate']->available = ($j_decode->$data['_kfdTourDate']->available+$totalincrement);
$j_decode->$data['_kfdTourDate']['available'] = ($j_decode->$data['_kfdTourDate']['available']+$totalincrement);
($j_decode->$data)['_kfdTourDate']->status = "available";
Also print_r $j_encode = json_encode($j_decode); prints me the following
{"2017-02-13":{"available":1,"bind":0,"info":"","notes":"","price":0,"promo":0,"status":"available"},"2017-02-14":{"available":1,"bind":0,"info":"","notes":"","price":0,"promo":0,"status":"available"},"2017-02-08":{"available":0,"bind":0,"info":"","notes":"","price":0,"promo":0,"status":"booked"},"2017-02-12":{"available":0,"bind":0,"info":"","notes":"","price":0,"promo":0,"status":"booked"},"2017-02-10":{"available":0,"bind":0,"info":"","notes":"","price":0,"promo":0,"status":"booked"},"2017-02-15":{"available":0,"bind":0,"info":"","notes":"","price":0,"promo":0,"status":"booked"},"2017-02-16":{"available":0,"bind":0,"info":"","notes":"","price":0,"promo":0,"status":"booked"}...
well, as mentioned here
in php 5.6.3 , it's allowed to use this expression:
echo $json_decode->$data['_kfdTourDate']->available;
so , you are trying to access the value of $data['_kfdTourDate'] which is element in $json_decode object
for example: https://3v4l.org/i9Q7p
in php 7,
Indirect access to variables, properties, and methods will now be
evaluated strictly in left-to-right order, as opposed to the previous
mix of special cases. The table below shows how the order of
evaluation has changed.
so, the interpreter will interpret this code as follow:
echo $json_decode->$data['_kfdTourDate']->available;
// first , give me the value $json_decode->$data,
// then choose the _kfdTourDate key
and to solve this, you need to :
echo $json_decode->{$data['_kfdTourDate']}->available;
to tell php that $data['_kfdTourDate'] is just a value;
There were some order-of-operations changes in PHP7 (see Changes to the handling of indirect variables, properties, and methods). I suspect you might need to mess around with some parentheses within $j_decode->$data['_kfdTourDate']->available to make it evaluate in the order you want.
I'm trying to implement some fairly simple image uploading using the MeioUpload behaviour in CakePHP 1.3, but I can't for the life of me get it to work. When I try to save $this->data in my controller, it tries to save a regular file array (for lack of a better word) rather than just the filename.
Here's what I'm doing:
I've put meio_upload.php into /app/models/behaviors
In my model, I'm doing the following:
var $actsAs = array(
'MeioUpload.MeioUpload' => array(
'filename' => array(
'dir' => 'img{DS}upload{DS}brawlers',
'allowedMime' => array('image/png'),
'allowedExt' => array('.png', '.PNG'),
'zoomCrop' => false,
'thumbsizes' => array(
'normal' => array(
'width' => 150,
'height' => 150
)
),
'default' => 'default.png',
'length' => array(
'minWidth' => 100,
'minHeight' => 100,
'maxWidth' => 150,
'maxHeight' => 150
)
)
)
);
In my view, I've got the following form:
<?php
echo $this->Form->create('Brawler', array('type' => 'file'));
echo $this->Form->input('name', array(
'label' => 'Name',
'maxLength' => '45'
)
);
echo $this->Form->input('comment', array(
'label' => 'Description',
'rows' => '3'
)
);
echo $this->Form->input('author', array(
'label' => 'Your name)',
'maxLength' => '45'
)
);
echo $this->Form->input('email', array(
'label' => 'Email (will not be shown)',
'maxLength' => '45'
)
);
echo $this->Form->input(
'filename',
array(
'between'=>'<br />',
'type'=>'file',
'label' => 'Image (Max 2mb, 150x150 pixels, .png)'
)
);
echo $this->Form->end('Submit');
?>
And finally my add action in the associated controller looks like this:
function add() {
if (!empty($this->data)) {
$this->Brawler->create();
if($this->Brawler->save($this->data)) {
$this->Session->setFlash('The brawler has been saved', true);
$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash('The Brawler could not be saved. Please try again.', true);
debug($this->data);
debug($this->validationErrors);
die();
//$this->redirect(array('action'=>'add'));
}
}
}
For posterity, here's my table design:
delimiter $$
CREATE TABLE `brawlers` (
`id` int(11) NOT NULL,
`name` varchar(45) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`comment` text,
`email` varchar(45) NOT NULL,
`author` varchar(45) NOT NULL,
`filename` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8$$
When I try to submit my form, this is the output I get:
app/controllers/brawlers_controller.php (line 37)
Array
(
[Brawler] => Array
(
[name] => Viking
[comment] => Herp. This is a description.
[author] => Me
[email] => me#gmail.com
[filename] => Array
(
[name] => 5.png
[type] => image/png
[tmp_name] => /storage/configuration/upload_tmp_dir/phpEF2okD
[error] => 0
[size] => 15863
)
)
)
app/controllers/brawlers_controller.php (line 37)
Obviously, this fails when it tries to save an array to the filename field. The image is never saved in the specified upload directory either. It seems like the meioupload behavior is never actually used. How can I verify this?
You'll have to excuse the mass of code that I've posted, but I figure it's better that I show you everything than to have you guess at what I may be doing. If someone can spot the error, that would save me many hours of pulling my hair.
Hey i have answer for ur Query
That is u have to make anther variable Say
$d1 and copy $this->date array into that array like below
$d1['brawlers']['name'] = $this->data['brawlers']['name'];
all ur variables
$d1['brawlers']['filename'] = $this->data['brawlers']['filename']['name'];
and then save it like $this->brawlers->save($d1);
I'm NOT PHP guy, but I had to use the CakePHP and Meio.Upload some time ago.
AFAIK you need 4 fields in your database for image:
filename (you can change name of this one in
settings)
dir
mimetype
filesize
Judging on your error and db schema I would say you are missing some of the fields.
Edit:
See the documentation
I had the same problem, the MeioUpload version your are using is incompatible with your version of Cake. I ended using version 2.3 of MeioUpload.