Bolt CMS Events - php

I am working with the save event but having limited luck.
I have currently tried two ways but to limited success.
1) I can either never get the function to fire,
2) I am not too sure what to pass into the function for method two.
All I am trying to do is to dump the event information out on content save.Any help greatly appreciated, really loving this CMS
Attempt One -- never runs the function at all
class Extension extends BaseExtension
{
public function initialize() {
$this->addCss('assets/extension.css');
$this->addJavascript('assets/start.js', true);
$this->app['dispatcher']->addListener(\Bolt\Events\StorageEvents::POST_SAVE, 'postSave');
}
function postSave(\Bolt\StorageEvent $event)
{
dump($event);
}
Attempt two -- what do I input as a parameter?
class Extension extends BaseExtension
{
public function initialize() {
$this->addCss('assets/extension.css');
$this->addJavascript('assets/start.js', true);
$this->app['dispatcher']->addListener(\Bolt\Events\StorageEvents::POST_SAVE,$this->postsave($this->?????));
}
function postSave(\Bolt\StorageEvent $event)
{
dump($event);
}

Hopefully my answer doesn't come too late!
You simply can modify the content and save it back to the database:
public function postSave(\Bolt\Events\StorageEvent $event) {
// get the content
$content = $event->getContent();
// get a field out of the contenttype
$data = $content->get("myField");
// now modify $data here
$data = "new data - what ever you want";
// set data to the content
$content->setValue("data", $data);
// write the modified content to the database
$this->app['storage']->saveContent($content);
}
Note that the function gets fired every time you save contents. So just add an if-statement like this to just modify content you really want to:
if ($event->getContentType() == "my_type")

The parameter needed is a php callback the format for this is something like this:
$this->app['dispatcher']->addListener(\Bolt\Events\StorageEvents::POST_SAVE, array($this, 'postSave'));
That syntax is saying to run the postSave method within the current class. So this would work with your example number 1.
Now you can dump the event in your postSave method and see the results.

Related

Yii 1.1.16, how to detect action, what is runned from code?

i have small trouble...
class Controller {
init() {
// initializing...
// render header && footer
$header = (new HeaderAction)->run();
$footer = (new FooterAction)->run();
// redirect to called action, what renders all the content
}
}
What i can detect diff between ->run() and called action?
Answer found in:
AfterRender -> parse Route -> compare action names. If match - echo, if not match - Return.
Yii is SHIT!!!
I will write new class MyAction with method AddData, what can render for me some viewfile. Creating class CAction for this, what can't rendering? Maybe i must create controller? Are you noob, Quang, ha?
Lol, i can't create the header with action. I must create it in Controller. Controller file now is 1200 lines. >_<
class MyAction {
public $data = array();
public function addData($name, $val) {
$this->data[$name] = $val;
}
public function render($file) {
ob_start;
// ... something
return ob_get_clean;
};
}
/// ITS ALL WHAT NEED ALL THE DEVELOPERS>>>>
BEHAVIORS? EVENTS? FILTERS? WIDGETS? MODULES? MAYBE WE NEED "CAMOBAP" AS AUTOCAR?
REASOOOONS????
===
Lol, there is model cannot to render at all. I have products with views as "tr-tr", and i must create controller, create action, create route for rendering funcking 10 SYMBOLS.... Its Rage. About u, Quang.
Russian Bear will kill you.

Pass an array to Redirect::action in laravel

I'm trying to pass an array from a function to another function in laravel.
In my PageController.php, I have
public function show($code, $id){
//some code
if(isset($search))
dd($search);
}
and another function
public function search($code, $id){
//some queries
$result = DB::table('abd')->get();
return Redirect::action('PageController#show, ['search'=>$search]);
}
But this returns me an error like this: ErrorException (E_UNKNOWN)
Array to string conversion
I'm using laravel.
You could maybe get it to work with passing by the URL by serialization, but I'd rather store it in a session variable. The session class has this nice method called flash which will keep the variable for the next request and then automatically remove it.
Also, and that's just a guess, you probably need to use the index action for that, since show needs the id of a specific resource.
public function search($code, $id){
//some queries
$result = DB::table('abd')->get();
Session::flash('search', $search); // or rather $result?
return Redirect::action('PageController#index');
}
public function index($code){
//some code
if(Session::has('search')){
$search = Session::get('search');
dd($search);
}
}

Send an array of data to a function without using serialize

I have an array that loaded data from excel, now I need to send this data to another view for a review of test, but this not found because is a array in a function, I try to use serialize and unserialize but this send a error of limit of characteres in the url.
public function excel() {
$this->loadModel('SoyaProductorCompra');
$excel=array();
$k=0;
if ($this->request->is('post')) {
$datos = new Spreadsheet_Excel_Reader();
$datos->read($this->request->data['SoyaProductorCompra']['excel']['tmp_name']);
for ($i = 2; $i <= $datos->sheets[0]['numRows']; $i++) {
$excel[$k]['producto']=$datos->sheets[0]['cells'][$i][1];
$excel[$k]['toneladas']=$datos->sheets[0]['cells'][$i][2];
$excel[$k]['precio']=$datos->sheets[0]['cells'][$i][3];
$excel[$k]['total']=$datos->sheets[0]['cells'][$i][4];
$excel[$k]['fecha']=$datos->sheets[0]['cells'][$i][5];
$excel[$k]['id']=$datos->sheets[0]['cells'][$i][6];
$k++;
}
$this->set('excels',$excel);
//return $this->redirect(array('action' => 'revision', serialize($excel))); not found
}
}
this is my other function that recive the array and show in my view but not found
public function revicionexcel($data) {
//$data=unserialize($data); not work
//debug($data); not work
}
I wouldn't send the data of a whole spreadsheet through a query string regardless, even if it were small enough to do that. I mean, what would happen if someone started manually editing the URL for instance? Either write the data to a file, or save it in the session instead.
It seems that you're calling the funciton inside the same controller, right?
If so, then why you just don't use:
public function excel()
{
//read excel into $excel variable
$this->revicionexcel($excel);
}
so, no need of redirects here
Although it's recommended that you have the excel reading in the model layer, as this layer is intended for all kind of data management.
Edit:
Then, based on your comments, you can move all the reading to the model, and call it from the controller:
SoyaProductorCompra model:
public function excel($data) {
//your excel reading function as you have it on the controller.
//change all "$this->request->data" references for the parameter "$data"
//be sure to return the excel properly.
...
return $excel;
}
SoyaProductorCompras controller:
public function revision()
{
$excel = $this->SoyaProductorCompra->excel($this->request->data);
$this->set('excels', $excel);
}
What we're doing here is to call the excel opening in the model from the action revision(), and sending them to its view. You don't need to redirect here.

CakePHP: How to use a view element inside of a controller

I'm trying to figure out how to use one of my view elements inside of a controller...
I know, I know: "Don't do that!" (99% of the time this is the correct answer)
But I think I actually have a good reason. The action is handling an AJAX request which returns markup. The returned markup is a list which I display everywhere else using an element. So in an effort to keep my code DRY, I think it's appropriate to do this here.
Is this possible?
Easy:
$view = new View($this, false);
$content = $view->element('my-element', $params);
Also:
DON'T DO THAT ANYMORE!!!
Sometimes, you need to render a CakePhp element from a view and inject its content into the page using AJAX the same time. In this case rendering element as a regular view from controller is better than creating a dedicated view that just contains <?php echo $this->element('some_element') ?>, and may be done this way:
<?php
public function ajax_action() {
// set data used in the element
$this->set('data', array('a'=>123, 'b'=>456, 'd'=>678));
// disable layout template
$this->layout = 'ajax';
// render!
$this->render('/Elements/some_element');
}
I know this is an old question and other people have already given basically the same answer, but I want to point out that this approach (provided by Serge S.) ...
<?php
public function ajax_action() {
// set data used in the element
$this->set('data', array('a'=>123, 'b'=>456, 'd'=>678));
// disable layout template
$this->layout = 'ajax';
// render!
$this->render('/Elements/some_element');
}
...is not a hacky workaround, but is in fact the recommended approach from the CakePHP docs for this common and legitimate use case:
If $view starts with ‘/’, it is assumed to be a view or element file
relative to the /app/View folder. This allows direct rendering of
elements, very useful in AJAX calls.
(Again: Credit to Serge S. for the code above)
$this->view = '/Elements/myelement';
You should use a client-side template. You should never return mark-up from a web service or API, just data. Have your JavaScript take the data, and then format it how you wish.
For example:
function getItems() {
$.get('/some/url', function(response) {
if (response.data.length > 0) {
for (var i = 0; i < response.data.length; i++) {
var item = response.data[i];
$('.results').append('<li>' + item.title + '</li>');
}
}
});
};
This is just an example written off the cuff. Obviously you’ll need to write your own implementation.
The way I did any ajax handling in Cake was to have my own AjaxController. Any interaction of ajax-kind goes there, which in-turn uses their own views (and view partials / elements). That way you can keep your code DRY and isolate and propagate all ajax use-cases there.
Example excerpt:
<?php
class AjaxController extends AppController {
/**
* (non-PHPdoc)
* Everything going to this controller should be accessed by Ajax. End of story.
* #see Controller::beforeFilter()
*/
public function beforeFilter() {
parent::beforeFilter();
$this->autoRender = false;
$this->layout = false;
if (!$this->request->is('ajax')) {
$this->redirect('/');
}
}
public function preview() {
if ($this->request->is('ajax')) {
$this->set('data', $this->data);
$this->render('/Elements/ajaxpreview');
}
}
?>
Here's the source: https://github.com/Sobient/dosspirit/blob/master/app/Controller/AjaxController.php

Managing different output formats or device-types

I have to display different views for mobile devices and I want to provide a simple JSON-API.
I wrote a little module for the Kohana Framework which loads different views depending on some circumstances, which should help me in this case: https://github.com/ClaudioAlbertin/Kohana-View-Factory
However, I'm not very happy with this solution because I can't set different assets for different device-types. Also, when I'd output JSON with a JSON-view, it's still wrapped in all the HTML-templates.
Now, I'm looking for a better solution. How do you handle different output formats or device-types in your MVC-applications?
I had an idea: just split the controller into two controllers: a data-controller and an output-controller.
The data-controller gets and sets data with help of the models, does
all the validating etc. It gets the data from the models and write it to a data-object
which is later passed to the view.
The output-controller loads the views and give them the data-object from the data-controller. There is an output-controller for each format or device-type: an output-controller for mobile-devices could load the mobile-views and add all the mobile-versions of stylesheets and scripts. A JSON-output-controller could load a view without all the html-template stuff and convert the data into JSON.
A little example:
<?php
class Controller_Data_User extends Controller_Data // Controller_Data defines a data-object $this->data
{
public function action_index()
{
$this->request->redirect('user/list');
}
public function action_list()
{
$this->data->users = ORM::factory('user')->find_all();
}
public function action_show($id)
{
$user = new Model_User((int) $id);
if (!$user->loaded()) {
throw new HTTP_Exception_404('User not found.');
}
$this->data->user = $user;
}
}
class Controller_Output_Desktop extends Controller_Output_HTML // Controller_Output_HTML loads a HTML-template
{
public function action_list($data)
{
$view = new View('user/list.desktop');
$view->set($data->as_array());
$this->template->body = $view;
}
public function action_show($data)
{
$view = new View('user/show.desktop');
$view->set($data->as_array());
$this->template->body = $view;
}
}
class Controller_Output_JSON extends Controller_Output // Controller_Output doesn't load a template
{
public function action_list($data)
{
$view = new View('user/list.json');
$view->users = json_encode($data->users->as_array());
$this->template = $view;
}
public function action_show($data)
{
$view = new View('user/show.json');
$view->user = json_encode($data->user);
$this->template = $view;
}
}
What do you think?
Hmm... From the 1st view it loooks strange, and somehow like fractal -- we are breaking on MVC one of our MVC -- C.
But why is this app returns so different results, based on point-of-entry (or device)?
The task of the controller is only to get the data and choose the view -- why do we need standalone logic for choosing something based on point-of-entry (device)?
I think these questions should be answered first. Somewhere could be some problem.
Also the cotroller should select only one view ideally, and dont' do "encode" or else with data, based on current output. I think all this should be in some kind of "layouts" or else. As data always the same and even different views should be the same -- only some aspects changes.

Categories