Customize fieldset output from form collection in ZF2 - zend-framework2

I have correctly set up a form in ZF2, which includes several elements and a collection containing a fieldset that can be duplicated by the user. All works fine, but I need more control on how the fieldset renders, ie. I need to add other things between some elements in the fieldset, rather than just output them one after another.
I'm not expert in ZF2, but from research I seem to understand that you can declare a custom fieldsetHelper in the formCollection, however:
I can't manage to do so; I tried to extend the FormCollection class, and adding protected $fieldsetHelper = 'myFieldsetHelper';, which is also declared in the module config, but I get:
Fatal error: Call to undefined function myFieldsetHelper()
I'm familiar with extending FormRow helper, but I don't know how the fieldset helper should be written (I only need to add my extra stuff between some elements), and can't find any example on the web.
Any help, please?

You can use other view helpers to customize the forms layout in your view script such as FormLabel, FormText, etc.
Please see my answer here
EDIT
You can also loop through all the collection elements in your view script and render separately.
<?php
foreach ($this->form->get('collection') as $fieldset) {
echo $this->formText($fieldset->get('elementName'));
}
?>

Related

How do I encapsulate calls to ViewBag or ViewData?

I want to be able to able to register script blocks in the ViewData or ViewBag and then unload them on my layout page at the correct position.
I tried writing a #function {} in my _Layout but this cannot be called from my Views.
So how do I write a class that allows me to do something similar to
#Something.registerscript("myscript.js")
And then on the Layout page
#Something.RenderScripts()
I saw an implementation using the singleton pattern here...
Add CSS or JavaScript files to layout head from views or partial views
But im afraid that will cause problems as this should be dynamic not static!
Is this for a generic solution or do you just want to include scripts files from within your views? For the latter, you can always create a section called "Head" or whatever which is created within the <head>-element.
For example:
_layout.cshtml
<html>
<head>
#RenderSection("Head", false)
</head>
...
</html>
View.cshtml
#section Head
{
<script type="text/javascript">...</script>
}
I wouldn't propose this as an answer, since there is the possiblity that you do want to actually do more than this (as far as I know, this doesn't work with EditorTemplates etc.). But in case you were thinking to complicated, this works very easy.
Why would you use ViewBag for this ? If you want to create something that has request-wide scope, use HttpContext.Current.Items - in your case implement one storing helper method, and one "render everything stored" method.
Viewbag or it's close relative viewdata I'd say are the best collections to use for this, as your context appears to be within the view. Where would you register the script & where would you render it?
You could, I think, write helper extensions to wrap up the register & render side of things. I believe helper methods can access viewdata. You'd get the added bonus of the abstraction away from the actual store you used, as you'd only reference it from these helper methods.

Can a controller influence the _layout.cshtml file?

I'm stuck! I'm under the impression that the _layout.cshtml file is used for MasterPage-like content. Everything there is rendered on every page. Naturally, I want to write the code for rendering my sidebar menu in that file.
I want to dynamically display a list of Categories from my DB, but I'm having a problem with passing the actual model of categories to Layout.cshtml since it seems no controller actually touches it.
Any suggestions?
Otherwise please tell me how to approach this problem. I've been wracking my brain for the past three days and still no elegant solution.
I need to:
Dynamically fetch a list of Categories from the DB.
Display this list of Categories on every single view. (Hence the use of _layout.cshtml)
Elegantly handle each different categories click.
I'm at my wits end. :P How would you solve this?
_layout.cshtml
#if(isSectionDefined("Categories"))
{
<div id="sidebar">
#RenderSection("Categories", required: false )
</div>
}
index.cshtml
#section Categories {
<ul>
<li>Category One</li>
<li>Category Two</li>
<li>Category Three</li>
</ul>
}
see this : http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx
Any viewmodel that you pass to your view is automatically available within your master page. If you do not use RenderAction/Action which is the best approach, then you must create the necessary master page data in every action and add it to viewdata - either by having a common base class for your strongly typed viewmodel that contains all master page data or by using the viewdata dictionary.
I would strongly recommend that you go down the html.action approach though. In this way, you have a totally separate controller action for dealing with your list of categories. This action can retrieve the neccesary category data and return the categorylist usercontrol as a partialview and you will not have to worry about polluting all your other actions with this data.
As I see it, ViewData (and its relatives like ViewBag, Model, etc.) is meant for the specific current view. Your _Layout.cshtml is not specific to the current view; and it would be awkward if EVERY controller would have to pass the categories data in addition to whatever else data it needs to pass for the view.
Instead, what I do, is provide a static method in one of my helper classes that retrieves the categories from the DB. I also do some caching there, so that I do not have to hit the DB on every single request. The _Layout.cshtml then simply calls this static method. Simple and elegant.
If you wish, you can bring this out to a partial view, make it a helper method, whatever.
One note of caution though - my custom error view also uses the same _Layout.cshtml, and if the DB goes down, you get an exception trying to display the exception. ASP.NET MVC is smart enough to detect this and abort processing, but you're left with a nondescript default error page. What I did was to place try...catch statements around these dangerous calls, which quietly ignore the exception if the current page is the error view.
I've achieved something similar by having my ViewModels implement an Interface which has members that contain the menu data. In my action method I set that data. Then in my view I check to see if my view-model implements that inteface, pull the menu data out and render the menu (in a partial view actually)

Encapsulating User Controls in ASP.NET MVC

Sorry if this is a basic question - I'm having some trouble making the mental transition to ASP.NET MVC from the page framework.
In the page framework, I often use ASCX files to create small, encapsulated chunks of functionality which get inclded in various places throughout a site. If I'm building a page and I need one of these controls - I just add a reference and everything just works.
As far as I can tell, in MVC, the ASCX file is just a partial view. Does this mean that wherever I want to add one of these units of functionality I also have to add some code to the controller's action method to make sure the relevant ViewData is available to the ASCX?
If this is the case, it seems like a bit of a step backwards to me. It means, for example, that I couldn't just 'drop' a control into a master page without having to add code to every controller whose views use that master page!
I suspect I'm missing something - any help would be appreciated.
Thanks,
- Chris
As far as I can tell, in MVC, the ASCX
file is just a partial view. Does this
mean that wherever I want to add one
of these units of functionality I also
have to add some code to the
controller's action method to make
sure the relevant ViewData is
available to the ASCX?
Yes.
However, you can use a RenderAction method in your view instead of RenderPartial, and all of your functionality (including the data being passed to the sub-view) will be encapsulated.
In other words, this will create a little package that incorporates a controller method, view data, and a partial view, which can be called with one line of code from within your main view.
Your question has been answered already, but just for sake of completeness, there's another option you might find attractive sometimes.
Have you seen how "controls" are masked on ASP.NET MVC? They are methods of the "HtmlHelper". If you want a textbox bound to "FirstName", for example, you can do:
<%= Html.Textbox("FirstName") %>
And you have things like that for many standard controls.
What you can do is create your own methods like that. To create your own method, you have to create an extension method on the HtmlHelper class, like this:
public static class HtmlHelperExtensions
{
public static string Bold(this HtmlHelper html, string text)
{
return "<b>" + text + "</b>\n";
}
}
Then in your view, after opening the namespace containing this class definition, you can use it like this:
<%= Html.Bold("This text will be in bold-face!") %>
Well, this is not particularly useful. But you can do very interesting things. One I use quite often is a method that takes an enumeration and created a Drop Down List with the values from this enumeration (ex: enum Gender { Male, Female }, and in the view something like Gender: <%= Html.EnumDropDown(Model.Gender) %>).
Good luck!
You can render a partial view and pass a model object to.
<% Html.RenderPartial("MyPartial", ViewData["SomeObject"]);
In your partial view (.ascx) file, you can then use the "Model" object (assuming you've inherited the proper object in your # Control deceleration) to do whatever you need to with that object.
You can, ofcourse, not pass and Model and just take the partial view's text and place it where you want it.
In your main view (.aspx file), you will need to define the proper object in the ViewData that you're passing to the partial view.
Another method you can do is use:
<% Html.RenderAction("MyAction", "MyController", new { Parameter1="Value1"}) %>
What the previous method does is call a controller Action, take its response, and place it where you called the "RenderAction()" method. Its the equivalent of running a request against a controller action and reading the response, except you place the response in another file.
Google "renderaction and renderpartial" for some more information.

Grails: Supplying Data to a Global UI Element

Please pardon this newbie question...
In Grails, if I want a partial to be embedded in a layout so that it appears globally, which requires live data, let's say a list of categories, where is the best place to pull the category data to feed it into the view?
I realize this is a very basic question, but I haven't seen this covered in any tutorials yet.
I started this as a comment to Bill James's answer but I figured it might be longer. Bill suggeseted using groovy code inside ${} to make the template (called partial in Rails) work globally:
<g:each in="${ Category.findAll() }" var="cat" />
But, you should not just add code if you dont feel like it might mess up your tidy xml/html. You can always put it in a closure inside a TagLib and thus make it a Tag. The closure must have no parameters, or an 'attr' parameter, or an 'attr' and 'body' parameters but other signatures are invalid.
class CustomTagLib {
static namespace = 'cus'
def categories = { attr, body ->
g.each( in: Category.findAll(), var: attr?.var ?: 'categories' )
}
}
Then you can use that tag into the template with the namespace you chose:
<cus:categories />
Personally I prefer using tags since most of the time it is a reusable code, so it's better for not violating the DRY principle.
You want to put it in grails-app\views\layouts\main.gsp. That's the default layout that most generated code (and likely most examples that you'll see) will use.
Check out the sitemesh section of the grails documentation.
I think you're trying to ask... "How do I feed the category data to the view when I don't know which action caused the page to render, so the action can't add the data to the model?" If that's so, you can use Groovy code directly in the ${} block, such as:
<g:each in="${ Category.findAll() }" var="cat" />
Note that findAll is added to every Model class, and can be called statically (via the classname, not an instance).
Hope this helps

MVC Contrib Input Builders and Spark View Engine

In Eric Hexter's Input Builders, different templates use different strongly-typed models; for example String uses PropertyViewModel<object>, DateTime uses PropertyViewModel<DateTime>, Form uses PropertyViewModel[], and so forth. Spark View Engine doesn't seem to allow this, because all elements that compose the presentation (masters, views, partials, etc.) are compiled into a single class.
If I try to setup a view involving more than one template, I get the following exception:
Only one viewdata model can be declared. PropertyViewModel<DateTime> != PropertyViewModel<object>
If leave just one viewdata declaration, I get another exception about the passed model item mismatching the required one.
It seems like I will have to give up either the Input Builders or Spark, which is sad because I really love both. So I thought I'd ask here to see if anybody has already figured this out.
Thanks.
You can always use <% Html.RenderPartial() %> for partial view rendering with different model. This will create more than one view class.

Resources