how to set a value for Zend_Form_Element_Submit (zendframework 1) - zend-framework

I have am having trouble setting the basic values of a zend form element submit button (Zendframework1). I basically want to set a unique id number in it and then retrieve this number once the button has been submitted.
Below is my code. you will nots that I tried to use the setValue() method but this did not work.
$new = new Zend_Form_Element_Submit('new');
$new
->setDecorators($this->_buttonDecorators)
->setValue($tieredPrice->sample_id)
->setLabel('New');
$this->addElement($new);
I would also appreciate any advice on what I use to receive the values. i.e what method I will call to retrieve the values?

The label is used as the value on submit buttons, and this is what is submitted. There isn't a way to have another value submitted as part of the button as well - you'd either need to change the submit name or value (= label).
What you probably want to do instead is add a hidden field to the form and give that your numeric value instead.

It's a little bit tricky but not impossible :
You need to implement your own view helper and use it with your element.
At first, you must add a custom view helper path :
How to add a view helper directory (zend framework)
Implement your helper :
class View_Helper_CustomSubmit extends Zend_View_Helper_FormSubmit
{
public function customSubmit($name, $value = null, $attribs = null)
{
if( array_key_exists( 'value', $attribs ) ) {
$value = $attribs['value'];
unset( $attribs['value'] );
}
$info = $this->_getInfo($name, $value, $attribs);
extract($info); // name, value, attribs, options, listsep, disable, id
// check if disabled
$disabled = '';
if ($disable) {
$disabled = ' disabled="disabled"';
}
if ($id) {
$id = ' id="' . $this->view->escape($id) . '"';
}
// XHTML or HTML end tag?
$endTag = ' />';
if (($this->view instanceof Zend_View_Abstract) && !$this->view->doctype()->isXhtml()) {
$endTag= '>';
}
// Render the button.
$xhtml = '<input type="submit"'
. ' name="' . $this->view->escape($name) . '"'
. $id
. ' value="' . $this->view->escape( $value ) . '"'
. $disabled
. $this->_htmlAttribs($attribs)
. $endTag;
return $xhtml;
}
}
So, you assign the helper to the element :
$submit = $form->createElement( 'submit', 'submitElementName' );
$submit->setAttrib( 'value', 'my value' );
$submit->helper = 'customSubmit';
$form->addELement( $submit );
This way, you can retrieve the value of the submitted form :
$form->getValue( 'submitElementName' );

Related

Gravity Forms Multi Page Losing POST value

I have a complex Gravity Form built, it has 10 pages. I am using fields to build a "string" that I then match to a CPT name to get meta data from to display a selection, based on user choices in the form.
One field I have is not holding its value in POST. I can see it when I select the value on the page, then when I click to next page the value is still there. However, after two pages the value ( and field ) disappear from POST.
This is the function I have put together that builds my product string.
add_filter( 'gform_pre_render_12', 'display_choice_result' );
function display_choice_result( $form ) {
$current_page = GFFormDisplay::get_current_page( $form['id'] );
$html_content = "";
$prod_string = "";
if ( $current_page >= 10 ) {
foreach ( $form['fields'] as &$field ) {
// Check for a class of "product-builder-item" on the field
// I use this as another way to denote what fields to add to string
if ( strpos( $field->cssClass, 'product-builder-item' ) === false ) {
continue;
}
//gather form data to save into html field (Field ID 14 on Form ID 12)
//exclude page break and any hidden fields
if ( $field->id != 14 && $field->type != 'page' ) {
$is_hidden = RGFormsModel::is_field_hidden( $form, $field, array() );
$populated = rgpost( 'input_' . $field->id );
// Make sure the field we are getting the value from is not hidden and has a value
if ( !$is_hidden && $populated !='' ) {
$html_content .= '<li>' . $field->label . ': ' . rgpost( 'input_' . $field->id ) . '</li>';
$prod_string .= rgpost( 'input_' . $field->id );
}
}
}
// Do a bunch of stuff here with the $prod_string variable
// ...
// ...
// ...
}
return $form;
}
Screenshots showing the POST disappearing..The POST field in question is input_22 with a value of 18000
This is one page after I choose from the field
This is two pages after,
Anyone run into this before or have any idea why it would be disappearing?
Thank you.
I was having the same exact issue as you described. I realized that a jQuery function was interfering with Gravity Form process. The jQuery function was set to change a zip code field from type text to tel so the number pad would open up on mobile devices. This is what was causing my issue.

Showing course image on custom page in Moodle

I have created a custom page on which all available courses are displayed. I have also uploaded the image for the course and now want to show the name of the course along with the image. I am able to get the names of courses from the database but how to get the image.
Try something like this
// Create a course_in_list object to use the get_course_overviewfiles() method.
require_once($CFG->libdir . '/coursecatlib.php');
$course = new course_in_list($courseid);
$outputimage = '';
foreach ($course->get_course_overviewfiles() as $file) {
if ($file->is_valid_image()) {
$imagepath = '/' . $file->get_contextid() .
'/' . $file->get_component() .
'/' . $file->get_filearea() .
$file->get_filepath() .
$file->get_filename();
$imageurl = file_encode_url($CFG->wwwroot . '/pluginfile.php', $imagepath,
false);
$outputimage = html_writer::tag('div',
html_writer::empty_tag('img', array('src' => $imageurl)),
array('class' => 'courseimage'));
// Use the first image found.
break;
}
}
echo $outputimage;
You may get course image directly from 'overviewfiles' files area.
function get_course_image()
{
global $COURSE;
$url = '';
require_once( $CFG->libdir . '/filelib.php' );
$context = context_course::instance( $COURSE->id );
$fs = get_file_storage();
$files = $fs->get_area_files( $context->id, 'course', 'overviewfiles', 0 );
foreach ( $files as $f )
{
if ( $f->is_valid_image() )
{
$url = moodle_url::make_pluginfile_url( $f->get_contextid(), $f->get_component(), $f->get_filearea(), null, $f->get_filepath(), $f->get_filename(), false );
}
}
return $url;
}

Auto complete/Suggest in Wordpress Form

I'm placing a search form of 6 fields on my home page which includes a text box field named course. I want to show course suggestions while user typing. One more is, I want to show/hide some fields according to the option of first field dropdown. Any help would be appreciated.
You can use jQuery Auto Suggest which is included with WordPress : wp_enqueue_script
With this you can write a form that does a Ajax lookup to the the Ajax URL handler. Which you can add_action onto. AJAX in Plugins
So you can ajax lookup and then on the action side you can just perform a get_posts to match titles, or a raw sql Query. And return what is needed. edit your functions.php.
add_action('wp_enqueue_scripts', 'se_wp_enqueue_scripts');
function se_wp_enqueue_scripts() {
wp_enqueue_script('suggest');
}
add_action('wp_head', 'se_wp_head');
function se_wp_head() {
?>
<script type="text/javascript">
var se_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).ready(function() {
jQuery('#se_search_element_id').suggest(se_ajax_url + '?action=se_lookup');
});
</script>
<?php
}
add_action('wp_ajax_se_lookup', 'se_lookup');
add_action('wp_ajax_nopriv_se_lookup', 'se_lookup');
function se_lookup() {
global $wpdb;
$search = like_escape($_REQUEST['q']);
$query = 'SELECT ID,post_title FROM ' . $wpdb->posts . '
WHERE post_title LIKE \'' . $search . '%\'
AND post_type = \'post_type_name\'
AND post_status = \'publish\'
ORDER BY post_title ASC';
foreach ($wpdb->get_results($query) as $row) {
$post_title = $row->post_title;
$id = $row->ID;
$meta = get_post_meta($id, 'YOUR_METANAME', TRUE);
echo $post_title . ' (' . $meta . ')' . "\n";
}
die();
}
Use ajax for both. You may have to write some mysql query to retrieve the required fields(post titles or whatever it is) from the table.

Zend Framework 2 form element error-class + custom ViewHelper to render form

This is my third question this week (and overall) - hope I don't get banned here :D
Anyway, searched around and couldn't find an exact explanation to solve my issue(s).
A. I've searched around and found a custom ViewHelper to render my forms. What it does is recursively get all fieldsets and when it gets to the element level, it goes like this:
public function renderElement($element) {
$html = '
<div class="row">' .
'<label class="col-md-12" for="' . $element->getAttribute('id') . '">' . $element->getLabel() . '</label>' .
$this->view->formElement($element) .
$this->view->FormElementErrors($element) .
'<div class="clearfix" style="height: 15px;"></div>';
return $html . PHP_EOL;
}
Form renders ok, except:
1) How can I add an error class to the form element? (like if I use formRow helper in my view, it automatically ads an 'input-error' class, while also keeping the initial class specified in my fieldset when creating the element - 'attributes' => array('class' => 'some-class')), so the element's class attribute becomes "some-class input-error" in case it's invalid.
2) How can I set a class for the 'ul' containing the error messages (the 'ul' rendered by $this->view->FormElementErrors($element))? Hope this is a one-liner and I don't have to go message-by-message and compose the html for the error messages list, but if not so be it (I don't know how to do that either).
B. Let's say that sometimes I don't use this custom ViewHelper to render my form. Zend's formRow view helper can be handy sometimes. This brings me to the following code in my view:
echo $this->formRow($this->form->get('user_fieldset')->get('user_name'));
I've noticed this automatically adds 'input-error' class on my element (in case it's invalid) which is perfect, BUT how can I also tell formRow to give a class to the 'ul' that's displaying the error messages?
I'd go even further and ask how I can turn this:
echo $this->formLabel($this->form->get('user_fieldset')->get('user_name'));
echo $this->formInput($this->form->get('user_fieldset')->get('user_name'));
echo $this->formElementErrors($this->form->get('user_fieldset')->get('user_name'), array('class' => 'form-validation-error'));
into something that ads an error-class to the element as well, not just to the error messages list, but if anyone answers to point A I think it's the same issue.
I've managed to do it like this:
public function renderElement($element) {
// FORM ROW
$html = '<div class="form-group">';
// LABEL
$html .= '<label class="form-label" for="' . $element->getAttribute('id') . '">' . $element->getLabel() . '</label>';
// ELEMENT
/*
- Check if element has error messages
- If it does, add my error-class to the element's existing one(s),
to style the element differently on error
*/
if (count($element->getMessages()) > 0) {
$classAttribute = ($element->hasAttribute('class') ? $element->getAttribute('class') . ' ' : '');
$classAttribute .= 'input-error';
/*
* Normally, here I would have added a space in my string (' input-error')
* Logically, I would figure that if the element already has a class "cls"
* and I would do $element->getAttribute('class') . 'another-class'
* then the class attribute would become "clsanother-class"
* BUT it seems that, even if I don't intentionally add a space in my string,
* I still get "cls another-class" as the resulted concatenated string
* I assume that when building the form, ZF2 automatically
* adds spaces after attributes values? so you/it won't have to
* consider that later, when you'd eventually need to add another
* value to an attribute?
*/
$element->setAttribute('class', $classAttribute);
}
$html .= $this->view->formElement($element);
/*
* Of course, you could decide/need to do things differently,
* depending on the element's type
switch ($element->getAttribute('type')) {
case 'text':
case 'email': {
break;
}
default: {
}
}
*/
// ERROR MESSAGES
// Custom class (.form-validation-error) for the default html wrapper - <ul>
$html .= $this->view->FormElementErrors($element, array('class' => 'form-validation-error'));
$html .= '</div>'; # /.form-group
$html .= '<div class="clearfix" style="height: 15px;"></div>';
return $html . PHP_EOL;
}
I'm not to fond of this, but I suppose there is no shorter way. I thought ZF2 shoud have something like:
if ($element->hasErrors()) { $element->addClass('some-class'); }
right out of the box. That's the answer I would have expected, that it would simply be a method I missed/couldn't find. But it turns out that ZF2 doesn't have quite anything in the whole world that you might need right out of the box, you end up having to write the (more or less) occasional helpers.
Anyway, if someone ever needs it here's the entire RenderForm view helper:
namespace User\View\Helper;
use Zend\View\Helper\AbstractHelper;
class RenderForm extends AbstractHelper {
public function __invoke($form) {
$form->prepare();
$html = $this->view->form()->openTag($form) . PHP_EOL;
$html .= $this->renderFieldsets($form->getFieldsets());
$html .= $this->renderElements($form->getElements());
$html .= $this->view->form()->closeTag($form) . PHP_EOL;
return $html;
}
public function renderFieldsets($fieldsets) {
foreach ($fieldsets as $fieldset) {
if (count($fieldset->getFieldsets()) > 0) {
$html = $this->renderFieldsets($fieldset->getFieldsets());
} else {
$html = '<fieldset>';
// You can use fieldset's name for the legend (if that's not inappropriate)
$html .= '<legend>' . ucfirst($fieldset->getName()) . '</legend>';
// or it's label (if you had set one)
// $html .= '<legend>' . ucfirst($fieldset->getLabel()) . '</legend>';
$html .= $this->renderElements($fieldset->getElements());
$html .= '</fieldset>';
// I actually never use the <fieldset> html tag.
// Feel free to use anything you like, if you do have to
// make grouping certain elements stand out to the user
}
}
return $html;
}
public function renderElements($elements) {
$html = '';
foreach ($elements as $element) {
$html .= $this->renderElement($element);
}
return $html;
}
public function renderElement($element) {
// FORM ROW
$html = '<div class="form-group">';
// LABEL
$html .= '<label class="form-label" for="' . $element->getAttribute('id') . '">' . $element->getLabel() . '</label>'; # add translation here
// ELEMENT
/*
- Check if element has error messages
- If it does, add my error-class to the element's existing one(s),
to style the element differently on error
*/
if (count($element->getMessages()) > 0) {
$classAttribute = ($element->hasAttribute('class') ? $element->getAttribute('class') . ' ' : '');
$classAttribute .= 'input-error';
$element->setAttribute('class', $classAttribute);
}
$html .= $this->view->formElement($element);
// ERROR MESSAGES
$html .= $this->view->FormElementErrors($element, array('class' => 'form-validation-error'));
$html .= '</div>'; # /.row
$html .= '<div class="clearfix" style="height: 15px;"></div>';
return $html . PHP_EOL;
}
}
User is my module. I've created a 'viewhelper.config.php' in it's config folder:
return array(
'invokables' => array(
'renderForm' => 'User\View\Helper\RenderForm',
),
);
and in Module.php:
public function getViewHelperConfig() {
return include __DIR__ . '/config/viewhelper.config.php';
}
Then, in your view simply call:
$this->renderForm($form);
Of course, if you don't have many view helpers, you could not create a separate config file just for that, leave Module.php alone and simply add:
'view_helpers' => array(
'invokables' => array(
'renderForm' => 'User\View\Helper\RenderForm',
),
),
to any configuration file.
I use getMessages() method to check if an element has an validation message. for eg.
<div class="form-group <?=($this->form->get('user_fieldset')->get('user_name')->getMessages())?'has-error':'';?>">
...
</div>
This question seems to be very old and you must have solved it by yourself. :)

Access Form values in my Symfony executeAction backend

So one of my pages consists of a quiz form that has several questions of type multiple choice, the choices are specified as radio buttons. I have been scanning the Symfony documentation to find out how to access form field values inputted by the user. Thing is, this isn;t a doctrine or propel based form, and neither do I require the values to be stored in the database, hence executing a $form->save() makes little sense to me. But I do require access to specific values of my form in my backend once the user hits submit.
Most of Symfony documentation that i have run into doesn't necessarily explain how this can be done. I would assume it would be something to the effect of :
$request->getParameter( 'radio_choices_id selected value ').
Thanks to all who read this and Cheers to the ones who respond to it :)
Parijat
Hm, it is very simple if I understand your question right)
For widget:
$this->widgetSchema['name'] = new sfWidgetFormChoice(array('choices' => array('ch_1', 'ch_2')));
Ok,in action:
$this->form = new FaqContactForm();
if ($request->isMethod('post')) {
$this->form->bind($request->getParameter($this->form->getName()));
if ($this->form->isValid()) {
$your_val=$this->form->getValue('name');
//or
$your_val=$this->form['name']->getValue());
}
}
In backend in protected function processForm(sfWebRequest $request, sfForm $form)
you have
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid())
{
$notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';
try {
$product = $form->save();
} catch (Doctrine_Validator_Exception $e) {
$errorStack = $form->getObject()->getErrorStack();
$message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " with validation errors: ";
foreach ($errorStack as $field => $errors) {
$message .= "$field (" . implode(", ", $errors) . "), ";
}
$message = trim($message, ', ');
$this->getUser()->setFlash('error', $message);
return sfView::SUCCESS;
}
Before $product = $form->save(); try
$your_val=$form->getValue('name');
//or
$your_val=$form['name']->getValue());