ZF2 forward plugin dispatches wrong View - zend-framework

I have a weird problem. I am trying to widgetize my website by creating a ViewHelper which contains and this piece of code but for some reason it doesn't work as expected:
//....
$forward = $serviceManager->get('ControllerPluginManager')->get('Forward');
$view = $forward->dispatch('Application\Controller\Widgets', array('action' => 'notexistingaction'));
$view1 = $forward->dispatch('Application\Controller\Widgets', array('action' => 'existingaction'));
\Zend\Debug\Debug::dump($view);
\Zend\Debug\Debug::dump($view1);
//....
The result is
object(Zend\View\Model\ViewModel)#713 (7) {
["captureTo":protected] => string(7) "content"
["children":protected] => array(0) {
}
["options":protected] => array(0) {
}
["template":protected] => string(9) "error/404"
["terminate":protected] => bool(false)
["variables":protected] => array(4) {
["content"] => string(14) "Page not found"
["message"] => string(15) "Page not found."
["reason"] => string(32) "error-controller-cannot-dispatch"
["display_exceptions"] => bool(true)
}
["append":protected] => bool(false)
}
object(Zend\View\Model\ViewModel)#716 (7) {
["captureTo":protected] => string(7) "content"
["children":protected] => array(0) {
}
["options":protected] => array(0) {
}
["template":protected] => string(9) "error/404"
["terminate":protected] => bool(false)
["variables":protected] => object(Zend\View\Variables)#717 (2) {
["strictVars":protected] => bool(false)
["storage":"ArrayObject":private] => array(3) {
["message"] => string(15) "Page not found."
["reason"] => string(32) "error-controller-cannot-dispatch"
["display_exceptions"] => bool(true)
}
}
["append":protected] => bool(false)
}
Question WHY ??
Technically there should be one with error and other one to be displayed its content .. but for some reason both appears as 404
Any help please?
Thanks

Related

Error: Call to undefined method MongoDB\Collection::getMongoCollection()

I've upgraded an app from PHP74 to 81 and doctrine/mongodb-odm 1.x to 2.x.
A call to this method
private function getLoginsForPipeline(array $pipeline)
{
$collection = $dm->getDocumentCollection(LoginTrackerModel::class)->getMongoCollection();
return $collection->aggregateCursor($pipeline, ["allowDiskUse" => true]);
}
where $pipeline is defined as:-
$pipeline = [
[0] =>
array(1) {
'$sort' =>
array(1) {
'date' =>
int(-1)
}
}
[1] =>
array(1) {
'$group' =>
array(2) {
'_id' =>
string(5) "$user"
'lastLoginDate' =>
array(1) {
...
}
}
}
[2] =>
array(1) {
'$match' =>
array(1) {
'lastLoginDate' =>
array(1) {
...
}
}
}
];
returns:-
Error: Call to undefined method MongoDB\Collection::getMongoCollection()
So, looks like getMongoCollection() has been deprecated in doctrine/mongodb-odm 2.x
I have a hunch we can replace
$collection = $dm->getDocumentCollection(LoginTrackerModel::class)->getMongoCollection();
with:-
$builder = $dm->createAggregationBuilder(LoginTrackerModel::class); in 2.x
does anyone know how/what we'd replace
$collection->aggregateCursor($pipeline, ["allowDiskUse" => true]);
with in 2.x?
Am I on the right track with something along the lines of:-
$builder
->match()
->field('lastLoginDate')
->group()
->sort('date');
$result = $builder->getAggregation();
I'm not 100% since getAggregation() != aggregateCursor()

Perl how to access a value of nested hash without specific some middle keys (wildcard)

I trying to fetch the facebook mobile posts.
$VAR1 = {
"mf_story_key" => "225164133113094",
"page_id" => "102820022014173",
"page_insights" => {
"102820022014173" => {
"actor_id" => "102820022014173",
"page_id" => "102820022014173",
"page_id_type" => "page",
"post_context" => {
"publish_time" => "1641702174",
"story_name" => "EntStatusCreationStory"
},
"psn" => "EntStatusCreationStory",
"role" => 1,
}
},
"story_attachment_style" => "album",
};
$publish_time = $VAR1->{page_insights}{102820022014173}{post_context}{publish_time};
If 102820022014173 is a dynamic value, how do I access the publish_time value without specific it?
You need to get the keys to the page_insights hash and then iterate through them.
use strict;
use warnings;
use 5.010;
my $post = {
"mf_story_key" => "225164133113094",
"page_id" => "102820022014173",
"page_insights" => {
"102820022014173" => {
"actor_id" => "102820022014173",
"page_id" => "102820022014173",
"page_id_type" => "page",
"post_context" => {
"publish_time" => "1641702174",
"story_name" => "EntStatusCreationStory"
},
"psn" => "EntStatusCreationStory",
"role" => 1,
}
},
"story_attachment_style" => "album",
};
my $insights = $post->{page_insights};
my #insight_ids = keys %{$insights};
for my $id ( #insight_ids ) {
say "ID $id was published at ",
$insights->{$id}{post_context}{publish_time};
}
gives
ID 102820022014173 was published at 1641702174
for my $page_insight ( values( %{ $VAR1->{page_insights} } ) ) {
my $publish_time = $page_insight->{post_context}{publish_time};
...
}
If there's always going to exactly one element,
my $page_insight = ( values( %{ $VAR1->{page_insights} } )[0];
my $publish_time = $page_insight->{post_context}{publish_time};
...
(You can combine the two statements if you so desire.)

is it possible to return different models in an API response

This is my first time posting here so please pardon my errors:
I have a search functionality whose route is:
Route::get('/search', 'SearchController#index');
Currently, I have an eloquent relationship where products has many deals. is it possible to return a single level deep array doing the following:
If the product has an active deal, return the deal only;
Otherwise, return the product itself.
here's what I earlier implemented in my Product.php:
public function deals()
{
return $this->hasMany(Deal::class, 'product_id');
}
Deal.php
public function product()
{
return $this->hasOne(Product::class, 'id', 'product_id');
}
SearchController:
public function index(Request $request)
{
$per_page = $request->per_page ?? 10;
$products = Product::query()->latest()
->when($request->query('filter'), function ($query) use ($request) {
$query->with('deals')->where('title', 'LIKE', "%$request->filter%");
})
->when($request->query('category'), function ($query) use ($request) {
$query->with('deals')->whereHas('categories', function ($q) use ($request) {
$q->where('title', 'LIKE', "%$request->category%");
});
})
->paginate($per_page);
return new PaginatedCollection($products, ProductResource::class);
}
and in my ProductResource:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ProductResource extends JsonResource
{
public function toArray($request)
{
$details = array_filter($this->details ?: [], function ($d) {
return $d != "";
});
$personalizedOptions = array_filter($this->personalized_options ?: [], function ($o) {
return $o != "";
});
return [
'id' => $this->id,
'createdAt' => $this->created_at,
'updatedAt' => $this->updated_at,
'title' => $this->title,
'sellerId' => $this->sellerId,
'description' => $this->description,
'categories' => CategoryResource::collection($this->categories),
'details' => $details,
'active' => (bool) $this->active,
'defaultPreviewImageId' => $this->default_preview_image_id,
'originalPrice' => $this->originalPrice,
'shippingPrice' => $this->shippingPrice,
'shippingWeightLbs' => $this->shippingWeightLbs,
'shippingWeightOz' => $this->shippingWeightOz,
'shippingMaxDays' => $this->shipping_max_days,
'shippingMinDays' => $this->shipping_min_days,
'personalized' => (bool) $this->personalized,
'personalizedOptions' => $personalizedOptions,
'deals' => $this->deals ?? null,
'options' => ProductOptionResource::collection($this->productOptions),
'images' => ImageResource::collection($this->images->whereNull('meta')),
'preview' => new ImageResource($this->images->where('meta', '=', 'preview')->first()),
];
}
}
Now, I have refactored the ProductResource to this but it's all returning null response
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ProductResource extends JsonResource
{
public function toArray($request)
{
$details = array_filter($this->details ?: [], function ($d) {
return $d != "";
});
$personalizedOptions = array_filter($this->personalized_options ?: [], function ($o) {
return $o != "";
});
if($this->deals){
DealResource::collection($this->deals);
}else{
return [
'id' => $this->id,
'createdAt' => $this->created_at,
'updatedAt' => $this->updated_at,
'title' => $this->title,
'sellerId' => $this->sellerId,
'description' => $this->description,
'categories' => CategoryResource::collection($this->categories),
'details' => $details,
'active' => (bool) $this->active,
'defaultPreviewImageId' => $this->default_preview_image_id,
'originalPrice' => $this->originalPrice,
'shippingPrice' => $this->shippingPrice,
'shippingWeightLbs' => $this->shippingWeightLbs,
'shippingWeightOz' => $this->shippingWeightOz,
'shippingMaxDays' => $this->shipping_max_days,
'shippingMinDays' => $this->shipping_min_days,
'personalized' => (bool) $this->personalized,
'personalizedOptions' => $personalizedOptions,
// 'deals' => $this->deals ?? null,
'options' => ProductOptionResource::collection($this->productOptions),
'images' => ImageResource::collection($this->images->whereNull('meta')),
'preview' => new ImageResource($this->images->where('meta', '=', 'preview')->first()),
];
}
}
}
The reason why it may be giving the null result because of the condition check. it is returning an array you need to update it to this.
if(count($this->deals))
this will check if the deal array contains an element in the array. if not it will return products.

Insert array into postgresql error

I using Phalcon Framework and PostgreSQL
I try to insert an array to database column type: varchar[]:
array(4) { [0]=> string(1) "1" [1]=> string(1) "6" [2]=> string(1) "9" [3]=> string(2) "12" }
But getting following error :
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Please help me to fix this please
Here is my Model:
<?php
namespace App\Models;
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;
class Document extends Model
{
public $id;
public $relatedocument;
public function getSource()
{
return "document";
}
=====Form======
<?php
namespace App\Modules\Backend\Forms;
use Idoc\Models\Document;
use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Select;
class DocumentForm extends Form
{
public function initialize($entity = null, $options = null)
{
$data = Document::find();
$this->add(new Select('relatedocument[]', $data, [
'using' => [
'id',
'name'
],
'useEmpty' => true,
'emptyText' => '....',
'multiple' => 'multiple',
'class' => 'form-control search-select'
]));
}
=====addAction======
public function addAction()
{
if ($this->request->isPost()) {
$doc = new Document();
$doc->relatedocument = $this->request->getPost('relatedocument');
if (!$doc->save()) {
$this->flash->error($doc->getMessages());
} else {
$this->flash->success("Văn bản đã được tạo");
Tag::resetInput();
}
}
$this->view->form = new DocumentForm(null);
}

Zend Framework Result Set

Hi I'm trying to implement the method fetchAll like the Album example but It doesn't work.
When I try to print the result with a var_dump I get this
object(Zend\Db\ResultSet\ResultSet)#258 (8) {
["allowedReturnTypes":protected]=>
array(2) {
[0]=>
string(11) "arrayobject"
[1]=>
string(5) "array"
}
["arrayObjectPrototype":protected]=>
object(Application\Model\Ubigeo)#242 (5) {
["codDpto"]=>
NULL
["codProv"]=>
NULL
["codDist"]=>
NULL
["name"]=>
NULL
["idUbigeo"]=>
NULL
}
["returnType":protected]=>
string(11) "arrayobject"
["buffer":protected]=>
NULL
["count":protected]=>
int(2057)
["dataSource":protected]=>
object(Zend\Db\Adapter\Driver\Pdo\Result)#257 (8) {
["statementMode":protected]=>
string(7) "forward"
["resource":protected]=>
object(PDOStatement)#248 (1) {
["queryString"]=>
string(52) "SELECT `ubigeo`.* FROM `ubigeo` ORDER BY `name` DESC"
}
["options":protected]=>
NULL
["currentComplete":protected]=>
bool(false)
["currentData":protected]=>
NULL
["position":protected]=>
int(-1)
["generatedValue":protected]=>
string(1) "0"
["rowCount":protected]=>
int(2057)
}
["fieldCount":protected]=>
int(5)
["position":protected]=>
int(0)
}
This is my serviceConfig:
public function getServiceConfig() {
return array(
'factories' => array(
'Application\Model\UbigeoTable' => function ($sm) {
$tableGateway = $sm->get('UbigeoTableGateway');
$table = new UbigeoTable($tableGateway);
return $table;
},
'UbigeoTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Ubigeo());
return new TableGateway('ubigeo', $dbAdapter, null, $resultSetPrototype);
}
),
);
}
Any help would be appreciate
According to var_dump your table contains these rows : codDpto, codProv, codDist, name and idUbigeo.
You can access the results this way :
foreach($resultSet as $row)
{
$result = '<p>codDpto: '.$row['codDpto'];
$result .= ', codProv: '.$row['codProv'];
$result .= ', codDist: '.$row['codDist'];
$result .= ', name: '.$row['name'];
$result .= ', idUbigeo: '.$row['idUbigeo'].'</p>';
echo $result;
}