When I remove name the selected dropdown item does get save into the database. When I add in the name field it doesn't get saved. The name goes to js where an input field will show up, and the input field gets saved. Why is it not saving the selected dropdown item then?
<td><p><?php echo $form->dropDownList($model,'product_type', CHtml::listData(ProductType::model()->findAll(),'product_type','description'),
array(
'class'=>'span12',
'name'=>'prodType',
'empty'=>"-- Select Type of Product --")); ?></td>
<td><?php echo $form->error($model,'product_type'); ?></td>
<script type="text/javascript">
$(document).ready(function(){
$('p select[name="prodType"]').change(function(e){
if ($('p select[name="prodType"]').val() == "Pre"){
$('#pre-input').show();
}else{
$('#pre-input').hide();
}
});
</script>
Your controller is probably something like this..
class MyController extends CController {
.....
public function actionSaveMyForm(){
....
if(isset($_POST['MyModel']){
$model->attributes = $_POST['MyModel'];
$model->save();
}
....
}
}
This is basically means if the array of MyModel is set in your $_POST, then assign all sub array elements to model attributes and then save them.
When you do not the set the name attribute in the dropDownList function call the auto-generated id attribute would be MyModel_<<attribute>> i.e. MyModel_product_type and the name attribute would be MyModel[product_type] Therefore when you send the form information, it will be available under $_POST['MyModel'] array. i.e. product type can be retrieved from $_POST['MyModel']['product_type']
therefore
if(isset($_POST['MyModel']){
$model->attributes = $_POST['MyModel'];
$model->save();
}
would assign product_type value $model->product_type and save it.
However when you assign the name manually, the value is gettable only at $_POST['myCustomName]` so you will have to save it specifically like this
if(isset($_POST['MyModel']) && isset($_POST['myCustomName')){
$model->attributes = $_POST['MyModel'];
$model->product_type = $_POST['myCustomName'];
$model->save();
}
then the model will get saved correctly.
Note: In addition to this you will have to change your JavaScript or form submit code to send the data correctly including your custom name field, along with the POST request
Related
I have an input tag that takes a users input that calls an AJAX dynamically outputs suggestions from my database. The issue is I want to store the primary key associated with that attribute.
I have figured out a way set it to the primary key when the user selects a value; however I would rather only have the attribute displayed on the front end. Essentially what I was thinking about doing was using the option tag and setting the value to the primary key, but after reading the documentation for it, that doesnt look like it would work.
HTML:
<input type="text" id = "zip_id" class="tftextinput2" autocomplete = "off" name="zip" placeholder="Zip Code" onkeyup = "autocompleter()">
<ul id = "zip_codes_list_id"></ul>
JS:
function autocompleter()
{
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#zip_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#zip_codes_list_id').show();
$('#zip_codes_list_id').html(data);
}
});
} else {
$('#zip_codes_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item)
{
// change input value
$('#zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
PHP:
<?php
//connect to db here
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM zip_codes WHERE zip LIKE (:keyword) ORDER BY zip_codes_id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs)
{
// put in bold the written text
$zip = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['zip']);
// add new option
// echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['zip']).'\')">'.$zip.'</li>'; (this one only passes the attribute)
echo '<li " onclick="set_item(\''.str_replace("'", "\'", $rs['zip_codes_id']).'\')">'.$zip.'</li>';
//this one passes the attribute but changes the displayed value to the primary key.
}
?>
As you can see from the PHP file, what I am trying to do is pass in the primary key value but keep the displayed value the attribute. I am not sure how to do that. Should I be using the UL tag?
The issue in your code is that you try to the zip_id value for the input, but this input contains the zip field value - I assume it's the textual representation. There are a few ways how you could save the zip_id on the frontend - either store it in the model (if you're using some MVC framework, but I gues it's not the case) or simply add a hidden input field:
<input type="hidden" id="actual_zip_id" name="zip_id">
And
function set_item(item)
{
// change input value
$('#actual_zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
UPD
Speakng about the entire idea of autocompleting zip codes, it looks pretty nasty, as pointed by Darren Gourley (check the comments).
So you'd rather validate it with regex first, and then do your db-related logic like that:
$('#zip_id').on('change', function(){
// your stuff
})
Best regards, Alexander
I am echoing out a form (foreach) from my filemaker records which will result in the items ID, Name, a Checkbox and then an image.
In my understanding i will have to use classes or the elements will all have the same id.
My Code;
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo '"'.$id.'"<br>';
echo $name.'<br>';
echo '<input type="checkbox" class="check" value="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'">';
echo '<div class="pics">';
echo '<img style="width:200px;" src="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'"><br>';
echo '<hr>';
echo '</div>';
}
Which results in a page full of the records, a checkbox and the relating image.
I wish to only show these images when the checkbox is checked but cannot find a solution, i have tried many jquery scripts, to no avail.
The images will then populate the next page as a pdf to be printed.
I am hoping not to have to grab the checkbox's values as an array to then use the get method with 100's of if statements but cant see another way ?
The jquery ive used.
$(document).ready(function () {
$('.pics').hide();
$('.check').click(function () {
$('pics').show;
});
$('.pics').hide;
});
and
$(function() {
$(".check").click(function(e) {
e.preventDefault();
$('.pics').hide();
$('.pics').show();
});
});
Plus many similar alternatives.
Is there something obvious i am missing ?
Query to filemaker method;
I have changed the path field to a calculated value which works great, thank you, although with 1000's of records, i would need lots of php code to echo the checkbox's to the website and lots more to be able to edit them from the website.
I have done this previously with the value held within the checkbox in filemaker.
$sesame = $print->getField('Allergens::Allergens[11]'); if ($sesame == "Sesame") { $sesame = "checked" ;} else if ($sesame !== "Sesame") {$sesame = "" ;}
This displays the checkbox synced with filemaker.
if ($_POST['Sesame'] == 'Sesame'){ $a_sesame = 'Sesame';} else { $a_sesame = 'No Sesame'; }
This is sent as a variable to my script.
if($a_sesame == "Sesame"){$contains_sesame = "Yes";} else { $contains_sesame = "No";}
This grabs the new value from the form.
Which all work great, but then i am writing a script in filemaker too to enable the to and from of the different names for each checkbox state.
which is for this part 120 lines long, this is a sample which i have to repeat for each repetition of this field.
Set Variable [ $sesame; Value:GetValue ( Get ( ScriptParameter ) ; 11 ) ]
If [ $sesame = "Sesame" ]
Set Field [ Allergens::Allergens[11]; "Sesame" ] Commit Records/Requests
[ Skip data entry validation; No dialog ]
Else If [ $sesame = "No Sesame" ]
Clear [ Allergens::Allergens[11] ] [ Select ]
Commit Records/Requests
[ Skip data entry validation; No dialog ]
Refresh Window
[ Flush cached join results; Flush cached external data ]
End If
This would be far too large to write for so many records, just for these 14 fields used 120 in filemaker and 400 plus in the php.
I am not 100% sure what you are trying to do but this should work. First add an extra div that closes input and div pics like below.
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo <<<TEXT
'{$id}'<br>
{$name}<br>
<div>
<input type='checkbox' class='check' value='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'>
<div class='pics'>
<img style='width: 200px;' src='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'><br>
<hr>
</div>
</div>
TEXT;
}
then change your java to this
$(document).ready(function() {
$(".pics").hide();
$(".check").click(function() {
$(this).siblings().toggle();
});
});
well I hope this helps
Another alternative would be to set up a simple calculated container field in FileMaker, with a calculated value of:
If ( checkbox; imageField )
This would only pass the image when the checkbox was ticked for a record. This should be faster than handling this in JavaScript, since you'd be limiting the number of images being sent over the wire.
Note: For performance, you might try this with this calculated container field stored and unstored. I suspect stored v unstored should make little difference, in which case I'd suggest leaving this unstored to minimize disk space consumed.
You can use the toggle()function:
$(function() {
$('.pics').hide();
$(".check").is(':checked',function(e) {
e.preventDefault();
$('.pics').toggle();
});
});
I am working with PHP's Yii framework and having issues clearing or deleting the uploaded file from the textfield. Currently, it will delete the content from the fileField, but can't get it to delete the textfield. Any ideas?
UPDATE
I can now clear my textField because I've hard coded my clearFileInputField function by adding $('.getFile').val(""); I reference this in my HTML by adding the 'class' => 'getName' in the input section. While this clears the data, it doesn't remove the file after saving. Any suggestions?
HTML
<div id = "clearContent">
<?php echo $form->labelex($model,'info'); ?>
<?php echo $form->textfield($model,'info', array(placeholder => "No file chosen", readonly => true, 'class' => 'getName')); ?><br>
<?php echo $form->fileField($model,'info'); ?>
<?php echo $form->error($model,'info'); ?>
<input type="checkbox" onclick = "clearFileInputField('clearContent')" href="javascript:noAction();"> Remove File
</div>
JavaScript:
<script>
function clearFileInputField(tagId) {
document.getElementById(tagId).innerHTML = document.getElementById(tagId).innerHTML;
$('.getFile').val("");
}
</script>
I am not sure if I understood the problem you are having correctly. If I understood the question completely wrong, please elaborate and I will try to improve my answer.
If you want to remove the the content (the value attribute) of a text and file input you can use code like the following:
// listen to the click on the #clearnbtn element
document.getElementById('clearbtn').addEventListener('click', function() {
// Remove the value of the #foo and #bar elements
document.getElementById('foo').value = "";
document.getElementById('bar').value = "";
});
If you would like to remove an entire field you can do that like so:
// Retrieves the input element, gets its parents and removes itself from it
var fooElement = document.getElementById('foo');
fooElement.parentElement.removeChild(fooElement)
Or you can set the innerHTML attribute of the parent element to an empty string ('').
document.getElementById('clearContent').innerHTML = "";
https://jsfiddle.net/osjk7umh/1/
I have a table which had a select field in it which I'd like to save into database if it dosnt exist yet through POST data. If it does exist then I'd like to update the already existing row in the database.
This can be found in the tbody in which i have my tablerow with an ng-repeat to display all data from a json.
<td>
<select id="statusSelect{{anime.id}}" ng-model="statusId" ng-options="animeStatus.id as animeStatus.status for animeStatus in animeStatuses"
ng-change='addUserAnime( "<?php echo Yii::app()->user->id; ?>", anime.id, statusId )'>
</select>
</td>
Next this is my code for what im trying to do in the angular controller:
$scope.addUserAnime = function( userId, animeId, statusId, userAnime )
{
if ( userId == '' ) {
//alert user that he/she needs to log in first
} else {
//loop through my json where i saved from which user which anime is saved with which status
for (var i = 0; i < $scope.usersAnime.length; i++) {
//if there is an already existing entry then i want to update it if not then i want to introduce it into DB with POST
if ($scope.usersAnime[i].anime_id == animeId && $scope.usersAnime[i].user_id == userId) {
$scope.userAnime = $.extend({}, $scope.usersAnime[i]);
$scope.userAnime.status_id = statusId;
$scope.userAnime.date_modified = today;
saveUserAnime();
return;
}
}
$scope.userAnime = {
id: 0,
user_id: userId,
anime_id: animeId,
status_id: statusId,
rating: '',
date_modified: today
};
saveUserAnime();
}
};
Problem is that if i POST a new entry it gets saved in the database, but if i dont reload the page and i change the select again giving it a new option it gets POSTed again instead of using PUT for update.In the end i end up with two entries instead of one. I want to introduce it to database on first select and i want to update it if its changed after. Is that possible. I tryed doing it with $dirty using the table as form but thats a nono.
In the saveUserAnime() function its correctly deffined to use POST if its new entry and use PUT if its an existing one. I have another form for which it works. The problem must be in this current function.
Just put that code where you get the object with the animeStatus and put that in a function and call it directly after that. Now you can call that function when your POST is done, so the new data will be loaded.
Otherwise you could also check through SQL, if that value exists in your table, so you don't need your check in angularjs, that would be easier than this one.
I have a table name "drug". It has column name "ingredians".
"ingredians" field has text (varchar)
I can select the "ingredians" using dropdown box.
<td width="100px"><center>
<select name="drugitem" style="width:100px; height:30px;" >
<? $sc="SELECT * FROM drug";
$scq=mysql_query($sc);
while($scf=mysql_fetch_array($scq))
{
?><option value='<? echo $scf[id];?>'><? echo $scf[ingredians];?></option>
<? } ;?>
</select></center>
</td>
And then I want to pass this "ingredians" both ID and VALUE to another table called "temp".
'temp' table has two colomns to catch these data called "drugitemid" and "drugitemname"
How can I pass both values.
Though your question is bit vague. As per my understanding what you need is to concat name with id in value for ingredients & than on other page you can use them after exploding with -,
<option value='<? echo $scf[ingredians].'-'.$scf[id];?>'><? echo $scf[ingredians];?></option>
On next page:
list($drugname, $drugid) = explode('-', $_POST['drugitem']);
Note: It's irrelevant to save both foreign id & name in any table.
You can use jquery. On this dropdown change event get value from.
var val_id = $("#yordropdown_id").val();
var name = $("#yordropdown_id option[value="+val_id+"]").text();
Then send ajax request with those id and names and save it to your temp table.
I think it makes sense!