ZendX Jquery Decorator - php

How use partial decorator in Jquery Element
I use this code for Form Element:
$title = new Zend_Form_Element_Text('title');
$title->setRequired(true)
->setAttrib('class', 'inputbox')
->setLabel('Title');
$title->viewScript = 'RegElement.phtml';
$title->setDecorators(
array(
array('ViewScript', array('class' => 'RegElement'))
)
);
But when i use Jquery Element i dont know how implement it:
$datePicker = new ZendX_JQuery_Form_Element_DatePicker(
"datePicker1", array("label" => "Date:")
);
$datePicker->viewScript = 'RegElement.phtml';
$datePicker->setDecorators(
array(
array('ViewScript', array('class' => 'RegElement'))
)
);
//views/scripts/RegElement.phtml
<li class="row <?php echo $this->class ?>">
<div class="cont-error">
<?php echo $this->formErrors($this->element->getMessages()); ?>
</div>
<div class="rowfields">
<?php echo $this->formLabel($this->element->getName(),
$this->element->getLabel()) ?>
<?php
echo $this->{$this->element->helper}(
$this->element->getName(),
$this->element->getValue(),
$this->element->getAttribs()
)
?>
</div>
<div class="hint"><?php echo $this->element->getDescription() ?></div>
</li>
And display this error:
Warning: Exception caught by form: Cannot render jQuery form element without at least one decorator implementing the 'ZendX_JQuery_Form_Decorator_UiWidgetElementMarker' interface.
I need display datePicker with same format. but I dont know how implement this interface.
thanks for your help.

It's because the regular ViewHelper decorator doesn't produce some proper code when used with ZendX_jQuery.
You have to use one decorator which implement ZendX_JQuery_Form_Decorator_UiWidgetElementMarker and there is one provided. UiWidgetElement
$datePicker->setDecorators(
array(
'UiWidgetElement',
array('ViewScript', array('class' => 'RegElement'))
)
);

Related

Yii alert widget

In view I have widget:
if ($content):
echo Alert::widget([
'options' => [
'class' => 'alert-info',
],
'body' => $content,
]);
endif;
That widget I want render not always, for example after save and atc. Now Now I have placed that widget between if condition, maybe exists some more clear way to render widget only in some cases.
I think Flash-Messages is what you want:
For Example:
In the controller you can do something like that:
<?php
Yii::app()->user->setFlash('success', "Data saved!");
$this->redirect(array('thing/view', 'id' => 1));
And in the view:
<?php if(Yii::app()->user->hasFlash('success')):?>
<div class="info">
<?php echo Yii::app()->user->getFlash('success'); ?>
</div>
<?php endif; ?>
And of course you can combine it with the alert-widget or with a custom-widget.
See full documentation: http://www.yiiframework.com/wiki/21/how-to-work-with-flash-messages/

placeholder attribute in zf2 problems

I cant get the value in the placeholder,the placeholder is empty
<div class="form_element">
<?php
//$name = $form->get('name');
$this->placeholder('name')->data="text value";
$name= $form->get('name');
echo $formLabel->openTag().$name->getOption('label')." ";
echo $this->formInput($name);
echo $formLabel->closeTag();
?>
</div>
In your code you used placeholder view helper (more about), and I don't see where you trying to get placeholder's value. It seems you asked about form input field placeholder attribute. If it true, then you must specify it as attribute. View helper placeholder is for different tasks.
Your form view helpers usage a little strange. May suggest my version of your code.
<div class="form_element">
<?php $name = $form->get('name'); ?>
<?php $name->setAttribute('placeholder', 'placeholder text'); ?>
<?php echo $formLabel($name); ?>
<?php echo $formInput($name); ?>
</div>
The better solution is to set placeholder in form element definition. For example:
<?php
use Zend\Form\Form;
class MyForm extends Form
{
public function __construct()
{
parent::__construct('<FORM_NAME>');
$this->add(array(
'name' => 'name',
'type' => 'Zend\Form\Element\Text',
'attributes' => array(
'placeholder' => '<PLACEHOLDER_TEXT>',
),
));
}
}

Yii Dependent-dropdown code not working

I am trying to setup a new application using the Yii framework that requires a dependent dropdown, so that when a user selects the jobSkillArea, the options for the next dropdown, jobSkillSpecialty, gets loaded using the built-in jQuery methods. I have copied and modified the code from things I found here and the Yii forums, but I am getting nothing, not even in Chrome's javascript console. Can anyone look at this and see where I've gone wrong? Thanks.
Here is the code in my view for the two dropdowns:
<div class="row">
<?php echo $form->labelEx($model,'jobSkillArea'); ?>
<?php
$list = array();
$list = CHtml::listData(validJobSkillAreas::model()->findAll(), 'JobSkillArea', 'JobSkillArea');
echo $form->dropDownList($model, 'jobSkillArea', $list,
array('prompt'=>'--Select Skill Area--'),
array(
'ajax'=>array(
'type'=>'POST',
'data'=>array('jobSkillArea'=>'js:this.value'),
'url'=>CController::createUrl('NewConsFormController/getSkillSpecialty'),
'update'=>'#'.CHtml::activeId($model,'jobSkillSpecialty')
)
)
);
?>
<?php echo $form->error($model,'jobSkillArea'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'jobSkillSpecialty'); ?>
<?php
$list = array();
$list = CHtml::listData(validJobSkillSpecialties::model()->findAll(),'jobSkillSpecialty','jobSkillSpecialty');
echo $form->dropDownList($model, 'jobSkillSpecialty', array(), array('prompt'=>'--Select Skill Specialty--'));
?>
<?php echo $form->error($model,'jobSkillSpecialty'); ?>
</div>
Then below is the code called by the first dropdown from my controller. The first find is to get the ID that links the parent with the child since I am not storing the KeyValue in the end product. The rest is as it came from the forums.
public function actionGetSkillSpecialty() {
$areaID = ValidJobSkillAreas::model()->find('JobSkillArea=:SkillArea',
array(':SkillArea'=>'$_POST[$jobSkillArea]'));
$data=ValidJobSkillSpecialties::model()->findAll('SkillAreaId=:SkillAreaId',
array(':SkillAreaId'=>$areaID->ID));
$list=array();
$list=CHtml::listData($data,'jobSkillSpecialty','jobSkillSpecialty');
echo "<option value=''>--Select Skill Specialty--</option>";
foreach($list as $value=>$jobSkillSpecialty) {
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($jobSkillSpecialty),true);
}
}
The view is a partial render within the _form view because that was the only way I could get the accordion widget to work with the fields I have. This is the accordion code that calls the jobDetails section that contains the two dropdown selection boxes.
<div id="accordion">
<?php
$this->widget('zii.widgets.jui.CJuiAccordion', array(
'panels'=>array(
'Job Details'=>$this->renderPartial('_partial_jobdetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
'Consultant Details'=>$this->renderPartial('_partial_consdetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
'Client Details'=>$this->renderPartial('_partial_clientdetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
'Internal Info'=>$this->renderPartial('_partial_internaldetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
'Form Requirements'=>$this->renderPartial('_partial_formsdetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
'JPMC Details'=>$this->renderPartial('_partial_jpmcdetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
),
// additional javascript options for the accordion plugin
'options'=>array(
'collapsible'=>true,
'active'=>false,
'autoHeight'=>false,
'heightStyle'=>'content',
),
'htmlOptions'=>array(
// HTML options you may need
),
));
?>
</div>
Please try the following code
View
<?php
echo CHtml::dropDownList('region_id','',
CHtml::listData($courses, 'course_id', 'course_name'),
array(
'prompt'=>'Select Region',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('loadcities'),
'update'=>'#city_name',
'data'=>array('region'=>'js:this.value'),
)));
echo CHtml::dropDownList('city_name','', array(), array('prompt'=>'Select City'),
);
?>
=================================================
controller function
public function actionLoadcities()
{
$data=City::model()->findAll('course='.$_POST['region'],
array(':region'=>(int) $_POST['region']));
$data=CHtml::listData($data,'city_id','city_name');
echo "<option value=''>Select City</option>";
foreach($data as $value=>$city_name)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($city_name),true);
}

zf2 form validation (zfcAdmin and BjyAuthorize related)

I'm facing validation problems integrating my custom module in zfcAdmin and BjyAuthorize.
My form class:
...
$formOptions = $this->settings->getFormSettings();
foreach ($formOptions as $field){
if (isset($field['field']))
$this->add($field['field']);
}
...
My filter class:
$formOptions = $this->settings->getFormSettings();
foreach ($formOptions as $filter){
if (isset($filter['filter']))
$this->add($filter['filter']);
}
...
Fields, filters and other options are retrieved from config file.
Basically everything works fine: form data can be added, edited or deleted from db.
Also after the zfcAdmin module installation no problem rose. Everything works fine using both 'site/mymodule' route and 'site/admin/mymodule' route: i can still add, edit and delete items from db.
Here the problem: I need some form elements (a Select in this particular case) editable/viewable only by administrator. (I can write a new controller/entity class 'ad hoc' for admin but i would like to use the same code for the whole site.)
I installed and configured bjyoungblood/BjyAuthorize module: it allowed me to display some form elements/fields only to admin but when i'm in edit mode a form validation error is displayed: "Value is required and can't be empty"
Here the code:
//view/mymodule/mymodule/update.phtml
<div id="page" style="margin-top: 50px;">
<?php if (isset($this->messages) && count($this->messages) > 0 ): ?>
<?php foreach ($this->messages as $msg): ?>
<div class="alert alert-<?php echo $this->escapeHtmlAttr($msg['type']); ?>">
<?php if (isset($msg['icon'])) echo '<i class="'.$this->escapeHtmlAttr($msg['icon']).'"></i> '; ?><?php echo $this->escapeHtml($msg['message']); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
<?php
$title = 'Edit Item';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url($this->route . 'mymodule/update', array('action' => 'update', 'id' => $this->id )));
$form->prepare();
$form->setAttribute('method', 'post');
$input = $form->getInputFilter();
?>
<?php echo $this->form()->openTag($form) ?>
<dl class="zend_form">
<?php foreach ($form as $element): ?>
<?php
//CHECK USER PRIVILEDGES
$elName = $element->getName();
$elResource = isset($this->form_options[$elName]['auth']) ? $this->form_options[$elName]['auth']['resource'] : "userresource";
$elPrivilege = isset($this->form_options[$elName]['auth']) ? $this->form_options[$elName]['auth']['privilege'] : "view";
//SHOW THE ELEMENT IF ALLOWED
if($this->isAllowed($elResource, $elPrivilege)):
?>
<?php if ($element->getLabel() != null): ?>
<dt><?php echo $this->formLabel($element) ?></dt>
<?php endif ?>
<?php if ($element instanceof Zend\Form\Element\Button): ?>
<dd><?php echo $this->formButton($element) ?></dd>
<?php elseif ($element instanceof Zend\Form\Element\Select): ?>
<dd><?php echo $this->formSelect($element) . $this->formElementErrors($element) ?></dd>
<?php else: ?>
<dd><?php echo $this->formInput($element) . $this->formElementErrors($element) ?></dd>
<?php endif ?>
<?php else: ?>
<?php
?>
<?php endif ?>
<?php endforeach ?>
</dl>
<?php echo $this->form()->closeTag() ?>
</div>
<div class="clear-both"></div>
My controller action
//controller
public function updateAction(){
$messages = array();
$id = (int)$this->getEvent()->getRouteMatch()->getParam('id');
$form = $this->getServiceLocator()->get('FormItemService');
$itemMapper = $this->getItemMapper();
$item = $itemMapper->findById($id);
$form->bind($item);
$request = $this->getRequest();
if($request->isPost()){
$form->setData($request->getPost());
if ($form->isValid()) {
die('c');//never here
$service = $this->getServiceLocator()->get('mymodule\Service\Item');
if ( $service->save($form->getData()) )
{
$messages[] = array(
'type' => 'success',
'icon' => 'icon-ok-sign',
'message' => 'Your profile has been updated successfully!',
);
}
else
{
$messages[] = array(
'type' => 'error',
'icon' => 'icon-remove-sign',
'message' => 'Profile update failed! See error messages below for more details.',
);
}
}else{
var_dump($form->getMessages());//Value is required and can't be empty
}
}
return array(
'messages' => $messages,
'form' => $form,
'id' => $id,
'form_options' => $this->getServiceLocator()->get('mymodule_module_options')->getFormSettings(),
'route' => $this->checkRoute($this->getEvent()->getRouteMatch()->getmatchedRouteName())
);
}
If user is not allowed to view the resource, the element is not echoed. So $request->getPost() has no value for that form element and an error is returned by isValid().
Has anyone solved a similar problem or can anyone point me to the right direction?
Thanks
The problem is that you don't do any security check in your FormFilter class, where you define your required fields.
The $form->isValid() function checks the posted data against those filter elements. So it's not enough to prevent the 'echo field' in your view, you still need to apply the security check to the filter element.
One other approach would be to make two forms one for the front end and one for the admin. Since the one for the admin will have the same fields plus one extra select field you can make the admin form extends the front end one. E.g.
class myForm
{
public function __construct(...)
{
// add fields and set validators
}
}
and the admin form could be:
class MyAdminForm extends myForm
{
public function __construct(...)
{
parent::__construct(...);
// add the extra field and extra validator
}
}
In that way even if you edit the front end form (or validators) the back end will always be up to date.
Hope this helps :),
Stoyan

Set Description in Zend Form

I am using Zend Framework in my project. I want to add a description/note to my forms, like
fields marked by * are mandatory
But i didn't found how to add a description to a form and how to use it with decorators.
Any help will be highly appreciated. Thanks.
There are two options:
Use a from decorator or
Extend Zend_Form_Element to create a custom
element
I would go with the latter, since it is very common to add parts of raw html code to forms not only before elements or after, but among them also.
You should do something like this:
class My_Form_Element_Raw extends Zend_Form_Element
{
protected $raw_html;
public function setRawHtml($value)
{
$this->raw_html = $value;
return $this;
}
public function getRawHtml()
{
return $this->raw_html;
}
public function render()
{
// you can use decorators here yourself if you want, or wrap html in container tags
return $this->raw_html;
}
}
$form = new Zend_Form();
// add elements
$form->addElement(
new My_Form_Element_Raw(
'my_raw_element',
array('raw_html' => '<p class="highlight">fields marked by * are mandatory</p>')
)
);
echo $form->render();
When extending Zend_Form_Element you dont need to overide setOption/s, getOption/s methods.
Zend internally uses set* and get* and protected properties to detect element options like in this case protected $raw_html; and public function setRawHtml($value) and public function getRawHtml()
Also naming your property $raw_html will accept both options of 'raw_html' and 'rawHtml' respectively
The easiest way to add additional text to your forms is to just add the appropriate html to the page view:
<div>
<h4>fields marked by * are mandatory</h>
<?php echo $this->form ?>
</div>
or use the viewScript decorator to control the entire form experience:
<article class="login">
<form action="<?php echo $this->element->getAction() ?>"
method="<?php echo $this->element->getMethod() ?>">
<table>
<tr>
<th>Login</th>
</tr>
<tr>fields marked by * are mandatory</tr>
<tr>
<td><?php echo $this->element->name->renderViewHelper() ?></td>
</tr>
<tr>
<td><?php echo $this->element->password->renderViewHelper() ?></td>
</tr>
<tr>
<td><?php echo $this->element->submit ?></td>
</tr>
</table>
</form>
</article>
However you can add a description to your form using $form->setDescription() then you can render that description with echo $this->form->getDescription(). It would probably be better to use these methods at the element level along with set and getTag() instead of the form level.
To provide the asterisk clue I just use css:
dt label.required:before {
content: "* ";
color: #ff0000;
}
I'm sure you can display any note you want using just css if you want.
class FormDecorators {
public static $simpleElementDecorators = array(
array('ViewHelper'),
array('Label', array('tag' => 'span', 'escape' => false, 'requiredPrefix' => '<span class="required">* </span>')),
array('Description', array('tag' => 'div', 'class' => 'desc-item')),
array('Errors', array('class' => 'errors')),
array('HtmlTag', array('tag' => 'div', 'class' => 'form-item'))
);
}
These are decorators for elements i usually use, they contain prefix with * and also description decorator.
then use code:
$element->setDescription('fields marked by * are mandatory');
Add description to one element,after that You can style description to appear somewhere in the bottomt, I hope this helps, have a nice day.

Categories