in your framework are there any automation to build forms?
For example let's say you have this array of fields:
$fields = array('name'=>array('type'=>'input',otherparams)
'desc'=>array('type'=>'textarea',otherparams)
);
based on fields you should make HTML like this:
<form>
Name: <input name="name" type="text">
Description: <textarea name="desc"></textarea>
//>Submit
</form>
Do you build your html by-hand or is there some sort of automation?
Thanks
I work with the Yii framework. The php generates the html automatically. You write some html by hand but it's for the views. The views also have dynamic php variables that change. The actually full html document is put together by calling a controller with the web address, that controller deciding what models if any it needs to apply to the form and what view to put the model in. Then it generates the html.
SiteController.php
<?php
class SiteController extends Controller
{
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->render('index');
}
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
/**
* Displays the contact page
*/
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$headers="From: {$model->email}\r\nReply-To: {$model->email}";
mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}
/**
* Displays the login page
*/
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
/**
* Logs out the current user and redirect to homepage.
*/
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
ContactForm.php = This is the model.
<?php
/**
* ContactForm class.
* ContactForm is the data structure for keeping
* contact form data. It is used by the 'contact' action of 'SiteController'.
*/
class ContactForm extends CFormModel
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
*/
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
}
This is the view:
contact.php
<?php
$this->pageTitle=Yii::app()->name . ' - Contact Us';
$this->breadcrumbs=array(
'Contact',
);
?>
<h1>Contact Us</h1>
<?php if(Yii::app()->user->hasFlash('contact')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('contact'); ?>
</div>
<?php else: ?>
<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm'); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'body'); ?>
<?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?>
</div>
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
</div>
<?php endif; ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>
Going to the page: http://yoursite/index.php/contact/ activates the actionContact method in the SiteController. That grabs the posted contact information, puts it into a model, and then renders a view.
CodeIgniter allows you to build forms using the Form Helper, although I prefer to write the HTML myself.
try this(not tested)
<?php
$fields = array('name'=>array('type'=>'input',name='fname')
'desciprtion'=>array('type'=>'textarea',name='desc')
);
?>
<form name="myform" action="" method="post">
<?php
foreach($fields as $key=>$value)
{
echo "<label>$key</label>";
echo " <$key['type'] name=\"$key['name']\" id=\"$key['id']>\">
}
?>
Related
I am working on codeigniter. I did the sql query to insert the data into the database.my query is running perfectly and is shown in the database table.
But i want to display message if my data is inserted into the table(like data inserted successfully).
here is my controller code:
public function insert(){
$post=$this->input->post();
unset($post['submit']);
if($this->testimonial_model->insert_testimonial($post))
{
$this->session->set_flashdata('feedback',"Data inserted successfully.");
$this->session->set_flashdata('feedback_class','alert-success');
}else{
$this->session->set_flashdata('feedback',"failed to add, Please Try again");
$this->session->set_flashdata('feedback_class','alert-danger');
}
return redirect('testimonial_edit');
}
here is my model code:
public function insert_testimonial($insert){
return $this->db->insert('testimonial',$insert);
}
Here is my view code and my view file name is testimonial_edit
<?php
if($feedback=$this->session->flashdata('feedback')):
$feedback_class=$this->session->flashdata('feedback_class');
?>
<div class="row">
<div class="col-lg-6">
<div class="alert alert-dismissable <?php $feedback_class?>">
<?php $feedback?>
</div>
</div>
</div>
<?php
endif;
?>
Below this code my form code is there.
After filling form when i clicked on submit button the data is successfully inserted but it showing following error
404 Page Not Found
The page you requested was not found.
and url of this error page is
http://localhost/lalcoresidency/testimonials/dashbord
Please help me to find out the solution
You can't redirect to a view file, so try adding a method to the controller which simply loads the view; then redirect to that method:
public function insert(){
$post=$this->input->post();
unset($post['submit']);
if($this->testimonial_model->insert_testimonial($post))
{
$this->session->set_flashdata('feedback',"Data inserted successfully.");
$this->session->set_flashdata('feedback_class','alert-success');
}else{
$this->session->set_flashdata('feedback',"failed to add, Please Try again");
$this->session->set_flashdata('feedback_class','alert-danger');
}
redirect('current_controller_name/testimonial_edit');
}
/* add this function that you can redirect to,
and which will load the view file of the same name */
function testimonial_edit(){
$this->load->view('testimonial_edit');
}
As for your success message not displaying, try:
<?php if($this->session->flashdata('feedback')){ ?>
<div class="row">
<div class="col-lg-6">
<div class="alert alert-dismissable <?php echo $this->session->flashdata('feedback_class'); ?>">
<?php echo $this->session->flashdata('feedback'); ?>
</div>
</div>
</div>
<?php } ?>
Try it:-
public function insert(){
$this->load->library('session');
$post=$this->input->post();
unset($post['submit']);
if($this->testimonial_model->insert_testimonial($post))
{
$this->session->set_flashdata('feedback',"Data inserted successfully.");
$this->session->set_flashdata('feedback_class','alert-success');
}else{
$this->session->set_flashdata('feedback',"failed to add, Please Try again");
$this->session->set_flashdata('feedback_class','alert-danger');
}
echo ($this->session->flashdata('feedback_class')) ? $this->session->flashdata('feedback_class') : '';
echo ($this->session->flashdata('feedback')) ? $this->session->flashdata('feedback') : '';
die;
redirect(base_url('testimonial_edit'));
}
Add url helper in config file helper array
like $config['helper']=array("url");
I have created a basic login form with validation containing only that the fields are not empty.
In controller the index looks like
$this->load->helper('form');
$this->load->view('auth/login');
and this is the view
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<meta charset="utf-8">
<title>LOGIN
</title>
</head>
<body>
<h1>Simple Login with CodeIgniter</h1>
<?php echo form_open('login/verifylogin'); ?>
<div class="" style="margin:0">
<label for="username">Username:</label>
<div class="" style="display:inline-block;margin:0">
<?php echo form_input(['name'=>'username','class'=>'','placeholder'=>'Your username here','value'=>set_value('username')]); ?>
</div>
<?php echo form_error('username',"<div class='w3-text-red' style='display:inline-block'>","</div>"); ?>
</div>
<br/>
<div class="">
<?php echo form_label('Password:','pass'); ?>
<div class="" style="display:inline-block;margin:0">
<?php echo form_password(['name'=>'password','class'=>'','placeholder'=>'Your password here']); ?>
</div>
<?php echo form_error('password',"<div class='w3-text-red' style='display:inline-block'>","</div>"); ?>
</div>
<br/>
<?php echo form_submit('submit', 'Login'); ?>
<?php echo form_close(); ?>
</form>
</body>
</html>
When a user is successfully validated he is redirected to dashboard view but in address bar still I get http://192.168.1.102/login/verifylogin (192.168.1.102 is the localhost or specifically its my device address on which server is running).
Also if a user leaves a field empty then he is showed the view auth/login with respective errors but the address bar shows http://192.168.1.102/login/verifylogin.
Please guide me how to fix this.
I am a beginner in codeigniter (I also have hands on laravel).
I have removed the index.php file according to the given guide.
I use ubuntu 14.04
EDIT 1:- I don't want to display the method name in address bar if a user fails login
EDIT 2:- Controller:-
<?php
/**
*
*/
class Login extends CI_Controller
{
public function index()
{
$this->load->helper('form');
$this->load->view('auth/login');
}
public function verifylogin()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_numeric');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run()) {
$this->load->helper('url');
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('Loginmodel');
if ($this->Loginmodel->login_valid($username, $password)) {
redirect('dashboard');
}else {
$this->load->view('auth/login');
}
} else {
$this->load->view('auth/login');
}
}
}
?>
I'm using Ajax validation in my widget. here is the code.
Widget function
public function run(){
if(!Yii::app()->user->isGuest){
$this->controller->redirect('/');
}
$model= new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
// blah blah.......
Widget View:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableAjaxValidation'=> true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<div class="row">
<?php echo $form->textField($model,'username',array('placeholder'=>'email','class'=>'form-control')); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->passwordField($model,'password',array('placeholder'=>'password','class'=>'form-control')); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Login', array('class'=>'btn btn-primary btn-block')); ?>
</div>
...
Right now the form is not submitting. After I click login nothing happens.
If I make enableAjaxValidation fale, form works but not AJAX.
If I make enableClientValidation false, form works but still no AJAX.
Any ideas? Thanks.
The thing is you are using a single submit button, instead of an ajax submit button.
For this, you may use, for example, an ajaxSubmitButton widget from Yii Bootstrap (or Yii booster).
So, in the SiteController :
...
$model= new LoginForm;
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['LoginForm']))
{
$model->unsetAttributes();
$model->attributes=$_POST['LoginForm'];
if($model->validate() && $model->login())
{
$array = array('login' => 'success');
$json = json_encode($array);
echo $json;
Yii::app()->end();
}
else{ //This is the important point
if(Yii::app()->getRequest()->getIsAjaxRequest())
{
$array=$model->getErrors();
$json = json_encode($array);
echo $json; //JSON containing the errors set in /models/LoginForm.php
Yii::app()->end();
}
}
}
...
In your view:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableAjaxValidation'=> true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
<div class="row">
<?php echo $form->textField($model,'username',array('placeholder'=>'email','class'=>'form-control')); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->passwordField($model,'password',array('placeholder'=>'password','class'=>'form-control')); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row" >
<?php
/** THIS IS THE AJAX SUBMIT BUTTON **/
$this->widget('bootstrap.widgets.TbButton', array(
'buttonType' => 'ajaxSubmit',
'label' => 'Login',
'ajaxOptions' => array(
'success' =>
'function(data){
var obj = $.parseJSON(data);
if(obj.login=="success"){
//...
// $(location).attr("href","BASEURL/someController/someAction")
}
else{
if("username" in obj){
$("#LoginForm_username_em_").text(obj.username[0]);
$("#LoginForm_username_em_").show();
$("#LoginForm_username").css({"background":"#FEE","border-color":"#C00"});
}
if("password" in obj){
$("#LoginForm_password_em_").text(obj.password[0]);
$("#LoginForm_password").css({"display":"block"});
$("#LoginForm_password").css({"background":"#FEE","border-color":"#C00"});
}
$("#LoginForm_password_em_").show();
}
}'),
));
?>
</div>
In order to use the ajaxSubmitButton widget of Yii Bootstrap (or Yii Booster), you have to download it from http://yiibooster.clevertech.biz/, extract it in your /protected/extensions folder and include it in /protected/config/main.php :
...
Yii::setPathOfAlias('bootstrap',dirname(__FILE__).'/../extensions/bootstrap'); //booster insead of bootstrap if you download the Yii Booster.
return array(
...
'components'=>array(
...
'bootstrap'=>array(
'class'=>'ext.bootstrap.components.Bootstrap', // assuming you extracted bootstrap under extensions
),
)
)
Yii Booster has many other widgets, for this reason I use it. If you don't want to use Yii booster for the ajax submit button, just use the CHtml::ajaxSubmitButton
Ajax validation needs a bit of care.
Please check response at console for ajax call. In ajax validation the output of ajax call should be pure json. In case of ajax validation from widget may include some html with response of ajax call.
have a look at http://www.yiiframework.com/forum/index.php/topic/12222-ajax-validation-in-widget-does-not-work/ hope it may help you.
When we create a yii webapp using yiic, a login function is already made.
However, I want to use the navbar as a login widget (and bootstrap for design) as shown in here. That's when I encountered my problem. When I try to login using the toolbar/widget, the details I have input are displayed in the browser's bar and then nothing. See here.
This my LoginWidget.php
<?php class LoginWidget extends CWidget {
public function run() {
$model=new LoginForm;
$form= $this->beginWidget('CActiveForm', array(
'id'=>'login-form',
// 'action'=>
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
)
));
echo $form->errorSummary($model);
?>
<div class="form-group">
<?php echo $form->textField($model,'username',array('placeholder'=>'Employee Code','class'=>'form-control')); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="form-group">
<?php echo $form->passwordField($model,'password',array('placeholder'=>'Password','class'=>'form-control')); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<?php
echo CHtml::submitButton('Sign in', array('class'=>'btn btn-success'));
$this->endWidget();
}
} ?>
This is my Controller (just the necessary part).
public function actionIndex()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect('myprofile/index');
}
// display the login form
$this->render('index',array('model'=>$model));
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
// $this->render('index');
}
When I try to login using localhost/project/index.php/site/login, it works.
Make sure the form sends data with POST
$form= $this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'method' => 'POST',
'enableClientValidation'=>true,
'clientOptions'=>
array(
'validateOnSubmit'=>true,
)
));
I'm learning to create MVC component right now. I studied the code that was created using the component creator.
Now I wanna to locate the SQL insert function after the save button is click in the edit form, where does the form send to to call the insert function?
com_astock/admin/view/addstock/tmpl/edit.php
<?php
/**
* #version 1.0.0
* #package com_astock
* #copyright Copyright (C) 2013. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE.txt
* #author Joe <joequah1#hotmail.com> - http://
*/
// no direct access
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html');
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
JHtml::_('formbehavior.chosen', 'select');
JHtml::_('behavior.keepalive');
// Import CSS
$document = JFactory::getDocument();
$document->addStyleSheet('components/com_astock/assets/css/astock.css');
?>
<script type="text/javascript">
js = jQuery.noConflict();
js(document).ready(function(){
});
Joomla.submitbutton = function(task)
{
if(task == 'addstock.cancel'){
Joomla.submitform(task, document.getElementById('addstock-form'));
}
else{
if (task != 'addstock.cancel' && document.formvalidator.isValid(document.id('addstock-form'))) {
Joomla.submitform(task, document.getElementById('addstock-form'));
}
else {
alert('<?php echo $this->escape(JText::_('JGLOBAL_VALIDATION_FORM_FAILED')); ?>');
}
}
}
</script>
<form action="<?php echo JRoute::_('index.php?option=com_astock&layout=edit&stock_code=' . (int) $this->form->getInput('stock_code')); ?>" method="post" enctype="multipart/form-data" name="adminForm" id="addstock-form" class="form-validate">
<div class="row-fluid">
<div class="span10 form-horizontal">
<fieldset class="adminform">
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('stock_code'); ?></div>
<div class="controls"><?php echo $this->form->getInput('stock_code'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('name'); ?></div>
<div class="controls"><?php echo $this->form->getInput('name'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('state'); ?></div>
<div class="controls"><?php echo $this->form->getInput('state'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('time_created'); ?></div>
<div class="controls"><?php echo $this->form->getInput('time_created'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('created_by'); ?></div>
<div class="controls"><?php echo $this->form->getInput('created_by'); ?></div>
</div>
</fieldset>
</div>
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
if the html the action is index.php/view=addstock&layout=edit
Where does the layout edit call to? I had try to locate my entire component I couldn't find any insert SQL.
I will be showing my index.html.php as well
<?php
/**
* #version 1.0.0
* #package com_astock
* #copyright Copyright (C) 2013. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE.txt
* #author Joe <joequah1#hotmail.com> - http://
*/
// No direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
/**
* View to edit
*/
class AStockViewAddstock extends JViewLegacy
{
protected $state;
protected $item;
protected $form;
/**
* Display the view
*/
public function display($tpl = null)
{
$this->state = $this->get('State');
$this->item = $this->get('Item');
$this->form = $this->get('Form');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
throw new Exception(implode("\n", $errors));
}
$this->addToolbar();
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*/
protected function addToolbar()
{
JFactory::getApplication()->input->set('hidemainmenu', true);
$user = JFactory::getUser();
$isNew = ($this->item->stock_code == 0);
if (isset($this->item->checked_out)) {
$checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $user->get('stock_code'));
} else {
$checkedOut = false;
}
$canDo = AStockHelper::getActions();
JToolBarHelper::title(JText::_('COM_ASTOCK_TITLE_STOCK'), 'addstock.png');
// If not checked out, can save the item.
if (!$checkedOut && ($canDo->get('core.edit')||($canDo->get('core.create'))))
{
JToolBarHelper::apply('addstock.apply', 'JTOOLBAR_APPLY');
JToolBarHelper::save('addstock.save', 'JTOOLBAR_SAVE');
}
if (!$checkedOut && ($canDo->get('core.create'))){
JToolBarHelper::custom('addstock.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false);
}
// If an existing item, can save to a copy.
if (!$isNew && $canDo->get('core.create')) {
JToolBarHelper::custom('addstock.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false);
}
if (empty($this->item->stock_code)) {
JToolBarHelper::cancel('addstock.cancel', 'JTOOLBAR_CANCEL');
}
else {
JToolBarHelper::cancel('addstock.cancel', 'JTOOLBAR_CLOSE');
}
}
}
You cannot see save code as your controller and model extends parent classes.
You can create your own public function save in controller and model or override it.
Basically this is how it works:
Controller method 'Save' is called, which validates data and loads model.
Controller calls Model and pass him valid data.
Model loads JTable, which stores the data and returns true or false
Model returns bool to controller
Controller handles redirect
Classes are located in:
libraries/legacy/controller and libraries/legacy/model
Try to create your component using the Component Creator and see how it does it. It can be a great leaning tool.
simple presave hook:
go to your model and write:
public function save($data){
// do stuff with $data
return parent::save($data);
}
better would be using the prepareTable function:
protected function prepareTable($table)
{
$table->fieldname = 'new_value';
}