How to store field Id in a row? - php

I write a web site with jquery and lot of ajax request to get data for table and ask data modifications with PHP/MySql on server side.
Currently, I use id attribute to store the id of the field of the table (which is an autoincrement int value).
And it works fine.
BUT I have recently learned that id should be unique (and start with a letter...).
AND I have different tables that could have the same id value (for different sql table)
Then I am not html (nor xhtml) compliant...
How could I correct my code ?
By using .data() function of jQuery ?
An hidden html element with the id as value (<span class="id">3</span>) ?
Other solution ?
Additional informations:
I have wrote a widget to manage my tables.
To add a new row, I do:
row = $('<div class="row" id="'+item.id+'"/>');
[...] // I add fields to my row
row.appendTo(tableData);// tableData is the html element where rows are
When a field element is changed, I trigger an event to the table that will ask the modification to the server with the right id:
$(e.target).closest(".row").attr("id")

If you are able to use jQuery 1.4.3 or greater look at using the html 5 data-* attributes. jQuery 1.4.3 will automatically use those data- attributes and place them in the .data() collection on the element.
Example:
<table>
<tr data-rowId="1">
</tr>
</table>
$("tr:first").data("rowId") would print 1
This method would also allow you to store json objects as well.
<table>
<tr data-row='{"Id" : 1, "Name": "Smith"}'>
</tr>
</table>
And than in your data()
var row = $("tr:first").data("row")
You can reference row.Id and row.Name

You can prefix your id with the table name :
<div id="mytable_1234"></div>
It's easy to extract the table name and the id from the field and this is HTML compliant.
var values = $(element).attr('id').split('_');
// values[0] is the table name and values[1] is the id.
You can use any other separator if you're already using underscores in your table names.

you can also use jQuery metadata .....
Its awesome to store data in html

Instead of using id use data-id and use the .data('id') (on that element) to retrieve it with jQuery.

I think... I understand your question - multiple data tables, all with autoincrement ids?
My solution would be pre-appending the ID with a letter (like you said) to differentiate it.
Example would be a dataset for 'cars' I would do:
<table>
<tr id="cars_1">
...
</tr>
<tr id="cars_2">
...
</tr>
<tr id="cars_3">
...
</tr>
</table>
Later if you have another table, bikes, you would do:
<table>
<tr id="bike_1">
...
</tr>
<tr id="bike_2">
...
</tr>
<tr id="bike_3">
...
</tr>
</table>
Your end result would be unique ID's while keeping the ID db value in mind, so you would do a simple check (if cars, then do this, etc), then to seperate the prefix (cars from the id 1, you would use something like the PHP expolode() fn).
Hope that clarifies it, and that I understood your question.

Related

how to remove(not delete) dynamically generated table elements?

Hi I have looped and echoed out this result
echo '<tr><td id="'.$row['productID'].'"><img height="150px" width="130px"
src="products/'.$row['image_url'].'"></td><td>'.$row['name'].'</td>
<td>'.$row['price'].'</td></tr>';
The above resulted in a table full of data, now How do i remove a specific row, I want to remove it not delete from the table, as in a shopping cart where you remove the item but not delete it from the table. How would you use javascript or any other in this case?
Thank you very much.
Make a extra field in table.
Default value for the active Row is 1....
deactive row is value is 0
When retrieve the data form table used the where function for the Active rows
Please you don't need JQuery for something simple like this..
document.getElementById('id_off_product').style.display = 'none';
You don't need jQuery to do this, although you can use it if you want.
If you want to hide the product:
document.getElementById('product_id').style.display = 'none';
With jQuery:
$('#product_id').hide();
If you want to show it again:
document.getElementById('product_id').style.display = '';
With jQuery:
$('#product_id').show();
If you want to completely remove the product:
document.getElementById('product_id').remove();
With jQuery:
$('#product_id').remove();
Also, you should probably put the id on the actual table row (tr) instead of on the table cell (td).
skimberk1's answer is most comprehensive. Here is an example that would allow a button on the row that would remove the row (parent/tr).
<table id="test">
<tr>
<td>one</td><td>two</td><td id="test" onclick="removerow(this);">remove</td>
</tr>
</table>
function removerow(e) {
e.parentNode.remove();
}
http://jsfiddle.net/FqbHW/19/embedded/result/
If completely removing is not desirable, then hiding or otherwise indicating it's inactive is possible... I would in that case also point you to Taveer's answer. You would need to track which rows are active/inactive. If you need additional details on this please comment.
Give it a id and using jQuery do as
$('yourid').hide(); // to hide
$('yourid').show(); // to show
if u use jquery, u have to know the id of product to remove
$('td#productId').parent().hide();

Adding Nested form rows PHP/Javascript

Overview:
I am creating a dynamic web invoicing system,
Most of the page are textareas and I have used tables to nest as they will post data into seperate tables after the form is submitted. When the "Nested" Add a Row is selected, it should add a row inside with form field that has details on which row and which position so it can be gathered in a for loop when it is posted.
Image:
Problem:
Adding a row in the circled area does not add it in the last row, It add's it as it is in the image. Additionally it only works on the first item, the second add a row does not even register a click.
I am unsure how to get the variables to create the form name[][] in this particular index size and the parents index number (located in javascript line 2-3)
Relevent Code:
Javascript
$("#additemrow").click(function(){
var currentListItem = $(this).length;
var currentJobItem = $(this).parents('#items').index('#items');
currentListItem++;
$("#listitem:last").after(/*Blank Form Row*/);
bind();
})
PHP
<table id="items">
<tr class="item-row"><td>/*form elements*/</td></tr>
<tr class="list-row">
<td colspan=5>
<table class="itemlist">
<?php
$itemCount = 0;
foreach($jobListItem as $items) {
foreach($items as $item) {
if($problem['item_id'] == $item['item_id']) {
?>
<tr id="listitem">
<td class="list-item">
<div class="delete-wpr">
<textarea class="item" name="item[/*A PARENT ITEM NUMBER*/][<?php echo $itemCount;?>][item]"></textarea>
<a class="deleteitem" href="javascript:;" title="Remove row">X</a>
</div>
</td>
</tr>
<?php
}
$itemCount++;
}
}
?>
<tr>
<td colspan="5"><a id="additemrow" href="javascript:;" title="Add a row">Add a row</a></td>
</tr>
</table>
//NEXT ITEMLIST GOES HERE
</table>
EDIT: Foreach Loop is just used to get variables from a array.
Please let me know if you need more details or bits of code as im not sure if I have given enough information.
Regarding the problem where your row gets insertet at the top:
Like Bertrand Lefort already said: in JQuery you can append nodes to the end of another (parent) node by calling parent_node.append(child_node) (more information here)
You can also add elements before/after another element by calling another_element.before(element) / another_element.after(element) or (be aware of reversed syntax!) element.insertBefore(another_element) / element.insertAfter(another_element)
Regarding the problem where only the first "add a row" registers a click:
You're selecting by id. Id's are (or should be) unique, so when you call $("#additemrow").click(function(){ ... }) the onClick-function will only be attached to the first element that matches the given id (as far as I remember).
If you want to attach the same onClick-function to multiple elements use class instead. However, if you do so, you got to make sure you insert the new element relative to the clicked element (eg. by using .parent(), .siblings() or similar functions).
Regarding your problem #2, I don't really know what you're trying to do, but this is what I noticed:
currentListItem and currentJobItem seem to be unused in their scope, since you are declaring them as local variables but not using them
.parents('#items').index('#items') is redundant because .parents('#items') already selects only the parent elements that match '#items'. If you want to get the index of the matched element, use index() (without parameters, see jquery API for more)
Some other notes:
If you have the time (and the need of a clean project) I recommend using template engines like Smarty to separate your logic from the output. This improves the readability of your code and also makes it easier to find/eliminate bugs.
I hope this helped a little bit. If you provide more information on what you're trying to do and what doesn't work as you expext, I will try to provide further help and update my answer.
You could add an id to the parent html element, then in your click handler:
$("#additemrow").click(function(){
$("#parent").append(/*Blank Form Row*/);
})

Change row value onclick html table like phpMyAdmin

I'm basically trying to use a simple method of editing table stored inside a mySQL database, but don't want to go through a different editing page, so my theory is :
Show all data inside a HTML table as usual would as followed.
<table class="table table-bordered sortable">
<thead>
<tr>
<th>Marchant</th>
<th>URL</th>
<th>Status</th>
<th>Sold</th>
<th>Deals</th>
<th>Sites</th>
<th>Found</th>
<th>Seen</th>
</tr>
</thead>
<tbody>
<tr>
<td>value</td>
<td></td>
<td></td>
<td>Sold here</td>
<td>Deals here</td>
<td>Sites here</td>
<td>null</td>
<td>null</td>
</tr>
</tbody>
I want to be able to edit the data on the fly, simply by clicking on the value displayed and changing it.
The question is how would i go about by doing this, is it even possible ?
If you're using jQuery check out edit-in-place plugins (jEditable is a good one).
The idea behind this is to set up a click event listener on the table cell, in which you append an editable textarea/form with the contents of the TD.
On change or submit the data is sent trough an ajax request to the server, which updates the DB and eventually returns back sanitized data (you update the TD contents with it).
Yes, its possible.
It's mostly frontend.
Here is example of creating input after you click on a cell. (jQuery)
// once page is loaded
$(document).ready(function() {
// adding an event when the user clicks on <td>
$('td').click(function() {
// create input for editing
var editarea = document.createElement('input');
editarea.setAttribute('type', 'text');
// put current value in it
editarea.setAttribute('value', $(this).html());
// rewrite current value with edit area
$(this).html(editarea);
// set focus to newly created input
$(editarea).focus();
});
});
After this you can add event to newly created input. (for example when user hits Enter)
Then you do AJAX request and send new values to a .php script.
You also need to add id to a newly created element so you know exactly what cell is needed to be changed after data is sent via AJAX.
Also, don't forget to validate data before putting to MySQL.
So if everything went good or not you return value back, and according to the value you write JavaScript code to to remove element from a cell / put edited value or popup a message.
Hope this helps.

HTML help - find a way to add a hidden value into a td field

I have an HTML table where I'm building an edit function to change a field inside this table.
I'd like your help to find a way to store the ID of the data listed in this field.
As a matter of fact, I have an object that has the listed data, RoleName, inside a <td>, and I'd like to store its id too, doing something like:
foreach ($accountUsers as $accountUser){
<td value="$accountUser->roleID">$accountUser->getRoleName()</td>
The problem is that value is not a property of a td. My constraint is that I must continue with the table.
If I've understood your question correctly, you can use HTML5 data-* attributes to store arbitrary data on an element:
<td data-value="$accountUser->roleID">$accountUser->getRoleName()</td>
Update (see comments)
You can access this data via the jQuery data method:
var value = $(yourTd).data("value");
Alternatively, you can use the native getAttribute method:
var value = yourTd.getAttribute("data-value");

post multidimensional array with Zend Form

i created a zend form which is able to generate subform with the elements like: items[0][price], items[0][count]; items[1][price] etc.
in each row of a table i need to display certain data. so, in my view i created a html table and tried to iterate through the 'items' and insert certain form element in certain column of a table.
<table>
<?php foreach($this->form->getSubform('items') as $item) :?>
<tr>
<td>just some data like product name</td>
<td><?php echo $item->getElement('price');?></td>
<td><?php echo $item->getElement('count');?></td>
</tr>
<?php endforeach;?>
</table>
after that, each form element item do NOT have array name anymore, as i was expecting, but just like 'items' or 'count' in each row, so multidimensional array will not be returned.
if i generate the form in view (echo $this->form;), then form element names are ok, but how should i add some data in the table then..? preferably it should be done in view.
Instead of adding elements always with price and count, since you're generating the field dinamically, try to name them price1, count1, price2, count2, and so on. Then you can retrieve them in your table using their new name (with the count appended).
Prepend your form decorator stack with the PrepareElements decorator. This decorator will loop through your form and set the appropriate belongsTo names.

Categories