i'am a cakephp newbie :D
how can i modify data in a controller before cakephp put the data into mysql?
function add() {
if (!empty($this->data)) {
$this->Template->create();
/* This works! */
$this->data['Template']['slug'] = Inflector::slug(utf8_encode(strtolower($this->data['Template']['name'])),'-');
/* does not work ! */
$this->data['Template']['created'] = time();
$this->data['Template']['category_id'] = $this->data['Template']['category'];
if ($this->Template->save($this->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
}else{
/* dropdown */
$this->set('categories',$this->Template->Category->find('list'));
}
}
Fields in my database:
templates
id
slug
category_id (belong to categories)
name
created
Can anyone help my?
greetings!
The correct way is putting it in your Model, not in your controller (because you are treating data, so it must be in the model).
For this, you can use model's "beforeSave" method:
Cake1.2: http://book.cakephp.org/view/683/beforeSave
Cake1.3: http://book.cakephp.org/view/1052/beforeSave
Cake 2: http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave
Related
I want to display a members details on screen when I select their name from a Dropdown
More information: I have a form that submits a few fields. Amongst them I have a "Select User" Dropdown to link this person to the data being submitted
Problem is- client wants the user's details to show when they select a user(make sure its the right person etc)
How can i accomplish this? There are like 3 seperate input fields that will need to contain data. I know how to do it using raw PHP/javascript, but do not know how to implement this in a Silverstripe way
You don't have to use Ajax for this, when you setup the form on your controller you can use loadDataFrom (http://api.silverstripe.org/3.3/class-Form.html#_loadDataFrom) to load the member directly into the form.
An example implementation could be (I haven't tested this, but it should work):
class Page_Controller extends ContentController
{
public function index()
{
$member = Member::currentUser();
$this->customise(array(
"Form" => $this->Form()->loadDataFrom($member)
));
}
public function Form() {
return Form::create(
$this,
"Form",
$fields, // Add your own fields here
$actions // Add your own actions here
);
}
}
Got a solution based off of this: https://www.silverstripe.org/community/forums/form-questions/show/24628
The way I did it was like this:
SS template
$("table.myTable").on('change','select#Some_Form',function(){
$.ajax({
type: "POST",
data: {param:param},
url: window.location.href+"your_action_here",
success: function(result) {
var resArr = JSON.parse(result);
$('input#Some_Field').val(resArr['key']);
}
});
});
Controller
static $allowed_actions = array('your_action_here');
//parameter is a SS_HTTPRequest
public function your_action_here($request){
//assuming my parameter is an ID
$ID = $request['param'];
$dataObject = DataObject::get_by_id('Object',$ID);
$JSONArray = array('key'=>$dataObject->Field);
echo json_encode($JSONArray);
}
When the select changes, gets the DataObject and populates correctly :)
I am new in cakePHP try to create a blog site where user add blog after category select, I have one categories table : fields: category_id, name and posts table : fields : id, category_id , title, body.
I want to fetch all categories to a dropdown list. When user add new post they have to select category first then he is able to post anything..
My PostsController:
<?php
class PostsController extends AppController{
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session','Paginator');
public function index(){
$this->Paginator->setting = array(
'limit' =>'10',
'order' => array('Post.id' =>'Desc')
/*'conditions' => array(
'Post.user_id' => AuthComponent::user(id)
)*/
);
$arrPosts = $this->Paginator->paginate('Post');
$this->set('posts', $arrPosts);
}
public function view($id = null){
if(!$id){
throw new NotFoundException(__("Error Processing Request ID"));
}
$post =$this->Post->findById($id);
if(!$post){
throw new NotFoundException(__("Error Processing Request POST"));
}
$this->set('post',$post);
}
public function add(){
// HERE I want to fetch all categoryies from categories table and want to send to view
if($this->request->is('post')){
$this->Post->create();
if($this->Post->save($this->request->data)){
$this->Session->setFlash(__('Blog Posted Sucessfully'));
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__('Unable to Post Blog '));
}
}
}
}
?>
I want to show my category in add form:
Please help me ...
In your controller action you need to use $this->set() to set a View variable. As long as you've got your associations setup correctly in your Post model you should then be able to use:-
$this->set('categories', $this->Post->Category->find('list'));
Cake's FormHelper should automatically know that the Post.category_id form field wants to be a select input with $categories as the options.
One further point, it would be better to set the view variables after processing the form as you won't need them if it saves correctly and so can reduce the number of database queries by 1.
If you use find('all') to retrieve the categories you will need to convert it into the format used by find('list') which can easily be done using Hash::combine():-
$categories = $this->Post->Category->find('all');
$this->set(
'categories',
Hash::combine($categories, '{n}.Category.id', '{n}.Category.name')
);
The only real value in doing this is if you need $categories for something else.
public function add(){
/*Here get the category list & set the view (ctp file)*/
$this->set('categories', $this->Post->Category->find('list'));
if($this->request->is('post')){
$this->Post->create();
if($this->Post->save($this->request->data)){
$this->Session->setFlash(__('Blog Posted Sucessfully'));
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__('Unable to Post Blog '));
}
}
}
//Set The dropdown in ctp file
$this->Form->input('category_id', array('type'=>'select', 'options'=>'categories'));
I'd like to ask, is it possible to change the original posted attributes in actionCreate()?
For example I have 3 attributes: name, phNumber, address
In the _form.php, it automatically posts these 3 attributes. BUT what if I want to change the posted name attribute to all Uppercases? Do I need to create my own method of creating a record just to change how the name will be recorded OR is there something that I can do in actionCreate() so that it only changes the name attribute?
For example, user types in
adam michael
for the name textbox, and I want to change only this attribute to
ADAM MICHAEL
to be recorded in the database instead of having to create another method.
Code below:
public function actionCreate() {
$model = new Masseuse;
if (isset($_POST['Masseuse'])) {
$model->setAttributes($_POST['Masseuse']);
if ($model->save()) {
if (Yii::app()->getRequest()->getIsAjaxRequest())
Yii::app()->end();
else
$this->redirect(array('servicemasseuse/create', 'mid' => $model->id));
}
}
$this->render('create', array( 'model' => $model));
}
Just simply do a $model->name=strtoupper($model->name);
Refer here
You must alter the user input prior to saving the data. You do this by creating an overwritten function in your model.
class Masseuse extends CActiveRecord {
// ...
public function beforeSave()
{
$this->name = strtoupper($this->name)
}
}
I am using a Yii hiddenField in a CActiveForm widget. I have saved this hidden field value in database. There is no issue with storing in DB with Controller action at all. after saving this the hidden field should display the value. And how can I populate the form with the database stored value. Or how to refer some other field in the form to contain value from DB after save is processed.
<?php echo $form->hiddenField($model,'ad_form_id',array('value'=>$base)); ?>
My controller action
public function actionBCFormFields()
{
$model=new BCFormField();
if(isset($_POST['BCFormField']))
{
$model->ad_form_id = $_POST['BCFormField']['ad_form_id'];
$model->attributes=$_POST['BCFormField'];
if ($model->save()){
echo'saved';
}
$this->redirect(array('create',
'crm_base_form_field_id'=>$model->crm_base_form_field_id));
}
Based on the very litle code you have given us i would suggest something like this in your controller, but if you edit your question and elaborate , i will edit my question:
public $ad_form_id
public function actionCreate()
{
$model = new User;
$this->ad_form_id = $this->base;
if (isset($_POST['User'])) {
$model->attributes = $_POST['User'];
$this->base = $this->ad_form_id;
if ($model->validate() && $model->save()) {
$this->redirect(array('view'));
}
}
$this->render('create',array('model' => $model,));
}
There is a 'main.php' view that contains a form with email and name fields and a submit button. Eveyrthing works fine with action_index (the code is below), but I'm curious how to modify the code below so it validates if the email was entered correctly. It should not put values in the database if the email field is not valid. I hope it is possible to made using ->rule. Is it? If yes, then how where to add the validation? (I had no luck trying it in different ways).
public function action_index()
{
if ( !empty($_POST) ) {
$model = ORM::factory('tbl1'); // create
$model->values($_POST); // load values to model
if ($model->check()) {
$model->save(); // save the model
} else {
//show errors
}
}
$this->response->body(View::factory('main'));
}
Thank you.
Use rules function in your ORM model:
public function rules()
{
return array(
'email' => array(
array('email', array(':value')),
),
);
}