how to set the radio button's 'checked' attribute dynamically. - joomla

I've developed a Joomla 2.5 component that does ALMOST exactly what I want it to do. I have a form that contains a fieldset with 2 radio buttons (for "am" and "pm"). I have been unable to figure out how to set the appropriate button's 'checked' attribute based upon other information. It is trivial to set a default within the xml file that defines the form fields, but I don't see how I to do this dynamically.
It is possible? Have I missed something in the documentation that would explain how to do this??

In case you load the form from the view: in the display() method of view.html you will be loading your form:
$this->form = $this->get('Form');
This is invoking a model which in turns extends joomla.application.component.modelform; its getForm method loads the form:
$form = $this->loadForm('com_yourcomp.model', ...
This is what I gather from your description. If this is not the case you might want to move the suggested code below right after you load the form: this is the complete snippet that allows you to set the value of a field:
/// Load the form from the model:
$this->form = $this->get('Form');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
throw new Exception(implode("\n", $errors));
}
//... some logic ...
$this->form->setValue('businessid',null,$businessId);
$this->form->setFieldAttribute( 'businessid', 'readonly', 'true' );

Related

Customizing Optimizely (Episerver) block outer div css class

Is it possible to add css classes to auto-generated outer div for block element ?
I have a simple Block with a ViewModel and a Controller and I need modify this autogenerated outer div, or optionally remove it?
I looked at other answers to this question where it was recommended ie.
#Html.PropertyFor(model => model.CurrentBlock.ClientLogos, new
{
CustomTag = "ul",
CssClass = "list",
ChildrenCustomTagName = "li",
ChildrenCssClass = "list_item"
})
Problem is when I use this syntax, model has no CurrentBlock property ???
My model is bound to ViewModel, I'm not sure if it affects this. I am very new to Optimizely.
You can use custom tag and css class. In your example CurrentBlock is probably part of the viewModel, you can directly use model.ClientLogs. Alternativly if you want more control you can use editing attributes.
<h1 #Html.EditAttributes(x => x.Heading)>
/* Render the Heading property, unless it it empty, then use PageName as fallback */
#Model.Heading ?? #Model.PageName
</h1>
You can find more information about editing attributes here: https://docs.developers.optimizely.com/content-cloud/v11.0.0-content-cloud/docs/adding-editing-attributes-using-property-web-control

How do I auto fill field values in a section of a form that is loaded via ajax in Laravel 4?

I have a section of a form that dynamically loads different sets of fields based on the user's selection in a control. I'm using a javascript event handler to detect when the selection changes, and using AJAX (with HTML payload) to pull in the proper set of fields.
I would like to be able to use Laravel's Form::getValueAttribute() method to automatically fill in the form fields' values in both the static and dynamic form parts. However, the partial view that is loaded by my AJAX call does not have the same instance of the Form class as the view with my main Form, so I can't simply call getValueAttribute() in the partial.
My thought is to make the AJAX call a POST, and serialize the necessary data (a subset of Input::old() or the model data depending whether the page is loaded as the result of validation errors, or an UPDATE request) to send along with the POST so that the HTML fragment I get back has the values set properly.
Is this the best way to get what I want? If so, does Laravel have any tools to help with the serialization of form data? If not, what might be a better approach?
I've found an approach I like better. When the view is loaded normally I use AJAX as usual to load the partial. But when the view is loaded for a validation post-back or for editing, I use Laravel's Views' nest method to nest the partial view containing the proper fields directly into the response. The partial then has access to all the Input and error data I need. The user is still able to change the field set as usual but I put up a confirm prompt for them if they have already set some values in a field set they previously selected. If they decide to proceed anyway, the field set is cleared and a new field set is brought in via AJAX as usual.
My code looks something like this:
Controller:
public function newThing() {
if ( Request::session()->has('errors') ) {
// this is a validation post-back
return View::make('thing')
->nest('fields', 'fields_partial');
} else {
// just a normal unfilled form
return View::make('thing');
}
}
public function editThing() {
return View::make('thing')
->nest('fields', 'fields_partial');
}
View: thing.blade.php (just a snip of it)
...
<form>
...
<select id="picker">...</select>
<div class="sub-fields">
{{ isset($fields) ? $fields : '' }}
</div>
...
</form>
...
<script>
$('#picker').change(function() {
// if any .sub-fields inputs have been changed, get confirmation from the user
// if user confirms, do ajax stuff to replace .sub-fields contents with new field set
// otherwise cancel the change
});
</script>

Where to define a filter function for a form field in my Joomla component's preferences

I am creating a component in Joomla 2.5. This component has some options that are defined in its config.xml, so they can be set in the preferences of the component. Now I would like to apply a filter to one of these option fields, using the attribute filter="my_filter".
In the source code of JForm I saw the following lines at the very end of the implementation of JForm::filterField():
if (strpos($filter, '::') !== false && is_callable(explode('::', $filter)))
{
$return = call_user_func(explode('::', $filter), $value);
}
elseif (function_exists($filter))
{
$return = call_user_func($filter, $value);
}
That's what I needed for using a filter function defined by myself!
I managed to do this for form fields used in the views of my component. I defined the filter function as MyComponentHelper::my_filter(), where MyComponentHelper is a helper class which I always load in the very base of my component. And in the form's xml I added filter="MyComponentHelper::my_filter" to the fields that have to be filtered. However... when I am trying to apply the filter function to a form field in my component's preferences, I am not in my own component, but in com_config instead, so my helper class is not available!
So, therefore, my question: where to define my own filter function in such a way that it can be found and called by JForm::filterField() in com_config?? Help is very much appreciated.
May be it is too late, but this topic is only I found about that trouble. May be my solution will be helpfull to someone.
1) Add to tag of .xml form file the attribute 'addfieldpath' like this:
<fieldset name="basic" addfieldpath="PATH_TO_MY_EXTENSION/models/fields">
2) Modify filtered field description like this:
<field
name="MY_FIELD_NAME"
type="myfildtype"
label="MY_FIELD_LABEL"
description="MY_FIELD_DESC"
filter="JFormFieldMyFieldType::filter"
/>
3) Create the file 'PATH_TO_MY_EXTENSION/models/fields/myfildtype.php':
<?php
defined('JPATH_PLATFORM') or die;
JFormHelper::loadFieldClass('text'); // or other standard Joomla! field type
class JFormFieldMyFieldType extends JFormFieldText // or other standard Joomla! field type class
{
protected $type = 'MyFieldType';
public static function filter($value)
{
// filter code
return $value;
}
}
I had to deal with the same issue today. Here is what I did.
Our form field looks like this:
<field name="verwaltungskosten" type="text" class="form-control" size="40" label="Verwaltungskosten" labelclass="col-sm-2
compojoom-control-label"
filter="MyComponentFilterDouble::filter" required="true"/>
As you can see we have a filter. We've specified
MyComponentFilterDouble as class and filter as a method of this class.
If you have a look at libraries/joomla/form/form.php in the
FilterField function toward the end you'll see that the code will try
to execute our custom filter. Now here comes the tricky part. How does
Joomla know where our filters are located? Well, it doesn't! We have
to load our filters in advance. JForm doesn't come with a utility
class that could load a custom filter. I've decided to load our
Filters in our model in the getForm function. As you know each model
that extends from JModelAdmin should have a getForm function. This
function makes sure that we are loading the correct form from a .xml
file. So in this function just before I load the form I did:
JLoader::discover('MyComponentFilter', JPATH_ADMINISTRATOR . '/components/com_mycomponent/models/forms/filters');
The discover method will make sure to auto load our class when we need
it. This way it will be available to our form.
And there we go! Now when our model validates the form. It actually
always first performs filtering on the data. Now in our custom filter
we can modify the data and pass it back for validation. It's that
easy!
The above text is in quotes because I took it from my blogpost about that same issue over here: https://compojoom.com/blog/entry/custom-filtering-for-jform-fields
I think what you're asking about is actually adding custom validation to one of your form fields. If that's the case you actually need to be looking at adding server-side validation in addition to adding configuration. Pay particular attention to the 'addrulepath' in the example under the heading "Using configuration parameters as default value". You'll most likely end up extending JFormRule, of which I've included a very stripped-down example below.
<?php
/** headers */
defined('JPATH_PLATFORM') or die; // Joomla only
class JFormRuleCustom extends JFormRule
{
public $type = 'Custom';
public function test(&$element, $value, $group = null, &$input = null, &$form = null) {
return /* true for passed validation, false for failed validation */
}
}
When you've got that down you can add the validation "custom" to your form fields like so:
<field
name="pw1"
type="password"
label="COM_NEWUSER_UPDATE_LABEL_PASSWORD1"
description="COM_NEWUSER_UPDATE_DESCRIPTION_PASSWORD1"
message="COM_NEWUSER_UPDATE_ERROR_PASSWORD1"
size="40"
required="true"
validate="custom"
minlength="5"
maxlength="20"
specials="!##$%^&*"
/>
Hopefully that answers your question and didn't go totally off-topic.

Yii Displaying Image dynamically dependent on dropdown

I'm trying to display an image but is dependent on a dropdown list in Yii. I can get the image from the database and display it, but how to do it dynamically depending on the choice from the dropdown?
Here is the reference: http://www.yiiframework.com/wiki/24/creating-a-dependent-dropdown#hh0 but, let me show you how to do it.
First all all, we need a div where the image will be displayed; I'll create one whose id will be 'img'. Then, the ajax request is specified inside the dropdownlist() as follows:
<?php echo $form->labelEx($model,'attribue'); ?>
<?php echo $form->dropDownList($model,'attribute',
array(/*The options in the DropDownList*/),
array(
'ajax'=>array(
'type'=>'POST',
'url'=>CController::createUrl('YourController/actionWhichEchoesTheImage'),
'update'=>'#img',
)));
?>
<div id="img"> // <---- the result of the ajax call will be displayed here
</div>
In the 'url' attribute we specify the function which will be called when the ajax request triggers. In the 'update' attribute we specified the div where will be displayed the result of calling that function (the image).
Finally, we have to declare the action actionWhichEchoesTheImage(). Let's declare it in the current controller. It would look something like this:
public function actionWhichEchoesTheImage()
{
if(isset($_POST['ModelName']['attribute']))
/*Here goes your code to load the image*/
echo CHtml::image(//Check the reference to see how to set this function);
}
Check CHtml::image() here: http://www.yiiframework.com/doc/api/1.1/CHtml/#image-detail

Is it good practice to add own file in lib/Varien/Data/Form/Element folder

I need to create module in Magento which will have few database tables. One of the function of the module is adding multiple images.
For example while being on the "Add new item" or "Edit item" page in the admin, from the left side I have tabs, one of them is "Item Images". When being clicked I want the content of this tab to be my own custom one.
After digging into the code, found out that the way it renders this content, Magento is using one of the Varien_Data_Form_Element classes for each element in the full form. I want to add my own class here that will render form elements the way I want.
Is this a good practice to do so, or there is some other more elegant way of adding own content in the admin forms?
EDIT: I must add that none of the existing classes is helping my problem.
SOLUTION EDIT:
I have a controller in my custom module that is in Mypackage/Mymodule/controllers/Adminhtml/Item.php. In the editAction() method which I am using for adding and creating new items, I am creating 2 blocks, one for the form and one left for the tabs:
$this->_addContent($this->getLayout()->createBlock('item/adminhtml_edit'))
->_addLeft($this->getLayout()->createBlock('item/adminhtml_edit_tabs'));
$this->renderLayout();
The Block/Adminhtml/Edit/Tabs.php block is creating 2 tabs on the left: General Info and Item Images, each of them are rendering different content on the right side using Block classes.
protected function _beforeToHtml()
{
$this->addTab('item_info', array(
'label' => Mage::helper('mymodule')->__('Item Info'),
'content'=> $this->getLayout()->createBlock('item/adminhtml_edit_tab_form')->toHtml(),
));
$this->addTab('item_images', array(
'label' => Mage::helper('mymodule')->__('Item Images'),
'active' => ( $this->getRequest()->getParam('tab') == 'item_images' ) ? true : false,
'content' => $this->getLayout()->createBlock('item/adminhtml_images')->toHtml(),
));
return parent::_beforeToHtml();
}
I wanted the tab item_images to render my own form elements and values, not the default varien form elements.
class Mypackage_Mymodule_Block_Adminhtml_Images extends Mage_Core_Block_Template
{
public function __construct()
{
parent::__construct();
$this->setTemplate('item/images.phtml'); //This is in adminhtml design
}
public function getPostId()
{
return $this->getRequest()->getParam('id');
}
public function getExistingImages()
{
return Mage::getModel('mymodule/item')->getImages($this->getPostId());
}
}
Then in the template app/design/adminhtml/default/default/template/item/images.phtml you can use these values:
//You can add your own custom form fields here and all of them will be included in the form
foreach($this->getExistingImages() as $_img):
//Do something with each image
endforeach;
//You can add your own custom form fields here and all of them will be included in the form
No, it's not. You should never edit or add to files that provided by a vendor. If you absolutely must replace a class file you should use the local code pool. For example, if you wanted to change the behavior of a text field,
lib/Varien/Data/Form/Element/Text.php
You should place a file in the local or community code pool
app/code/local/Varient/Data/Form/Element/Text.php
However, doing the replaces the class, and it becomes your responsibility to maintain compatibility with future versions. That means if Magento Inc. changes lib/Varien/Data/Form/Element/Text.php, you need to update your version to be compatible.
Based on what you said I'd look into creating a class rewrite for the Block class that renders the form.

Resources