I've seen other threads and bug reports to do with the belongsTo property of an Zend_Element but nothing that relates directly to what i'm experiencing..
Here is my (simplified) Zend_Form:
$form = new Zend_Form();
$form->addElement('text', 'fname', array('belongsTo' => 'user'));
$form->addElement('text', 'sname', array('belongsTo' => 'user'));
Which is fine and the elements render like so:
<input type="text" name="user[fname]" />
<input type="text" name="user[sname]" />
...which is exactly what i want.
However, when the form is submitted, the element values are only accessible if you call
$form->getValue('fname') or $form->getValue('sname')
NOT, if you call...
$form->getValue('user');
What i'm expecting to see when you call $form->getValues('user') is an array of the values.
The array of values is clearly visible if you call
$form->getValues();
If this is the expected behaviour, then whats the point of putting them in an array? Because there would be no distinction between "user[fname]" and "client[fname]" - in fact adding another element with name "fname", even though it belongs to another item, would overwrite the previous.
I've tried adding a sub form which does result in what i want, but that way all the sub-form elements get rendered together, what i really want is to lay the 'array' elements in random places, like this...
<input type="text" name="user[fname]" />
<input type="text" name="some-other-field" />
<input type="text" name="some-other-field2" />
<input type="text" name="user[sname]" />
<input type="text" name="another-field-too" />
$form->getValue('fname') or $form->getValue('sname')
works this way because getValue() is just looking for the name of the element, and the names of your elemnts are fname and sname.
Excerpt: Zend/Form.php
public function getValue($name)
{
if ($element = $this->getElement($name)) {
return $element->getValue();
}
the way to access your belongsTo data from what I've seen should be:
$data = $form->getValues();
$user=$data['user'];
this should do what you want. Based on this:
Excerpt: Zend/Form.php
public function getValues($suppressArrayNotation = false)
{
$values = array();
$eBelongTo = null;
if ($this->isArray()) {
$eBelongTo = $this->getElementsBelongTo();
}
foreach ($this->getElements() as $key => $element) {
if (!$element->getIgnore()) {
$merge = array();
if (($belongsTo = $element->getBelongsTo()) !== $eBelongTo) {
if ('' !== (string)$belongsTo) {
$key = $belongsTo . '[' . $key . ']';
}
}
$merge = $this->_attachToArray($element->getValue(), $key);
$values = $this->_array_replace_recursive($values, $merge);
}
}
//...Code continues
return $values;
Hope this helps.
Related
I have the following XPath query that a kind user on SO helped me with:
$xpath->query(".//*[not(self::textarea or self::select or self::input) and contains(., '{{{')]/text()") as $node)
Its purpose is to replace certain placeholders with a value, and correctly catches occurences such as the below that should not be replaced:
<textarea id="testtextarea" name="testtextarea">{{{variable:test}}}</textarea>
And replaces correctly occurrences like this:
<div>{{{variable:test}}}</div>
Now I want to exclude elements that are of type <div> that contain the class name note-editable in that query, e.g., <div class="note-editable mayhaveanotherclasstoo">, in addition to textareas, selects or inputs.
I have tried:
$xpath->query(".//*[not(self::textarea or self::select or self::input) and not(contains(#class, 'note-editable')) and contains(., '{{{')]/text()") as $node)
and:
$xpath->query(".//*[not(self::textarea or self::select or self::input or contains(#class, 'note-editable')) and contains(., '{{{')]/text()") as $node)
I have followed the advice on some questions similar to this: PHP xpath contains class and does not contain class, and I do not get PHP errors, but the note-editable <div> tags are still having their placeholders replaced.
Any idea what's wrong with my attempted queries?
EDIT
Minimum reproducible DOM sample:
<div class="note-editing-area">
<textarea class="note-codable"></textarea>
<div class="note-editable panel-body" contenteditable="true" style="height: 350px;">{{{variable:system_url}}</div>
</div>
Code that does the replacement:
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);
foreach ($xpath->query(".//*[not(self::textarea or self::select or self::input or self::div[contains(#class,'note-editable')]) and contains(., '{{{')]/text()") as $node) {
$node->nodeValue = preg_replace_callback('~{{{([^:]+):([^}]+)}}}~', function($m) use ($placeholders) {
return $placeholders[$m[1]][$m[2]] ?? '';
},
$node->nodeValue);
}
$html = $dom->saveHTML();
echo html_entity_decode($html);
Use this below xpath.
.//*[not(self::textarea or self::select or self::input or self::div[contains(#class,'note-editable')]) and contains(., '{{{')]
My business functionality is to format JSON code returned from database and then use AJAX to process the JSON content and need to use only ".getJSON" instead of ".ajax"
The point where i was struck up is: how to sent the parameters using .getJSON to another page (customer.php) as i need to search for the customer data from database and return result in JSON formate.[The "data" parameter which holds key&value pair that needs to be sent to the server.]
Code from ajaxcall.php(where .getJSON is used)
<head>
<script>
$(document).ready(function(){
function search(){
var x=$("#srh").val();
if(x!=""){
$.getJSON({
url:'/customer.php',
data:{value:"x"},
success:function (data)
{
content= data;
$("#result").html(content[0].cust_id);
}
});
}
}
$("#button").click(function(){
search();
});
});
</script>
</head>
<body>
<input type="text" id="srh" placeholder="Enter the Name of the Customer"/>
<input type="button" id="button" value="search" />
<div id="result"></div>
</body>
Here, i need to pass the X parameter to customer.php using getJSON.The way i am passing is not working!
Code from customer.php(where i need to get search term (X parameter as input) $var=$_POST["value"]
and fetch the data from database using X parameter in where condition and return data in JSON content)
<?php
$conn = new mysqli("localhost", "xyz", "12345", "cust");
$var=$_GET['value'];
if (mysqli_connect_errno())
{ echo 'connect not possible to database: ' . mysqli_connect_error($conn); }
else
{
$query="SELECT cust_fname,cust_lname,cust_id,cust_addresa,cust_phone
from customer where UPPER(cust_lname) like UPPER('%" . $x. "%') ";
$result = mysqli_query($conn, $query);
if (!$result) { die("Not Found ! " . mysqli_error($conn)); }
else
{
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$json = json_encode($rows);
}
mysqli_free_result($result);
mysqli_close($conn);
print $json;
}
} ?>
Appreciate your pointer on this! Thanks in Advance.
I think I have a simple bug somewhere but I can't see it!
In my view, I have the following javascript to create a form:
$.ajax({
url:"<?php echo site_url('mycontroller/methodX/'.$ip.'/'.$hardwaremodel);?>",
type:'POST',
dataType:'json',
success: function(returnDataFromController) {
var htmlstring;
var submitFormHTML;
htmlstring = "<br><br><B>To reassign the port to a new vlan, click on a VlanId below and then click on the OK button</B><br><table class='table table-bordered table-striped'>";
htmlstring = htmlstring + "<th>VlanId</th><th>Name</th>";
for(i = 0; i < returnDataFromController.length; i++) {
}
submitFormHTML = "<form method='post' accept-charset='utf-8' action='/myapp/index.php/controllerABC/methodABC/"+ $('#ip').val() +"/" + $('#hardwaremodel').val() +"/" + $('#port').val() + "'><input type='text' id='newVlanID' style='width:5em;height:1.5em'/> <button type='submit' class='btn' id='saveVlan' style='width:10em;height:2em'>Reassign Vlan</button></form>";
//alert(submitFormHTML);
$('#clientajaxcontainer').html(htmlstring);
$('#newvlanform').html(submitFormHTML);
It's the "submitFormHTML" string that builds the form.
And in my controller I have the following logic to check for the input:
public function methodABC()
{
if($_POST){
echo 'I am here';
$form = $this->input->post();
var_dump($form);
exit();
}
else {
echo "false";
}
It always print the "false". I've also tried using:
print_r($this->input->post());
and
echo $this->input->post('newID');
But I can't seem to get the data from my view into the controller.
Can you see where I'm going wrong? Thanks for the help.
Edit:
The page when rendered, creates the following HTML for the form:
<form method="post" action="/myapp/index.php/switches/changeportvlan/11.11.11.11 /">
<input type='text' id='newVlanID' style='width:5em;height:1.5em'/>
<button type="submit" class='btn' id='saveVlan' style='width:10em;height:2em'>Reassign Vlan</button>
</form>"
The problem was that the textbox is missing a "name" attribute. "id" is not enough!
You need
if ($this->input->post(Null, False)) {
echo "I am here";
$form = $this->input->post(Null, True); ## True for XSS-cleaning, which you probably want.
exit();
}
else {
echo "False";
}
You have to give $this->input->post() arguments. Moreover, never use $_POST in CodeIgniter.
Good luck
I have the following default decorators in a Zend_Config_Ini to set up my form:
elementDecorators.viewHelper.decorator = "ViewHelper"
elementDecorators.label.decorator = "Label"
elementDecorators.errors.decorator = "Errors"
elementDecorators.htmlTag.decorator = "HtmlTag"
elementDecorators.htmlTag.options.tag = "li"
I have the following element definition also in the Zend_Config_Ini:
elements.username.type = "text"
elements.username.options.label = "Username:"
elements.username.options.required = true
and the following output is produced:
<li>
<label for="username" class="required">Username:</label>
<input type="text" name="username" id="username" value="" />
</li>
Now what I need to know is, how do I (through the ini config file preferably), set the id or class of the LI tag? I would like the following output:
<li id="form-username-element"> ... </li>
or
<li class="form-2col"> ... </li>
Update:
I was able to get it by overriding all the decorators in the element config itself like this:
elements.username.options.decorators.viewHelper.decorator = "ViewHelper"
elements.username.options.decorators.label.decorator = "Label"
elements.username.options.decorators.errors.decorator = "Errors"
elements.username.options.decorators.htmlTag.decorator = "HtmlTag"
elements.username.options.decorators.htmlTag.options.tag = "li"
elements.username.options.decorators.htmlTag.options.class = "username-row-element"
So that will work, however creates a lot of duplication as that would have to go onto every element (with the single change of the last line which would be the class setting itself). So what I am NOW wondering, is, from the ini file, is there a way to just override the class name using the default decorators (rather than having to duplicate all of the decorators for each element)?
Easiest thing to do is create your own Decorator. For instance, I've created an ElementWrap decorator, which wraps each element with a div and adds the necessary class and id. It could look something like this:
class Form_Decorator_ElementWrap extends Zend_Form_Decorator_Abstract
{
public function render($content)
{
$element = $this->getElement();
if($this->getOption('openOnly')) {
return '<div class="'.$this->getClass().'" id="'.$this->getId().'">' . $content;
} else if($this->getOption('closeOnly')) {
return $content . PHP_EOL . '</div>' . PHP_EOL;
} else {
return '<div class="'.$this->getClass().'" id="'.$this->getId().'">' . $content . '</div>';
}
}
public function getClass()
{
$element = $this->getElement();
$classes = array(
'field_wrap',
'field_' . strtolower(substr(strrchr($element->getType(), '_'), 1)),
$this->getOption('class'),
);
if($element->hasErrors()) {
$classes[] = 'field_error';
}
if($elementClass = $element->getAttrib('class')) {
$classes[] = $elementClass;
}
return implode(' ', array_filter($classes));
}
public function getId()
{
return 'fieldwrap-' . $element->getId();
}
}
So I am using a Zend_Form_Element_MultiCheckbox to display a long list of checkboxes. If I simply echo the element, I get lots of checkboxes separated by <br /> tags. I would like to figure out a way to utilize the simplicity of the Zend_Form_Element_MultiCheckbox but also display as multiple columns (i.e. 10 checkboxes in a <div style="float:left">). I can do it manually if I had an array of single checkbox elements, but it isn't the cleanest solution:
<?php
if (count($checkboxes) > 5) {
$columns = array_chunk($checkboxes, count($checkboxes) / 2); //two columns
} else {
$columns = array($checkboxes);
}
?>
<div id="checkboxes">
<?php foreach ($columns as $columnOfCheckboxes): ?>
<div style="float:left;">
<?php foreach($columnOfCheckboxes as $checkbox): ?>
<?php echo $checkbox ?> <?php echo $checkbox->getLabel() ?><br />
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</div>
How can I do this same sort of thing and still use the Zend_Form_Element_MultiCheckbox?
The best place to do this is using a view helper. Here is something I thought of really quickly that you could do. You can use this in your view scripts are attach it to a Zend_Form_Element.
I am going to assume you know how to use custom view helpers and how to add them to form elements.
class My_View_Helper_FormMultiCheckbox extends Zend_View_Helper_FormMultiCheckbox
{
public function formMultiCheckbox($name, $value = null, $attribs = null,
$options = null, $listsep = "<br />\n")
{
// zend_form_element attrib has higher precedence
if (isset($attribs['listsep'])) {
$listsep = $attribs['listsep'];
}
// Store original separator for later if changed
$origSep = $listsep;
// Don't allow whitespace as a seperator
$listsep = trim($listsep);
// Force a separator if empty
if (empty($listsep)) {
$listsep = $attribs['listsep'] = "<br />\n";
}
$string = $this->formRadio($name, $value, $attribs, $options, $listsep);
$checkboxes = explode($listsep, $string);
$html = '';
// Your code
if (count($checkboxes) > 5) {
$columns = array_chunk($checkboxes, count($checkboxes) / 2); //two columns
} else {
$columns = array($checkboxes);
}
foreach ($columns as $columnOfCheckboxes) {
$html .= '<div style="float:left;">';
$html .= implode($origSep, $columnOfCheckboxes);
$html .= '</div>';
}
return $html;
}
}
If you need further explanation just let me know. I did this fairly quickly.
EDIT
The reason I named it the same and placed in a different directory was only to override Zend's view helper. By naming it the same and adding my helper path:
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
My custom view helper gets precedence over Zend's helper. Doing this allowed me to test without changing any of my forms,elements, or views that used Zend's helper. Basically, that's how you replace one of Zend's view helpers with one of your own.
Only reason I mentioned the note on adding custom view helpers and adding to form elements was because I assumed you might rename the helper to better suit your needs.