How do I use CakePHP to append data to database when submitting from a form? - forms

I've been developing this application for use in my biology lab where I require the following:
User adds in data into a text field.
When the user wants to update the text field, s/he cannot update the existing text, and can only append new text to the field.
Therefore, the form must contain a blank text field that the user can input text to append to the existing entry.
Ideally, I'd also like to append the timestamp for when each entry is recorded.
As you can see, it's sort of like a lab notebook, where the integrity of previously-entered data is important.
I'm having trouble with 2nd point, in that I don't know how to create a blank text field that saves the data to the corresponding field in the model.
Here is the code I currently have for the "view":
(I've tried to hide the existing data - "results_summary" - in a "hidden" element.)
<!-- File: /app/View/Experiments/update.ctp -->
<h1>Update Experiment</h1>
<h2>Objective:</h2>
<p><?php echo $experiment['Experiment']['objective']?></p>
<p>Notebook <?php echo $experiment['Experiment']['notebook_number'] ?>, Page <?php echo $experiment['Experiment']['notebook_page'] ?> </p>
<p>Date Started: <?php echo $experiment['Experiment']['date_started']?></p>
<p>Date Ended: <?php echo $experiment['Experiment']['date_ended']?></p>
<p>Project: <?php echo $experiment['Project']['title']?>
<p>Status: <?php echo $experiment['ExperimentStatus']['title']?>
<p>Results Summary:</p>
<p><?php echo $this->Form->create('Experiment', array('action' => 'update'));
echo $this->Form->hidden('results_summary');
echo $this->Form->text('results_summary');
echo $this->Form->end('Update');
//$experiment['Experiment']['results_summary']?></p>
Does anybody have clues as to how I could go about solving this problem? I'm quite lost right now, as I haven't had the experience coding this before.

Based on requirements 3 and 4, I would model the database in a way that each summary entry is stored in a separate row. You'll need a separate table for that, something like this:
id | experiment_id | summary_entry | summary_entry_timestamp
Column experiment_id is a foreign key to the related id on experiments table. Tables/models are related so that Experiment hasMany ExperimentSummaryEntry.
Then, logging to the experiment results summary will be a matter of inserting a new row on that table.

I would have to agree with #bfavaretto
Without seeing your database structure it is hard to be sure.
I suspect that you are doing
Project hasMany Experiment
Experiment hasOne ExperimentStatus
You need an additional
Experiment hasMany ExperimentEntry
the entries table need to have
id int(11), experiment_id int (11), content TEXT, created DATETIME
if you are okay using DATETIME field for timestamp then I suggest using **created because cakephp will auto fill in for you.
instead of update experiment, you do a add experimententry.
in the afterSave method of ExperimentEntry you do a
$this->Experiment->id = $this->data['ExperimentEntry']['experiment_id'];
$latestSummary = $this->Experiment->field('result_summary');
$latestSummary .= $this->data['ExperimentEntry']['content']; // you may need to add a newline before you append. up to you
$this->Experiment->save(array(
'Experiment' => array(
'result_summary' => $latestSummary
)));
Code is not tested so use at own risk.
** no corresponding page in cakephp 2.0 docs for created and modified but definitely this works. I have tried it before.

Related

Adding Fields/ Columns to oc_product_description Table, Opencart 2.3.0.2

Background: Added some new columns in oc_product_description (I added some key product features and alternative name for ebay listing, so I can generate the product data into a template to use on ebay listings, whilst keeping and using the code on the opencart website..)
Problem: that when I save the product in opencart it deletes the data I just entered into the table, because it uses a Delete and then Insert function (by the looks of it?) in admin/model/catalog/product.php approx line 140. Which uses the $data['product_descriptions'] array which comes about in admin/controller/catalog/product.php approx line 765.. but here there are 3 possibilities.. either from the post or from a get function, or a new array..
I added hidden fields to the admin/view/catalog/product_form.php but what's going on here doesn't make it through to the table in the end..
I also added the new fields to the getProductDescriptions() function and directly to the $data array just as the other fields were already..
Please don't send me off to look up MVC models..Please help!!!
The problem was: that I had used the wrong name and value in the hidden fields..I obviously wasn't giving it much thought when I merely wrote:
<input type="hidden" name="name_ebay" value="<?php echo $entry_name_ebay; ?>">
In actual fact what was required was:
<input type="hidden" name="product_description[<?php echo $language['language_id']; ?>][name_ebay]" value="<?php echo isset($product_description[$language['language_id']]) ? $product_description[$language['language_id']]['name_ebay'] : ''; ?>">
I hope this post has offered some reminders or hints concerning Adding Your Own Fields to Opencart's Product Description Table, and using them in the admin
Take note mostly of:
i) use of language id in the view
ii) the delete, insert (instead of update) in model
iii) the change from post to $data array in controller
Furthermore, I did notice that the delete line,
$this->db->query("DELETE FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'");
Seems to delete the record with this product id?? but without regard to language id?.. I'll have to look into whether this deletes the translated versions on a multi-lingual site of the products in the product_description table..?

how to create a form elements with value in moodle

I am trying to create a form element text with value in moodle.
I trying the below :
$mform->addElement('text','test', get_string('test'));
This is used to create a text box . i want to add value also like
<input type='text' value='<?php .... ?>' />
How to do that in moodle
When you instantiate the form, you can pass the relevant data into it, e.g.
$form = new my_form();
$formdata = (object)array('test' => 'The value to display in the textbox');
$form->set_data($formdata);
(Usually the data passed into the form is some existing data retrieved from the database).
I'm not sure what kind of data did you mean here.
If you want to set user data (for example, you are developing a form that edits existing record), then use $form->set_data() after creating a form instance as Davo suggested.
If you want to pre-fill the form with default value, then use this inside the form definition:
$mform->addElement('text','test', get_string('test'));
$mform->setDefault('test', 'your default value');
You can use both methods, in which case the data from set_data() will have priority.

Cakephp Controller isn´t processing form data

Hi I´m new with cakephp (v.1.3). I´m trying to do something simple.
I have two tables: fichas[id,... etc] and labos[id,laboratorio,ficha_id] so "labos" belongs to "fichas". (labos.laboratorio is ENUM field).
I would like to view a "ficha" given labos.id and labos.laboratorio so I´ve included the following code in "home.ctp"
<h3>Mostrar Ficha</h3>
<?php echo $this->Form->create('ficha',array('action'=>'localiza'));?>
<?php echo $this->Form->radio('laboratorio',array('A','B','C'),array('A','B','C')); ?>
<?php echo $this->Form->input('id',array('label'=>'Numero','type'=>'text')); ?>
<?php echo $this->Form->end("Mostrar");?>
Then in "fichas_controller.php" added the following:
function localiza(){
$laboratorio=$this->data['Ficha']['laboratorio'];
$id=$this->data['Ficha']['id'];
if(!$id){
$this->Session->setFlash('Por favor introduzca un valor valido');
$this->redirect(array('action'=>'index'));
}
$this->set('fichas',$this->Ficha->findID($id,$laboratorio));
}
Finally in the model "ficha.php" the following:
function findID($id=null,$laboratorio=null){
return $this->find('all',array('conditions'=>array('Labo.laboratorio'=>$laboratorio,'Labo.id'=>$id)));
}
Obviously the file views/fichas/localiza.ctp exists
The thing is when I press the submit button in the form it just reloads the home.ctp page. Looks like the controller´s code is not being executed because i´ve tried to force the error message that should load the index action changing the if condition to true but the same result. I´ve changed the name of the function in the model expecting an error to ocurr but I get the same result.
I have another two forms in the home.ctp page but calling another actions and models.
One of them its almost identical and it works fine.
I can´t figure out the error.
Thanks in advance for any help.
Marcelo.
The array key $this->data['Ficha'] likely doesn't exist. You've created the lowercase "ficha" form, this name should be capitalized, otherwise the data is available in $this->data['ficha']. So the form creation call would look like this:
<?php echo $this->Form->create('Ficha',array('action'=>'localiza'));?>
You can debug in two ways on Cake
Configure::write('debug', 2);
debug($this->data);
OR
The other PHP ways
print_r($this->data);
This way, you will know if you are passing the data->params properly.
Why is your model has first charcter in lower-case? It should be
Fichas
Labos
Then you can issue a direct find on the controller, if you only want.
$d = $this->Fichas->find('all', array();
You might have added the home.ctp file into another controller. Try adding the controller in the following line:
<?php echo $this->Form->create('ficha',array('controller' => 'fichas', 'action'=>'localiza'));?>
Hope it helps.

Expression Engine - For entrys listing, only show last category in tree?

I have a category structure like this:
cat1
cat2
-catA
-catB
cat3
For a list of entries Im showing the category names for each one with this:
{categories show_group=“1”}{category_name}{/categories}
How can I limit the category names to only show the last in the tree when there is more than one? EG if an entry is part of ‘cat2’ and also ‘catA’, I only want ‘catA’ to display.
Thanks
Update - Ive tried the following but total_results returns the number of entries, not the number of categories for each entry.
{exp:channel:entries channel="news|blog" category="<?php echo $cat_id ?>" orderby="date" sort="desc" disable="member_data|pagination" dynamic="no"}
{categories show_group="1"}{if count == total_results}{category_name}{/if}{/categories}
{/exp:channel:entries}
The efficient way would be to write a SQL query to get exactly the value you want. The inefficient but easy way would be to hide all results except the last one.
{!-- requires PHP parsed on output --}
<?php $lastCat = ""; ?>
{categories}
<?php $lastCat = "{category_name}"; ?>
{/categories}
<?php echo $lastCat; ?>
It turns out {count} and {total_results} aren't supported within the {categories} tag pair. You can use PHP to substitute.
Whether inefficient is good enough depends on how many categories you have and how effective caching the page will be.

Symfony dynamic model form template

I am developing symfony based web application. I have many Models (Laptop, Netbook, Ipad,Tablet.... all these models inherited from Product model).Based on these models I also have Forms (LaptopForm, NetbookForm...so on).
In my action class I get Model name and assign it to template :
$modelForm = $this->modelName.'Form';
$this->form = new $modelForm();
Then in my template I do that <?php echo $form ?> ..There is no problem it prints all fields and labels in html table.
But my problem is that I want to divide template in to 2 parts. General and special fieldset.In general fields set i want to display Product model fields(name,price...).But Special field set changes according to product type. How I can handle this special fields set?Can someone give a clue or source please?
Thanks in advance!
You can manage it manually, in your specialized form class (not alter the base class).
Perhaps, with the use of sfWidgetFormSchema :
http://www.symfony-project.org/forms/1_4/en/A-Widgets#chapter_a_sfwidgetformschema
You have to name the widget 'general' and 'special', for a stanhdard re-use in form template, like this :
<?php echo $form['general'] ?>
<?php echo $form['special'] ?>