How to pass data to layout in Zend 2? - layout

I've looked around, and there are a few links about this in Zend 1 at best. The best solution I've found is
// controller:
return array('viewValue' => 'something');
// layout.phtml
$children = $this->viewModel()->getCurrent()->getChildren();
$viewValue = $children[0]->viewValue;
In the layout, but it seems a little kludgy. It's even stranger because when I do get_class_methods on the layout it doesn't show a viewModel() method. Basically, I've looked around the API (and source code) and haven't found much. Zend 1 also seems to have more access; some old solutions involved getting the view, and directly modifying it, but in Zend 2 we return a new array (or view model). Any tips?
As for why, I'm using a jQuery mobile layout. So the heading is separate from content, but the structure should be the same (should belong in the layout).

The view models are hierarchically build. The top level view model is the "layout" and a child view model is injected after a controller is dispatched. This means you can build quite some tree of models for your application.
The top level view model (so the one representing the layout) is also located in the MvcEvent. That object is passed along in the application during bootstrap, but also linked to the controller when the controller is initialized.
The MvcEvent is accessible with $this->getEvent() in the controller, the view model by $event->getViewModel(). So to cut things short, just do this:
controller MyController
{
public function myAction()
{
$this->getEvent()->getViewModel()->foo = 'bar';
}
}
And in your layout.phtml:
<?php echo $this->foo; ?>

This pretty much is, how it is done. The new Zend\View-Components are pretty much all ViewModels nested into each other. Rob Allen has written a great article about it on how to work with variables throughout ViewModels.
Furthermore most often i think this approach isn't the best way. It'd be much better to have a ViewHelper or a Layout-Placeholder to do the job. Once again a great article has been written, this time by my dear Bakura, aka Michael Gallego.
Currently, either of those approaches would be your way to go.

Related

How to implement a SideNavigationViewController into a UIViewController?

A little confused on how to implement this into my main view controller. The example project shows it as a navigation controller, but I wasn't able to add an existing class on a fresh navigation controller or my current UIViewController. I could just be implementing it wrong though. Much appreciation if I can gain some traction on how to work with these.
If you could share some code that would be great.
How things work:
Navigation Controllers
There are currently 4 different Navigation Controllers that each offer their own features. The controllers can be used individually, or together.
SideNavigationViewController
The SideNavigationViewController offers 3 bodies to display content: mainViewController, leftViewController, and rightViewController.
MainViewController
The mainViewController must always exist, and has a facility for transitioning between view controllers using the transitionFromMainViewController method. Using this method is as easy as passing a UIViewController in its first parameter.
sideNavigationViewController?.transitionFromMainViewController(InboxViewController())
There are further parameters that allow for animations, completions, etc... to be set when transitioning between view controllers.
LeftViewController and RightViewController
The leftViewController and rightViewController can be set only once. To make them dynamic, you would need to use another Navigation Controller as its view controller.
NavigationBarViewController
The NavigationBarViewController offers a NavigationBarView along side the ability to manage two UIViewControllers, the mainViewController and the floatingViewController.
MainViewController
The mainViewController is like the SideNavigationViewController's mainViewController, and has a transitionFromMainViewController method that transitions from view controller to view controller in the body portion of the NavigationBarViewController.
FloatingViewController
The floatingViewController is a modalViewController and when set, it pops over MainViewController and NavigationBarView. Setting that value is like so:
navigationBarViewController?.floatingViewController = InboxViewController()
To close and hide the floatingViewController set it to nil, like so.
navigationBarViewController?.floatingViewController = nil
SearchBarViewController
The SearchBarViewController offers a single transitioning mainViewController, as well, has a SearchBarView at the top. Transitioning the mainViewController is like so:
sideNavigationBarViewController?.transitionFromMainViewController(InboxViewController())
MenuViewController
The MenuViewController is another controller that has a mainViewController, which takes the entire screen. Floating above it, is a MenuView that is used to transition between mainViewControllers.
menuViewController?.transitionFromMainViewController(InboxViewController())
Final Notes
These Navigation Controllers can be used in any combination and any amount of times creating a robust and intricate stack of controllers that act like one.
I hope this helps :)

Passing an object from a tabbarController to its subviews

I am trying to pass a simple core data objects info from a tabBarController to its subviews so that they each reference a different attribute of that object. As a newbie, I'm not sure even where to start. It doesn't seem to be as simple as passing the data from one tableView to another...
Thank you for any help.
If you are sharing the same object between (most of the) the view controllers of your tab bar controller, maybe the best architecture for this would be to have one central data object.
A typical pattern is a singleton, some kind of data manager that provides the object, but maybe that is overkill. Another is to keep references to all view controllers and update them one by one when something changes - also not very elegant.
What you really want is something like a global variable. You could (ab)use your app delegate (just give it a property that points to the object) or if you prefer even your tab bar controller (make a subclass, give it a property). In the latter case, every view controller could then get the object like this:
NSManagedObject *object = [(MyCustomTabBarController*)self.tabBarController object];
For example, you can check for changes and refresh your views in viewWillAppear.
A UITabBarController should be handling other view controllers, not handling data objects. How does the tab bar controller get the object reference in the first place? And what is the object you're sharing?
Let each of your subordinate VC's keep a pointer to the object, and then they can each follow the appropriate keypath to get to the entities they're designed to handle.
Tim Roadley's book Learning Core Data for iOS, in chapters 5 and 6, shows how to pass an object from one view controller (a table view) to a detail view. It doesn't sound like that's what you're asking, but just in case...
In response to comment:
I'm looking at a tableview, tap a cell, and then a tab bar controller slides in? That's not the usual visual metaphor for a tab bar; it's meant for changing modes for the entire program. See the Music app for a typical example: songs, playlists, artists.
But if you really need to do it that way, try this (I'm assuming you're using storyboards):
In prepareForSegue: in your tableview controller, tell the destination (tab bar controller) what object it's working with.
In the tab bar controller's -viewWillAppear, tell each of its tabs about the attribute: self.frobisherViewController.frobisher = self.myWidget.frobisher.
You could instead tell each of the component tabs about the top level object: self.frobisherViewController.widget = self.myWidget. But I like the first approach better because there is less linkage. The frobisherViewController now would need to know about both widgets and frobishers.
This ended up being very simple. I was trying to call the object in the child views initWithNibName which doesn't work. I ended up creating a setObject function and calling the properties I wanted in viewWillAppear.
Hope this helps someone.

create or inject ViewModel when building a "tabs" application

We try to build an application with a few tabs. As reference-project we use that example: http://slodge.blogspot.co.uk/2013/06/n25-tabs-n1-days-of-mvvmcross.html
To get the ViewModel-instances we need to create the tabs, we used the "HomeViewModel"-pattern as mentioned in that post: Create View Model using MVVMCross built in factory?
What I don't like at this approach is the initialisation of ViewModel's with "new". As far as I understand, it skips the whole ViewModel-Lifecycle (https://github.com/slodge/MvvmCross/wiki/View-Model-Lifecycle) which we really like. In our current project, we'd like to use the "start()" lifecycle-method, but it's never called due to initialisation with "new".
What worked for us was to go that way:
var loaderService = Mvx.Resolve<IMvxViewModelLoader>();
var vm = (UserListViewModel)loaderService.LoadViewModel(new MvxViewModelRequest(typeof(UserListViewModel), null, null, null), null);
So my question: Is that the way to do the job or is it just a dirty workaround and there is a much better solution?
Update: We came to that solution:
CreateTabFor<SettingsViewModel>("Settings", "settings");
//This method loads the ViewModel
private UIViewController CreateTabFor<TTargetViewModel>(string title, string imageName)
where TTargetViewModel : class, IMvxViewModel
{
var controller = new UINavigationController();
controller.NavigationBar.TintColor = UIColor.Black;
var viewModelRequest = new MvxViewModelRequest(typeof(TTargetViewModel), null, null, null);
var screen = this.CreateViewControllerFor<TTargetViewModel>(viewModelRequest) as UIViewController;
SetTitleAndTabBarItem(screen, title, imageName);
controller.PushViewController(screen, false);
return controller;
}
The 'viewmodel lifecycle' is an area of conflicting interests in MvvmCross. The root cause is the conflict between:
viewmodel's which are just the models for any view
viewmodel's which are specifically used within the 'ShowViewModel' navigation process
For simple 'whole page' User Experiences, the C-I-R-S viewmodel lifecycle is easy to support and to ensure it gets consistently used.
However, as soon as the user experience starts to merge in tabs, flyouts, hamburger menus, dialogs, split views, etc then:
the developers sometimes want to control viewmodel lifecycles themselves
it's not as easy for the framework to ensure that view models are always created, activated and tombstoned/rehydrated consistently
Personally, I like your approach - of trying to ensure all viewmodels are independent and all constructed the same way - but MvvmCross doesn't force this approach on all developers.
Specifically for tabs, most of the existing examples do use the 'owned sub-viewmodel' pattern that you've identified.
However, it should be relatively easy to implement other mechanisms if you want to - just as you already have.
In particular, you can:
use the loaderService directly - getting hold of it via Mvx.Resolve<IMvxViewModelLoader>();
use ShowViewModel with a custom presenter to create both views and viewmodels - the beginnings of this is illustrated in that N=25 video but you could take it much further and actually add the tabs in response to ShowViewModel calls.
use alternative calls to create the child tabs and their viewmodels inside the Views - e.g. where the Touch sample currently calls
var screen = this.CreateViewControllerFor(viewModel) as UIViewController;
this could easily be replace with something like:
var screen = this.CreateViewControllerFor<ChildViewModel>() as UIViewController;;
(or one of the other overloads from MvxCanCreateIosViewExtensionMethods.cs)
One repo where I know some users have taken some of these ideas and played with them is the Sliding menu repo - I think they have chosen to use this.CreateViewControllerFor<TViewModel> to create their view models. This may or may not be the way you choose to go - but it might be of interest for you to experiment with.

Accessing UITextView from another class

I've currently got two view controllers A and B, A uses a segue to push B and this works back and forth nicely, however based on some button presses in view controller B i want to change the text within a UITextView in controller A.
I've had a look at previous posts but i'm a novice at present and was confused by the way in which i should go about doing this.
I'd love to be able to get my head around how interactions are best done between various parts of the app. Also i was wondering if there is a way i can tap into a segue returning to trigger some other code.
Thanks
Edit:
OK perhaps i was a little bit limited with my information, from what i can gather reading other posts they are manually creating a variable for the viewcontroller (A) in viewcontroller (B) then accessing it in the second view controller (B) and setting a variable (property and synthesize) to edit that way, however i have the viewcontrollers embedded in a navigation controller and using a push setup in the storyboard (GUI system). I'm not sure if i have to create a variable to do this or if because they exist in the storyboard there is another way, if someone could just point me in the direction of a post that helps to explain this (i am looking at the moment too) i'd be very grateful.
OK well here's how i got it to work but i imagine there are:
A: Better ways to do it.
B: Changes depending on your setup.
I had my two view controllers embedded in a navigation controller, and used a segue push to access the second view controller each had a different class (all setup in the storyboard thing).
To get it working for me i did the following:
I have a singleton (a class that stores all my data but is global to the app so the variables can be accessed from anywhere in the app) this allows me to have variables that i can access from any view controller. A great tutorial on this can be found here
I then created an NSString variable (passedNote) and updated the value of this variable from the ViewController B, when my button was pressed.
Next when viewController A is loaded (in the viewWillAppear: (BOOL)animated method) i append or replace the value of the textview (dependent on some logic) I have with the global variable (passedNote).
Hope this helps anyone who had the problem.

MVC basics: Should I add a UIViewController, a Delegate or a Source to my custom view?

my question is about view controllers, delegates and all that in general. I feel perfectly comfortable with UIView, UIViewController, Delegates and Sources, like UITableView does for instance. It all makes sense.
Now I have implemented my first real custom view. No XIBs involved. It is an autocomplete address picker very much like in the Mail application. It creates those blue buttons whenever a recipient is added and has all the keyboard support like the original.
It subclasses UIView. There is no controller, no delegate, no source. I wonder if I should have either one of those? Or all, to make it a clean implementation.
I just cannot put my finger on the sense a view controller would make in my case. My custom view acts much like a control and a UIButton doesn't have a controller either.
What would it control in my view's case?
Some of my thoughts:
For the source: currently the view has a property "PossibleAutocompleteRecipients" which contains the addresses it autocompletes. I guess this would be a candidate for a "source" implementation. But is that really worth it? I would rather pass the controller to the view and put the property into the controller.
The selected recipients can be retrieved using a "SelectedRecipients" property. But views should not store values, I learned. Where would that go? Into the controller?
What about all the properties like "AllowSelectionFromAddressBook"? Again, if I compare with UIButton, these properties are similar to the button's "Secure" property. So they are allowed to be in the view.
The delegate could have methods like "WillAddRecipient", "WillRemoveRecipient" and so on and the user could return TRUE/FALSE to prevent the action from happening. Correct?
Should I maybe inherit from UIControl in the first place and not from UIView?
And last but not least: my custom view rotates perfectly if the device is rotated. Why don't all views? Why do some need a controller which implements ShouldAutoRotateToDeviceOrientation()?
Does it make sense what I wrote above? In the end I will provide the source on my website because it took me some time to implement it and I would like to share it as I have not found a similar implementaion of the Mail-App-like autocomplete control in MonoTouch.
I just want to learn and understand as much as possible and include it in the source.
René
I can answer part of your question.
I just cannot put my finger on the
sense a view controller would make in
my case
The ViewController is responsible for handling the View's state transitions (load, appear, rotate, etc) These transitions are used mainly when you use a navigation component (UINavigationViewController, UITabBarController). These components needs to received a ViewController that will handles the view's transitions.
For exemple, when you push a ViewController on a UINavigationViewController, it will cause the ViewDidLoad, ViewWillAppear, ViewDidAppear. It will also cause the ViewWillDisappear, ViewDidDisappear of the current ViewController.
So, if your application has only one portrait view, you don't need a ViewController. You can add your custom view as a subview of the main window.

Resources