Zend Framework 2 Saving layout and template content in database - templates

I want to save both layout and view template CONTENT in the database. Each view template will be associated to a layout_id. When a controller action loads, it will fetch the appropriate layout and view from database.
I've done fair amount of researching, looks like this hasn't been discussed before, at least not with ZF2. Not only I want different themes for the site, I also want version control on the design, user can work on a version of template, save it and when done publish the site. I've been looking into custom view strategy and renderer and could not find out how to piece everything together.
Please advice how to proceed with this problem. If there are any tutorials out there please let me know.

First, you have to decide your database structure. I would prefer a table where for each controller/action, depending on the version of the design, you have a file for the layout view, and another for the action view. I think it is a flexible way, since you can have for instance the same layout for all the controllers, but a a different view for the content of every action, or you can have a different layout for an specific controller.
It could be something like this.
CREATE TABLE `templates` (
`version` INT(5) NOT NULL,
`controller` VARCHAR(30) NOT NULL,
`action` VARCHAR(30) NOT NULL,
`layout_view` VARCHAR(30) DEFAULT NULL,
`action_view` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`version`,`module`,`controller`,`action`)
)
remember that the template names has to be 'MODULE/CONTROLLER/ACTION' that is the format that the function ViewModel::setTemplate is expecting. So if in your Module Foo, you have the folder view, with a hierachy like this Foo/view/foo/controllerName/actionName.phtml in your database you should store: foo/controllerName/actionName
Then you have to set, somewhere in the config files, the current design version that has to be used. This version could be a different one in your local machine, and in the production server. For that, you leverage the /config/autoload/local.php that allows you to have different configuration in the different enviroments, just telling your git, subversion, or ftp, to ignore this file, so you can have a different one in every enviroment. Check this docs. It will be enough if you put something like this:
/config/autoload/local.php
return array(
'designVersion' => 1,
);
Then when the application loads, you have to check the current version of the design, and set the correct templates to be used. I would do it after the dispatch event, so the way would be to add a listener in the app bootstrarp. For that, in your main module (i.e. "App" or "Application" module), in the Module.php you overwrite the onBootstrap function, load the event manager, and add a callback to the MvcEvent::EVENT_DISPATCH event.
There, you can have access to the serviceManager, so you can retrieve your database adapter, also, you can know the current requested controller and action, the current viewmodel object, and from it, the action viewmodel. So you already have everything you need. So you can go like this:
public function onBootstrap(MvcEvent $e) {
//get the service manager
$sm = $e->getApplication ()->getServiceManager ();
//get your db adapter
$db=$sm->get("whatever is the service name of your database adapter, entity manager, or whatever you are using");
//get the config
$config = $sm->get ( 'config' );
$version = $config ['designVersion'];
//get the event manager, and attach a callback to the MvcEvent::EVENT_DISPATCH
$em = $e->getApplication ()->getEventManager ();
$em->attach ( MvcEvent::EVENT_DISPATCH, function ($e) use($sm) {
//you get the routeMath, so you can know the controller and action
$routeMatch = $e->getRouteMatch ();
$action=$routeMatch->getParam ( 'action' );
$controller=$routeMatch->getParam ( 'controller' );
//now, with $action, $controller, and $version
//you query your db to get the layout and view templates:
$views=$db->whetever..
$layout_template= $views->layout_view;
$action_template= $views->action_view;
//you get the current viewModel, it hasnt been rendered yet, so we can set the templates
$viewModel = $e->getViewModel ();
if (is_null ( $viewModel ))
return;
$viewModel->setTemplate ($layout_template);
//and now, we get the action view model, that we know that is set as a children of the layout viewmodel. So we can retrieve it like this:
$children = $viewModel->getCurrent()->getChildren();
$child = $children[0];
//if we are afraid the view could have more children, and you want to make sure that you rerieve the correct one, then you could iterate over $children and look for the child that has the correct captureTo name set. For the action’s view model, this defaults to content:
/*
$children = $viewModel->getCurrent()->getChildren();
$child=null;
foreach($children as $c) {
if ($c->captureTo() == 'content') {
$child=$c;
break;
}
}
*/
//and now, you set the template to the view:
$child->setTemplate ($action_template);
}, - 100 );
}

Related

Create NewRecord through Siebel Business Service eScript

I am trying to create a new record using BS server script.
Since the process is taking place inside the BS, the context of Parent is not present, hence I am unable to get Parent Row_Id which I need to explicitly stamp against the child record being created for visibility.
Initially I tried to pass the Parent Row_Id from applet as a profile, but this fails when there are no records in the child applet, ie this.BusComp().ParentBusComp().GetFieldValue returns "This operation is invalid when there are no records present" as the "this" context is unavailable.
Any suggestions?
I was able to achieve the desired with the below code
sId = TheApplication().ActiveBusObject().GetBusComp("Q").ParentBusComp().GetFieldValue("Id");
if(this.BusComp().CountRecords() > 0)
{
sA = TheApplication().ActiveBusObject().GetBusComp("Q").GetFieldValue("A");
sB = TheApplication().ActiveBusObject().GetBusComp("Q").GetFieldValue("B");
}
sEntity = TheApplication().ActiveBusObject().GetBusComp("Q").Name();
It is for these reasons that Siebel provides Pre-Default settings at the Business Component Field level. If you wish to do this entirely through scripting, you will have to find the Active context, you have to know which BC is the parent.
Lets say you know that the Parent BC has to be Account. So
ActiveBusObject().GetBusComp("Account").GetFieldValue("Id") will give you the row id of the currently selected Account BC record. But do make sure that this script fires only in this context. So check the ActiveViewName to check this.
if(TheApplication().GetProfileAttr("ActiveViewName")=="Custom View")
{
//put the scripting here.
}

OpenCart pass data to children module

Basically what i'm trying to do is to pass some data from "parent" controller to the controller of its children module, for example:
header controller
$this->children = array(
'module/newslettersubscribe'
);
newslettersubscribe controller
public function index() {
// Use here data from the header controller
}
Is that even possible to do?
Here the approach is incorrect. You should edit only the slider controller and check whether there is a path variable available in the GET (query string), e.g.:
if (!empty($this->request->get['path'])) { /* ... */ }
If it is you can now extract the categories from it's value (which is e.g. 1_12_36):
if (!empty($this->request->get['path'])) {
$category_ids = explode('_', (string)$this->request->get['path']);
}
Now knowing the category IDs (or the category path) you can display the appropriate images only using whatever code you made up.

Force a controller to always act as a proxy to a model in Ember

I'm looping through a content of an ArrayController whose content is set to a RecordArray. Each record is DS.Model, say Client
{{# each item in controller}}
{{item.balance}}
{{/each}}
balance is a property of the Client model and a call to item.balance will fetch the property from the model directly. I want to apply some formatting to balance to display in a money format. The easy way to do this is to add a computed property, balanceMoney, to the Client object and do the formatting there:
App.Client = DS.Model({
balance: DS.attr('balance'),
balanceMoney: function() {
// format the balance property
return Money.format(this.get('balance');
}.property('balance')
});
This serves well the purpose, the right place for balanceMoney computed property though, is the client controller rather than the client model. I was under the impression that Ember lookup properties in the controller first and then tries to retrieve them in the model if nothing has been found. None of this happen here though, a call to item.balanceMoney will just be ignored and will never reach the controller.
Is it possible to configure somehow a controller to act always as a proxy to the model in all circumstances.
UPDATE - Using the latest version from emberjs master repository you can configure the array controller to resolve records' methods through a controller proxy by overriding the lookupItemController method in the ArrayController. The method should return the name of the controller without the 'controller' suffix i.e. client instead of clientController. Merely setting the itemControllerClass property in the array controller doesn't seem to work for the moment.
lookupItemController: function( object ) {
return 'client';
},
This was recently added to master: https://github.com/emberjs/ember.js/commit/2a75cacc30c8d02acc83094b47ae8a6900c0975b
As of this writing it is not in any released versions. It will mostly likely be part of 1.0.0.pre.3.
If you're only after formatting, another possibility is to make a handlebars helper. You could implement your own {{formatMoney item.balance}} helper, for instance.
For something more general, I made this one to wrap an sprintf implementation (pick one of several out there):
Ember.Handlebars.registerHelper('sprintf', function (/*arbitrary number of arguments*/) {
var options = arguments[arguments.length - 1],
fmtStr = arguments[0],
params = Array.prototype.slice.call(arguments, 1, -1);
for (var i = 0; i < params.length; i++) {
params[i] = this.get(params[i]);
}
return vsprintf(fmtStr, params);
});
And then you can do {{sprintf "$%.2f" item.balance}}.
However, the solution #luke-melia gave will be far more flexible--for example letting you calculate a balance in the controller, as opposed to simply formatting a single value.
EDIT:
A caveat I should have mentioned because it's not obvious: the above solution does not create a bound handlebars helper, so changes to the underlying model value won't be reflected. There's supposed to be a registerBoundHelper already committed to Ember.js which would fix this, but that too is not released yet.

Adding item to filtered result from ember-data

I have a DS.Store which uses the DS.RESTAdapter and a ChatMessage object defined as such:
App.ChatMessage = DS.Model.extend({
contents: DS.attr('string'),
roomId: DS.attr('string')
});
Note that a chat message exists in a room (not shown for simplicity), so in my chat messages controller (which extends Ember.ArrayController) I only want to load messages for the room the user is currently in:
loadMessages: function(){
var room_id = App.getPath("current_room.id");
this.set("content", App.store.find(App.ChatMessage, {room_id: room_id});
}
This sets the content to a DS.AdapterPopulatedModelArray and my view happily displays all the returned chat messages in an {{#each}} block.
Now it comes to adding a new message, I have the following in the same controller:
postMessage: function(contents) {
var room_id = App.getPath("current_room.id");
App.store.createRecord(App.ChatMessage, {
contents: contents,
room_id: room_id
});
App.store.commit();
}
This initiates an ajax request to save the message on the server, all good so far, but it doesn't update the view. This pretty much makes sense as it's a filtered result and if I remove the room_id filter on App.store.find then it updates as expected.
Trying this.pushObject(message) with the message record returned from App.store.createRecord raises an error.
How do I manually add the item to the results? There doesn't seem to be a way as far as I can tell as both DS.AdapterPopulatedModelArray and DS.FilteredModelArray are immutable.
so couple of thoughts:
(reference: https://github.com/emberjs/data/issues/190)
how to listen for new records in the datastore
a normal Model.find()/findQuery() will return you an AdapterPopulatedModelArray, but that array will stand on its own... it wont know that anything new has been loaded into the database
a Model.find() with no params (or store.findAll()) will return you ALL records a FilteredModelArray, and ember-data will "register" it into a list, and any new records loaded into the database will be added to this array.
calling Model.filter(func) will give you back a FilteredModelArray, which is also registered with the store... and any new records in the store will cause ember-data to "updateModelArrays", meaning it will call your filter function with the new record, and if you return true, then it will stick it into your existing array.
SO WHAT I ENDED UP DOING: was immediately after creating the store, I call store.findAll(), which gives me back an array of all models for a type... and I attach that to the store... then anywhere else in the code, I can addArrayObservers to those lists.. something like:
App.MyModel = DS.Model.extend()
App.store = DS.Store.create()
App.store.allMyModels = App.store.findAll(App.MyModel)
//some other place in the app... a list controller perhaps
App.store.allMyModels.addArrayObserver({
arrayWillChange: function(arr, start, removeCount, addCount) {}
arrayDidChange: function(arr, start, removeCount, addCount) {}
})
how to push a model into one of those "immutable" arrays:
First to note: all Ember-Data Model instances (records) have a clientId property... which is a unique integer that identifies the model in the datastore cache whether or not it has a real server-id yet (example: right after doing a Model.createRecord).
so the AdapterPopulatedModelArray itself has a "content" property... which is an array of these clientId's... and when you iterate over the AdapterPopulatedModelArray, the iterator loops over these clientId's and hands you back the full model instances (records) that map to each clientId.
SO WHAT I HAVE DONE
(this doesn't mean it's "right"!) is to watch those findAll arrays, and push new clientId's into the content property of the AdapterPopulatedModelArray... SOMETHING LIKE:
arrayDidChange:function(arr, start, removeCount, addCount){
if (addCount == 0) {return;} //only care about adds right now... not removes...
arr.slice(start, start+addCount).forEach(function(item) {
//push clientId of this item into AdapterPopulatedModelArray content list
self.getPath('list.content').pushObject(item.get('clientId'));
});
}
what I can say is: "its working for me" :) will it break on the next ember-data update? totally possible
For those still struggling with this, you can get yourself a dynamic DS.FilteredArray instead of a static DS.AdapterPopulatedRecordArray by using the store.filter method. It takes 3 parameters: type, query and finally a filter callback.
loadMessages: function() {
var self = this,
room_id = App.getPath('current_room.id');
this.store.filter(App.ChatMessage, {room_id: room_id}, function (msg) {
return msg.get('roomId') === room_id;
})
// set content only after promise has resolved
.then(function (messages) {
self.set('content', messages);
});
}
You could also do this in the model hook without the extra clutter, because the model hook will accept a promise directly:
model: function() {
var self = this,
room_id = App.getPath("current_room.id");
return this.store.filter(App.ChatMessage, {room_id: room_id}, function (msg) {
return msg.get('roomId') === room_id;
});
}
My reading of the source (DS.Store.find) shows that what you'd actually be receiving in this instance is an AdapterPopulatedModelArray. A FilteredModelArray would auto-update as you create records. There are passing tests for this behaviour.
As of ember.data 1.13 store.filter was marked for removal, see the following ember blog post.
The feature was made available as a mixin. The GitHub page contains the following note
We recommend that you refactor away from using this addon. Below is a short guide for the three filter use scenarios and how to best refactor each.
Why? Simply put, it's far more performant (and not a memory leak) for you to manage filtering yourself via a specialized computed property tailored specifically for your needs

Symfony2: File Upload via Doctrine does not fire the PrePersist/PreUpdate lifecycle-event

i tried to implement the file upload via doctrine/lifecycle callbacks as described here:
http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html#using-lifecycle-callbacks
So far it works, but the PrePersist/PreUpdate Event is not fired, the function "preUpload" is not called.
Functions like "upload" and "removeUpload" triggered by other lifecycle events are called correctly.
Does anyone have an idea why the event is not fired or a solution for this problem?
Thanks
I have another solution to this problem:
My entity has a field "updatedAt" which is a timestamp of the last update. Since this field gets set anyway (by the timestampable extension of Gedmo) I just use this field to trick doctrine into believing that the entitiy was updated.
Before I persist the entity I set this field manually doing
if( $editForm['file']->getData() )
$entity->setUpdateAt(new \DateTime());
This way the entity gets persisted (because it has changed) and the preUpdate and postUpdate functions are called properly.
Of course this only works if your entity has a field that you can exploit like that.
You need to change tracking policies.
Full explanation.
there's a much simpler solution compared with changing tracking policies and other solutions:
in controller:
if ($form->isValid()) {
...
if ($form->get('file')->getData() != NULL) {//user have uploaded a new file
$file = $form->get('file')->getData();//get 'UploadedFile' object
$news->setPath($file->getClientOriginalName());//change field that holds file's path in db to a temporary value,i.e original file name uploaded by user
}
...
}
this way you have changed a persisted field (here it is path field), so PreUpdate() & PostUpdate() are triggered then you should change path field value to any thing you like (i.e timestamp) in PreUpdate() function so in the end correct value is persisted to DB.
A trick could be to modify the entity no matter what..on postLoad.
1 Create an updatedAt field.
/**
* Date/Time of the update
*
* #var \Datetime
* #ORM\Column(name="updated_at", type="datetime")
*/
private $updatedAt;
2 Create a postLoad() function that will modify your entity anyway:
/**
* #ORM\PostLoad()
*/
public function postLoad()
{
$this->updatedAt = new \DateTime();
}
3 Just update that field correctly on prePersist:
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
$this->updatedAt = new \DateTime();
//...update your picture
}
This is basically a slight variation of #philipphoffmann's answer:
What i do is that i modify an attribute before persisting to trigger the preUpdate event, then i undo this modification in the listener:
$entity->setToken($entity->getToken()."_tmp");
$em->flush();
In my listener:
public function preUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof MyEntity) {
$entity->setToken(str_replace('_tmp', '', $entity->getToken()));
//...
}
}
Another option is to display the database field where the filename is stored as a hidden input field and when the file upload input changes set that to empty so it ends up triggering doctrine's update events. So in the form builder you could have something like this:
->add('path', 'text', array('required' => false,'label' => 'Photo file name', 'attr' => array('class' => 'invisible')))
->add('file', 'file', array('label' => 'Photo', 'attr' => array('class' => 'uploader','data-target' => 'iddp_rorschachbundle_institutiontype_path')))
Path is a property managed by doctrine (equal to the field name in the db table) and file is the virtual property to handle uploads (not managed by doctrine). The css class simply sets the display to none. And then a simple js to change the value of the hidden input field
$('.uploader').change(function(){
var t = $(this).attr('data-target');
//clear input value
$("#"+t).val('');
});
For me, it worked good when I just manually called these methods in the controller.
Do you have checked your metadata cache driver option in your config.yml file?If it exists, just try to comment this line:
metadata_cache_driver: whateverTheStorage
Like this:
#metadata_cache_driver: whateverTheStorage