How to add javascript function in a zend dojo form? - php

I'm fighting with a Zend_dojo_form.
Here is (part of) the code:
class Application_Form_RegistrationForm extends Zend_Dojo_Form {
private $_user;
private $_admin;
private $_teamadmin;
private $_newuser;
private $_redirect;
public function __construct($admin = false, $user = null, $redirect = '') {
//blablabla
parent::__construct();
}
public function init() {
Zend_Dojo::enableForm($this);
$this->setMethod('post');
$this->setAttribs(array(
'id' => 'formRegistration',
'name' => 'formRegistration',
));
//some decorators
if ($this->_admin) {
$this->addElement(
//blabla + inline javascript
'onChange' => "if(this == ".E_UserRole::OPERATOR.") dojo.query(\".perms\").style({ display:\"block\" }); else dojo.query(\".perms\").style({ display:\"none\" }); "
)
);
}
if (Application_Manager_Login::hasRole(E_UserRole::ADMIN)) {
//add some display:none elements
$permission_decorators = array(
"DijitElement",
"Errors",
array(array("data" => "HtmlTag"), array("tag" => "td", "class" => "perms", "style"=> "display:none", )),
array("Label", array("tag" => "td", "class" => "perms", "style"=> "display:none", 'escape' => false, 'requiredSuffix' => ' <span class="red">*</span>')),
array(array("row" => "HtmlTag"), array("tag" => "tr"))
);
//hidden element
$this->addElement(
'CheckBox',
'permission_content',
array(
'decorators' => $permission_decorators,
'label' => 'Gestione contenuti',
'checkedValue' => true,
'uncheckedValue' => false,
'checked' => $this->_user->permission_content,
)
);
}
//submit button and other stuff
}
}
As you can see I've put some inline javascript to show/hide some options when the user_role changes.
Now the situation is a bit complex. I could keep writing inline javascript but I'd like to declare a js function on the beginning and just call it from the onchange Event.
Since this form is called by several controllers I won't add this function manually each time a
new RegistrationForm();
is called.

Ok, I came up with this solution..
function addJavascript(){
echo "<script>
function toggle( e ){
alert(e);
if(e == ".E_UserRole::USER." || e == ".E_UserRole::ADMIN."){
dojo.query(\".perms\").style({ display:\"none\" });
}
else {
dojo.query(\".perms\").style({ display:\"block\" });
}
}
</script>
";
}
I declared this function inside the class and I just call it in the beginning with:
$this->addJavascript();
then in the onChange i call the toggle function I need (function that will become more complex, I need this workaround to make it readable) with:
$this->addElement(
//blabla
'onChange' => "toggle(this)",
)
);
hope this helps someone else :)

Related

Magento custom admin module wysiwyg integration

I've created an admin module based off of the tutorial here. I'm attempting to change two of my form inputs to wysiwyg editors based off of information found here. However, whenever I load the edit page I get an error Call to a member function setCanLoadTinyMce() on a non-object. $this->getLayout()->getBlock('head') var_dumps to false.
Namespace/Slides/Block/Adminhtml/Slide/Edit.php looks as follows
class Namespace_Slides_Block_Adminhtml_Slide_Edit
extends Mage_Adminhtml_Block_Widget_Form_Container
{
protected function _prepareLayout()
{
parent::_prepareLayout();
if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
}
}
protected function _construct()
{
//... Construction stuff
}
}
Namespace/Slides/Block/Adminhtml/Slide/Edit/Form.php
class Cfw_Slides_Block_Adminhtml_Slide_Edit_Form
extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
//...Do some things first, like create the fieldset..
//Add the editable fields
$this->_addFieldsToFieldset($fieldset, array(
'foreground_image' => array(
'label' => $this->__('Foreground Image'),
'input' => 'image',
'required' => false,
),
'background_image' => array(
'label' => $this->__('Background Image'),
'input' => 'editor',
'required' => true,
'config' => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
'wysiwyg' => true,
),
'description' => array(
'label' => $this->__('Text Overlay'),
'input' => 'editor',
'required' => false,
'config' => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
'wysiwyg' => true,
)
));
return $this;
}
protected function _addFieldsToFieldset(
Varien_Data_Form_ElementFieldset $fieldset, $fields)
{
$requestData = new Varien_Object($this->getRequest()->getPost('slideData'));
foreach ($fields as $name => $_data) {
if ($requestValue = $requestData->getData($name)) {
$_data['value'] = $requestValue;
}
//Wrap all fields with slideData group
$_data['name'] = "slideData[$name]";
//Generally, label and title are always the same
$_data['title'] = $_data['label'];
//If no new value exists, use the existing slide data.
if (!array_key_exists('value', $_data)) {
$_data['value'] = $this->_getSlide()->getData($name);
}
//Finally, call vanilla funcctionality to add field.
$fieldset->addField($name, $_data['input'], $_data);
}
return $this;
}
}
I'm not sure if you need it, but here's my file structure as well
Namespace
-Slides
--Block
---Adminhtml
----Slide
-----Edit
------Form.php
-----Edit.php
-----Grid.php
----Slide.php
--controllers
---Adminhtml
----SlideConroller.php
--etc
---config.xml
--Helper
---Data.php
--Model
---Resource
----Slide
-----Collection.php
----Slide.php
---Slide.php
--sql
---namespace_slides_setup
----install-0.0.1.php
The issue is that Magento cannot find your head block.
Instead of using:
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
Try calling it like this:
Mage::app()->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
If that doesn't work, it's a different issue but the problem is still that Magento can't find the head block.
I imagine you no longer need a solution for this, but I ran into the same issue using the same tutorial that you did.
The 'head' block (and thus setCanLoadTinyMce()) was unavailable in the Edit.php and the Form.php via the _prepareLayout() function.
The 'head' block was available in the controller(SlideController.php in your case) between $this->loadLayout() and $this->renderLayout within the editAction() function.
In SlideController.php change
$this->loadLayout()
->_addContent($brandBlock)
->renderLayout();
to
$this->loadLayout() ;
$this->_addContent($brandBlock);
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
$this->renderLayout();

How to display confirm box before submitting an AJAX form in Drupal 7?

Using Drupal 7 form API, How can I prompt javascript confirm box before submitting an AJAX form? I have tried different possible ways to do this but no success. Here is the code:
function create_list_form($form, &$form_state) {
$form['list_name'] = array(
'#type' => 'textfield',
'#required' => TRUE,
'#title' => 'List Name'
'#attributes' => array()
);
$form['list_desc'] = array(
'#type' => 'textfield',
'#required' => TRUE,
'#title' => 'List Desc'
'#attributes' => array()
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#attributes' => array('class' => array('use-ajax-submit')),
'#value' => 'Create List'
);
return $form;
}
Here is the Javascript code:
Drupal.behaviors.module = {
attach: function() {
jQuery('#edit-submit').click(function(){
if(!confirm('Are you sure?'))
return false;
});
}
}
I have found the solution. We can do it by overriding beforeSerialize() function:
Drupal.behaviors.module = {
attach: function() {
Drupal.ajax['edit-submit'].beforeSerialize = function () {
if(confirm('Are you sure?'))
return true;
else
return false;
}
}
}
Did you try to add an eventlistener on your button?
function show_confirmation() {
if (confirm("Do you want to submit?")){
// here you can do something before it gets submitted
} else {
// return false prevents the form from submitting
return false;
}
}
var button = document.getElementById('button_name');
button.addEventListener('click', show_confirmation);
Edit: You can use this one if you want to make your function re-usable:
function your_callback_func() {
// This could be any code for example your AJAX code etc
}
function show_confirmation(your_callback_func) {
if (confirm("Do you want to submit?")){
your_callback_func()
} else {
// return false prevents the form from submitting
return false;
}
}
var button = $('#button_name');
button.click(function() {
show_confirmation(your_callback_func);
});

Magento: Admin form action not correct

I want to add a new form to the edit customer page, so far so good, using rewrites to customer_edit_tabs i was able to add a tab and my admin form to the page. Code looks like this.
protected function _beforeToHtml()
{
$this->addTab('extraoptions', array(
'label' => Mage::helper('customer')->__('Extra options'),
'class' => 'ajax',
'url' => $this->getUrl('module/adminhtml_tabs/info', array('_current' => true)),
));
This adds my tab corrently. From there the link on the tabs controller:
public function infoAction()
{
$this->_init();
$this->getResponse()->setBody(
$this->getLayout()->createBlock('module/adminhtml_tabs_edit')->toHtml()
);;
}
This links to my form container on Block/Adminhtml/Tabs/Edit.php
class Namespace_Module_Block_Adminhtml_Tabs_Edit extends Mage_Adminhtml_Block_Widget_Form_Container{public function __construct()
{
parent::__construct();
$this->_objectId = 'id';
$this->_mode = 'edit';
$this->_blockGroup = 'module';
$this->_controller = 'adminhtml_tabs';
$this->_updateButton('save', 'label', Mage::helper('module')->__('Save'));
}
public function getHeaderText()
{
return Mage::helper('module')->__('Extra Options');
}
}
My Block/Adminhtml/Tabs/Edit/Form.php
class Namespace_Module_Block_Adminhtml_Tabs_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
public function __construct()
{
parent::__construct();
}
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'info_form',
'action' => $this->getUrl('module/adminhtml_tabs/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data'
)
);
$fieldset = $form->addFieldset('extra_options', array('legend' => Mage::helper('module')->__('Extra Options Fieldset')));
$fieldset2->addField('extra', 'text', array(
'name' => 'zip',
'title' => Mage::helper('module')->__('extra'),
'label' => Mage::helper('module')->__('extra data'),
'maxlength' => '250',
'required' => false,
));
$form->setUseContainer(true);
}
protected function _prepareLayout()
{
return parent::_prepareLayout();
}
Everything is fine, I have a new button below the default save customer buttons, but this save button does not update the action, so if i click it, it goes to the default customer/edit/save action, it does not tell me the method does not exist which it should. My guess is that there is something wrong with the container but i have tried three tutorials with little differences to no avail, hope someone can help and even maybe someone will find my code helpful.
In this line of code:
'action' => $this->getUrl('module/adminhtml_tabs/save')
You are telling Magento to look for a module named module, a controller aliased adminhtml_tabs, and a saveAction() method within that file.
You need to figure out where you want to send the user when a save needs to be performed, and then place it there (e.g. the route to your controller->saveAction() method).
I decided to create a new button to save with a custom action. On the container:
$this->_addButton('save', array(
'label' => Mage::helper('adminhtml')->__('Save Extras'),
'onclick' => 'document.myform.submit();',
'class' => 'save',
),-1,5);
This did the trick.

Zend Honeypot Validation

On my bootstrap I don't have a class, it's a simple php file:
I have added there:
$loader = Zend_Loader_Autoloader::getInstance ();
$loader->setFallbackAutoloader ( true );
$loader->suppressNotFoundWarnings ( false );
//resource Loader
$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
'basePath' => APPLICATION_PATH,
'namespace' => '',
));
$resourceLoader->addResourceType('validate', 'validators/', 'My_Validate_');
$loader->pushAutoloader($resourceLoader);
Then, in application/validators I have:
class My_Validate_Spam extends Zend_Validate_Abstract {
const SPAM = 'spam';
protected $_messageTemplates = array(
self::SPAM => "Spammer"
);
public function isValid($value, $context=null)
{
$value = (string)$value;
$this->_setValue($value);
if(is_string($value) and $value == ''){
return true;
}
$this->_error(self::SPAM);
return false;
}
}
In my form constructor I have:
$this->addElement(
'text',
'honeypot',
array(
'label' => 'Honeypot',
'required' => false,
'class' => 'honeypot',
'decorators' => array('ViewHelper'),
'validators' => array(
array(
'validator' => 'Spam'
)
)
)
);
And finally on my view I have:
<dt><label for="honeypot">Honeypot Test:</label></dt>
<dd><?php echo $this->form->honeypot;?></dd>
Despite all this, I receive my form data, either by filling or not filling that text field.
What am I missing here ?
Thanks a lot in advance.
Thats expected behaviour. $honeypot is a form-element. Now, let's say you have a form $hp_form where $honeypot is one of the elements assigned.
Now, in your controller simply use something like:
if ($hp_form->isValid($this->getRequest()->getPost())) {
// do something meaningful with your data here
}
Probably you also want to check, if you display the form for the first time or if the user submitted the form:
if ($this->getRequest()->isPost() &&
false !== $this->getRequest()->getPost('submit_button', false)) {
if ($hp_form->isValid($this->getRequest()->getPost())) {
// do something meaningful with your data here
}
}
...assuming that your submit button has the id 'submit_button'.
Hope this helps
Bye,
Christian
replace :
if (is_string($value) and $value == ''){
return true;
}
by :
if (strlen($value) > 0)
{
return true;
}

adding img tag in zend form

I'm building a form with a class extending Zend_Form.How can I add an img tag inside the form?I also need to add a class to it and align attribute
This is the final result I want to achieve:
<span class="myElement"><img src="myPath" align="middle" class="myClass"/>
<input type="text"></span>
I didnt find much about Zend_Form_Element_Image's documentation
thanks
Luca
Have in library/Application/Form/Element/Img.php
class Application_Form_Element_Img extends Zend_Form_Element_Xhtml
{
public $helper = 'formImg';
public function loadDefaultDecorators ()
{
parent::loadDefaultDecorators ();
$this->removeDecorator ('Label');
$this->removeDecorator ('HtmlTag');
$this->addDecorator('HtmlTag', array (
'tag' => 'span',
'class' => 'myElement',
));
}
}
In application/view/helpers/FormImg.php
class Zend_View_Helper_FormImg extends Zend_View_Helper_FormElement
{
public function formImg ($name, $value, $attribs = null)
{
$info = $this->_getInfo($name, $value, $attribs);
$xHtml = '<img'
. $this->_htmlAttribs ($attribs)
. ' />';
return $xHtml;
}
}
In your form:
$this->addElement ('img', 'myimage', array (
'src' => '/images/download.png',
'align' => 'right',
));
Note: paths are subject to change in your particular application.
Actually, you don't need a custom element to do that. You can use HtmlTag decorator and use the openOnly option.
$form = new Zend_Form();
$form->addElement("text", "foo", array("decorators" => array(
array(array("img" => "HtmlTag"), array(
"tag" => "img",
"openOnly" => true,
"src" => "myPath",
"align" => "middle",
"class" => "myClass"
)),
array("ViewHelper"),
array(array("span" => "HtmlTag"), array(
"tag" => "span",
"class" => "myElement"
))
)));
echo $form->foo;
Hi you can create a custom element called "html"
class Zend_Form_Element_Html extends Zend_Form_Element_Xhtml
{
public $helper = 'formHtml';
}
Now you can call it:
$yourForm->addElement(
'html',
'myElementId',
array(
'value'=>'<span class="myElement"><img src="myPath" align="middle" class="myClass"/>
<input type="text"></span>'))
For more info you can check this link:
Zend Framework: Insert DIV and Image in my form

Categories