Cannot use object of type Illuminate\Http\Response as array (Larravel/October CMS) - laravel

i am having this erro clicking in on the menu (Build) so i dont understand. someone can help me please? Why this is happining in this line below?
public function run($url = null)
{
$params = RouterHelper::segmentizeUrl($url);
// Handle NotFoundHttpExceptions in the backend (usually triggered by abort(404))
Event::listen('exception.beforeRender', function ($exception, $httpCode, $request) {
if (!$this->cmsHandling && $exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
return View::make('backend::404');
}
}, 1);
/*
* Database check
*/
if (!App::hasDatabase()) {
return Config::get('app.debug', false)
? Response::make(View::make('backend::no_database'), 200)
: $this->passToCmsController($url);
}
the erro start happining at this line---------->
$controllerRequest = $this->getRequestedController($url);
if (!is_null($controllerRequest)) {
return $controllerRequest['controller']->run(
$controllerRequest['action'],
$controllerRequest['params']
);
}
/*
* Fall back on Cms controller
*/
return $this->passToCmsController($url);
}

To make a View you don't need to make Response. Instead of
Response::make(View::make('backend::no_database'), 200)
use
return View::make('backend::no_database');
or this for custom page
return View::make('author.plugin::backend.file'); # htm is on views/backend/file.htm
By the way check above on same file, it has return View::make('backend::404');

Related

Eloquent: querying using a non-existing column

I'm trying the following: I have two models (Pub and Schedule) related by a 1xN relationship as follows:
Pub:
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function pubSchedules()
{
return $this->hasMany(Schedule::class);
}
Schedule:
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function pub()
{
return $this->belongsTo(Pub::class);
}
Table schedules has the following fields:
id | pub_id | week_day | opening_time | closing_time |
I use the following function to know if one pub is currently (or not) open:
/**
* #return bool
*/
public function isPubCurrentlyOpen()
{
$schedules = Schedule::where([
['pub_id', $this->id ],
['week_day', Carbon::now()->dayOfWeek],
])->get();
foreach ($schedules as $schedule){
$isOpen[] =
Carbon::now('Europe/Madrid')->between(
Carbon::now('Europe/Madrid')->setTimeFromTimeString($schedule->opening_time),
Carbon::now('Europe/Madrid')->setTimeFromTimeString($schedule->closing_time)
);
}
if(in_array(true, $isOpen)){
return true;
//return "Pub Opened";
}
return false;
//return "Pub Closed";
}
In my PubController I'd like, when the option "Filter by open pubs" is chosen if($request->openPubs == 1), to show only opened pubs isOpen ==true.
Knowing the relationships between models, how can I do it?
I'm looking for something like this:
if($request->openPubs == 1)
{
$pubs = $pubs->with('pubSchedules')->where('isOpen' == true);
}
Can you help me?
Thanks a lot!
You can do this using a "whereHas"
$openPubs = Pub::whereHas('schedule', function ($query) {
$query->where('week_day', Carbon::now()->dayOfWeek);
$query->whereRaw(
"'".Carbon::now('Europe/Madrid')->format("H:i:s")."' BETWEEN opening_time AND closing_time"
);
})->get();
This is assuming your opening time and closing time are the appropriate time format and not strings (though strings will work as well in a 24h format).
You might achieve something similar to what you are looking for by using a scope e.g.
public function scopeFilterBy($query, $filter = null) {
if ($filter == "isOpen") {
$query->whereHas('schedule', function ($query) {
$query->where('week_day', Carbon::now()->dayOfWeek);
$query->whereRaw(
"'".Carbon::now('Europe/Madrid')->format("H:i:s")."' BETWEEN opening_time AND closing_time"
);
});
}
return $query; //Not sure if this is needed
}
You could then do:
Pub::filterBy($request->openPubs ? "isOpen" : null)->get();
I don't fully understand how you are trying to accomplish this but it should be something like this
$pubs = Pub::with(['pubSchedules' => function ($query) {
$query->where('opening_time', '>' ,Carbon::now()) // make sure it's currently open
->where('closing_time', '<' ,Carbon::now()) // make sure that it's not finished already
->where('week_day', '==' ,Carbon::now()->dayOfWeek) // make sure it's today
}])->find($id);
// to get if pub is currently
if($pub->pubSchedules->count()){
//
}
you can put this code in the model (Pub) and make some changes
if you already have the object you can do this (Add it to model)
public function isPubOpen()
{
$this->load(['pubSchedules' =>
// same code in other method
]);
return (bool) $this->pubSchedules->count();
}
For small tables you could call the function isPubCurrentlyOpen for each element.
For this you would need to change your function to recieve the pub_id as a parameter:
public function isPubCurrentlyOpen($pub_id)
{
$schedules = Schedule::where([
['pub_id', $pub_id ],
['week_day', Carbon::now()->dayOfWeek],
])->get();
foreach ($schedules as $schedule){
$isOpen[] =
Carbon::now('Europe/Madrid')->between(
Carbon::now('Europe/Madrid')->setTimeFromTimeString($schedule->opening_time),
Carbon::now('Europe/Madrid')->setTimeFromTimeString($schedule->closing_time)
);
}
if(in_array(true, $isOpen)){
return true;
//return "Pub Opened";
}
return false;
//return "Pub Closed";
}
and to query the data do:
if($request->openPubs == 1)
{
// assuming $pubs is a collection instance
$pubs = $pubs->filter(function($a){
return $this->isPubCurrentlyOpen($a->id);
})
}
There's a feature in Eloquent called Eager Loading. The Eloquent ORM provides a simple syntax to query for all the Schedules that are related with this particular Pub as described below:
$pubIsOpen= $pub->schedules()
->where([
['week_day', Carbon::now()->dayOfWeek],
['opening_time' , '<' , Carbon::now('Europe/Madrid')],
['closing_time' , '>' , Carbon::now('Europe/Madrid')]
])
->count();
if($openPubCount > 0){
//PUB is open
}else{
//PUB is closed
}
If it helps to someone in the future I post my solution, thanks to #apokryfos:
Pub:
/**
* #param $pubs
* #return mixed
*/
public static function isPubCurrentlyOpen($pubs)
{
$pubs->whereHas( 'pubSchedules', function ($pubs) {
$pubs->where( 'week_day', Carbon::now()->dayOfWeek )
->whereRaw(
"'" . Carbon::now( 'Europe/Madrid' )->format( "H:i:s" ) . "' BETWEEN opening_time AND closing_time"
);
} );
return $pubs;
}
PubsController:
/**
* #param GetPubRequest $request
* #return ApiResponse
*/
public function getPubs(GetPubRequest $request)
{
$orderBy = 'id';
$order = 'asc';
$pubs = Pub::withDistance();
............
if($request->openPubs == 1)
{
$pubs = Pub::isPubCurrentlyOpen($pubs);
}
return $this->response(PubProfileResource::collection($pubs->orderBy($orderBy, $order)->paginate()));
}

Joomla router.php links displayed correctly but doesnt works joomla 3.7

I have a problem with router.php
I cannot found an error in public function parse(&$segments)
The url generated as i want but it doesn't work with sef correct
the parse function gets correctly the view and the id_tsi parameters but id_tsi parameter seems to be not working
Version of joomla 3.7
the url of the component looks like
www.ktopoverit.ru/index.php?option=com_helloworld&view=reestr_si&id_tsi=1
url with switched on sef looks like
www.ktopoverit.ru/poverka/reestr_si/1
$vars looks like
Array (
[view] => reestr_si
[id_tsi] => 1
)
and my router is
class helloworldRouter extends JComponentRouterBase
{
public function build(&$query)
{
$segments = array();
if (isset($query['view']))
{
$segments[] = $query['view'];
unset($query['view']);
}
if (isset($query['id_tsi']))
{
$segments[] = $query['id_tsi'];
unset($query['id_tsi']);
};
return $segments;
}
public function parse(&$segments)
{
$vars = array();
switch($segments[0])
{
case 'reestr_si':
$vars['view'] = 'reestr_si';
$id = explode(':', $segments[0]);
$vars['id_tsi'] = (int) $id[1];
break;
}
return $vars;
}
}
Since your build() method creates the right URLs, it makes sense to take it as the base for some assumptions.
$query contains max. two values, a view (string) and an id (int). One or both of them may be omitted.
So. independent from the actual number of segments, we can just assume that an int represents the id and a string (i.e., everything else) represents the view.
/**
* Parse URL
*
* This method is meant to transform the human readable URL back into
* query parameters. It is only executed when SEF mode is switched on.
*
* #param array &$segments The segments of the URL to parse.
*
* #return array The URL attributes to be used by the application.
*/
public function parse(&$segments)
{
while (!empty($segments))
{
$segment = array_pop($segments);
if (is_numeric($segment))
{
// It's the ID
$vars['id_tsi'] = (int) $segment;
}
else
{
// It's the view
$vars['view'] = $segment;
}
}
return $vars;
}

How to open new HTML.TWIG with ajax post method in symfony

I'll try to explain the situation, I want by calling AJAX post to be able to open new html.twig template and load all the data that was return to the callback of the ajax method. To be honest I have no idea how that can be achieved.
My controller
/**
* #Route("/Datasheet", name="DatasheetPage")
*
* #return JsonResponse|\Symfony\Component\HttpFoundation\Response
*/
public function QCCAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
$part_family = $request->request->get('Part_Family');
$QCE = $request->request->get('QCE');
if($part_family == "DSUB")
{
$em =$this->getDoctrine()->getManager();
/** #var $repository \Doctrine\ORM\EntityManager */
$query = $em->createQuery(
'
SELECT
qce
FROM
AppBundle:QCE_SUBD qce
WHERE
qce.qCE LIKE :QCE
'
)->setParameters(array(
'QCE' => '%'.$QCE.'%',
));
$QCADS = $query->getArrayResult();
return new JsonResponse(json_encode($QCADS));
}
}
return $this->render('MyIndex/QCC_DATASHEETS.html.twig');
}
Here the found values are return to the post,
function generate_QCEs() {
$.post("/app_dev.php/Datasheet" ,
{
Part_Family: 'DSUB',
QCE : 'DSUB_PWR_5_P_-_CBL_QLH_4X1.0QMMTC'
} ,
function (data)
{
$('#QCE_HEADLINE').append('<h3>QCE:DSUB_PWR_5_P_-_CBL_QLH_4X1.0QMMTC</h3>');
var obj = JSON.parse(data);
// console.log(obj);
var Cable = obj[0].descriptionCables;
var Gender = obj[0].gender;
var partFamily =obj[0].partFamily;
var FamilyType = obj[0].familyType;
var Contacts = obj[0].numOfContacts;
MATING_QCEs(Cable, Gender, partFamily, FamilyType, Contacts);
}
);
}
So basically what I'm seeking is, how I could redirect to another twig and at the same time upload all the values to it.
for Example
$('#QCE_HEADLINE').append('<h3>QCE:DSUB_PWR_5_P_-_CBL_QLH_4X1.0QMMTC</h3>');
The AJAX call needs redirect me and update Datasheet.html.twig while my call is made from another twig template......

How does $this->load->view('view_name',$data,TRUE); works internally

I know what is the use of this method.
The third parameter of view method TRUE or FALSE how it works internally because want to make same method in core php which would be very usefull in core php. Not only in core in other framworks as well such as cake php too.
Thanks.
This is the main function that is called :
public function view($view, $vars = array(), $return = FALSE)
{
return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
Now the first protected function _ci_load()
protected function _ci_load($_ci_data)
{
// Set the default data variables
foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val)
{
$$_ci_val = isset($_ci_data[$_ci_val]) ? $_ci_data[$_ci_val] : FALSE;
}
$file_exists = FALSE;
// Set the path to the requested file
if (is_string($_ci_path) && $_ci_path !== '')
{
$_ci_x = explode('/', $_ci_path);
$_ci_file = end($_ci_x);
}
else
{
$_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION);
$_ci_file = ($_ci_ext === '') ? $_ci_view.'.php' : $_ci_view;
foreach ($this->_ci_view_paths as $_ci_view_file => $cascade)
{
if (file_exists($_ci_view_file.$_ci_file))
{
$_ci_path = $_ci_view_file.$_ci_file;
$file_exists = TRUE;
break;
}
if ( ! $cascade)
{
break;
}
}
}
if ( ! $file_exists && ! file_exists($_ci_path))
{
show_error('Unable to load the requested file: '.$_ci_file);
}
// This allows anything loaded using $this->load (views, files, etc.)
// to become accessible from within the Controller and Model functions.
$_ci_CI =& get_instance();
foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var)
{
if ( ! isset($this->$_ci_key))
{
$this->$_ci_key =& $_ci_CI->$_ci_key;
}
}
/*
* Extract and cache variables
*
* You can either set variables using the dedicated $this->load->vars()
* function or via the second parameter of this function. We'll merge
* the two types and cache them so that views that are embedded within
* other views can have access to these variables.
*/
if (is_array($_ci_vars))
{
foreach (array_keys($_ci_vars) as $key)
{
if (strncmp($key, '_ci_', 4) === 0)
{
unset($_ci_vars[$key]);
}
}
$this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars);
}
extract($this->_ci_cached_vars);
/*
* Buffer the output
*
* We buffer the output for two reasons:
* 1. Speed. You get a significant speed boost.
* 2. So that the final rendered template can be post-processed by
* the output class. Why do we need post processing? For one thing,
* in order to show the elapsed page load time. Unless we can
* intercept the content right before it's sent to the browser and
* then stop the timer it won't be accurate.
*/
ob_start();
// If the PHP installation does not support short tags we'll
// do a little string replacement, changing the short tags
// to standard PHP echo statements.
if ( ! is_php('5.4') && ! ini_get('short_open_tag') && config_item('rewrite_short_tags') === TRUE)
{
echo eval('?>'.preg_replace('/;*\s*\?>/', '; ?>', str_replace('<?=', '<?php echo ', file_get_contents($_ci_path))));
}
else
{
include($_ci_path); // include() vs include_once() allows for multiple views with the same name
}
log_message('info', 'File loaded: '.$_ci_path);
// Return the file data if requested
if ($_ci_return === TRUE)
{
$buffer = ob_get_contents();
#ob_end_clean();
return $buffer;
}
/*
* Flush the buffer... or buff the flusher?
*
* In order to permit views to be nested within
* other views, we need to flush the content back out whenever
* we are beyond the first level of output buffering so that
* it can be seen and included properly by the first included
* template and any subsequent ones. Oy!
*/
if (ob_get_level() > $this->_ci_ob_level + 1)
{
ob_end_flush();
}
else
{
$_ci_CI->output->append_output(ob_get_contents());
#ob_end_clean();
}
return $this;
}
second protected function _ci_object_to_array :
protected function _ci_object_to_array($object)
{
return is_object($object) ? get_object_vars($object) : $object;
}
And that's it. If you know your php, you can easily make out what it does :) Cheers

How to change existing tag information in Magento

I am trying to update the popularity count of Magento's Tag module by interacting with this core function in Mage_Tag_Model_API
public function update($tagId, $data, $store)
{
$data = $this->_prepareDataForUpdate($data);
$storeId = $this->_getStoreId($store);
/** #var $tag Mage_Tag_Model_Tag */
$tag = Mage::getModel('tag/tag')->setStoreId($storeId)->setAddBasePopularity()->load($tagId);
if (!$tag->getId()) {
$this->_fault('tag_not_exists');
}
// store should be set for 'base_popularity' to be saved in Mage_Tag_Model_Resource_Tag::_afterSave()
$tag->setStore($storeId);
if (isset($data['base_popularity'])) {
$tag->setBasePopularity($data['base_popularity']);
}
if (isset($data['name'])) {
$tag->setName(trim($data['name']));
}
if (isset($data['status'])) {
// validate tag status
if (!in_array($data['status'], array(
$tag->getApprovedStatus(), $tag->getPendingStatus(), $tag->getDisabledStatus()))) {
$this->_fault('invalid_data');
}
$tag->setStatus($data['status']);
}
try {
$tag->save();
} catch (Mage_Core_Exception $e) {
$this->_fault('save_error', $e->getMessage());
}
return true;
}
In my controller I have this :
public function clickAction()
{
$tagString = $this->getRequest()->getParam('tag');
$tagByName = Mage::getModel('tag/tag')->loadByName($tagString);
$tagId = $tagByName->getTagId();
$basePopularity = ['base_popularity' => '13']; // hard coding while testing
Mage::getModel('tag/api')->update($tagId, $basePopularity, 1);
}
If I put a log statement in this part of the update function :
try {
// log stuff
$tag->save();
}
I can see it makes it to that try but there is no change in the data. What did I screw up? Any other ideas on how I can update the popularity of a tag through a controller? Using this same method and adding 'name' => 'blah' to that $data array parameter works fine..
I also found in Mage_Tag_Model_Indexer_Summary.php this method defined in the PHPdoc * #method Mage_Tag_Model_Indexer_Summary setPopularity(int $value) Maybe that is what I need... can someone provide an example showing how I could use that magic setter?
Try adding Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); at the start of your clickAction function. base_popularity can only be updated from admin store.

Resources