Cakephp: combine input values to create hidden name input - cakephp

I've searched high and low for a solution but can't seem to get this figured out. What I'm trying to do is upon adding a product, I want the name field to be populated from the inputs in the form. So the name would include the values the user selects for type_id,category_id and subcategory_id. Does anyone know of a way to accomplish this?
Add product View page
<fieldset>
<legend><?php echo __('Add Product'); ?></legend>
<?php
echo $this->Form->input('type_id');
echo $this->Form->input('category_id', array('label' => 'Vendor'));
echo $this->Form->input('subcategory_id', array('label' => 'Model'));
echo $this->Form->input('location', array('label' => 'Location'));
echo $this->Form->input('sku', array('label' => 'Asset Tag'));
echo $this->Form->input('mac');
echo $this->Form->input('description', array('label' => 'Notes'));
echo $this->Form->input('name', array( 'value' => ['type_id']['category_id'] , 'type' => 'hidden'));
//echo $this->Form->input('cost');
// echo $this->Form->input('Tag');
?>
</fieldset>
Product controller add function
public function add() {
if ($this->request->is('post')) {
$this->Product->create();
if ($this->Product->save($this->request->data)) {
$this->Session->setFlash(__('The product has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The product could not be saved. Please, try again.'));
}
}
$subcategories = $this->Product->Subcategory->find('list',array('order'=>'Subcategory.name asc'));
$categories = $this->Product->Category->find('list',array('order'=>'Category.name asc'));
$types = $this->Product->Type->find('list',array('order'=>'Type.name asc'));
$this->set(compact('subcategories', 'categories', 'types'));
}

In order to do it the way you are trying to do it, you would have to use client-side javascript to update the input value "on-the-fly", but that's not very safe and can easily be messed with. It would make much more sense to drop the name input altogether and just handle this in the beforeSave method of your Product model (or alternatively by defining the name value in your Controller just before saving).
public function beforeSave($options = array()) {
// Generate the name based on type and category
$this->data['Product']['name'] = $this->data['Product']['type_id'] .
$this->data['Product']['category_id'];
return true;
}
Update based on your comment.
In order to get the names, just find those names (assuming your models are associated) and define those:
public function beforeSave($options = array()) {
// Get the type name
$type = $this->Type->field('name', array(
// Set the condition for the field
'Type.id' => $this->data['Product']['type_id']
));
// Get the category name
$category = $this->Category->field('name', array(
// Set the condition for the field
'Category.id' => $this->data['Product']['category_id']
));
// Generate the name based on type and category
$this->data['Product']['name'] = $type . $category;
return true;
}

Related

cakephp canot save form control field in database

i am trying to make an simple cakephp aplication!
I have a form that creates a new article.. my problem is that i have an input field for the artice slug but when i cakephp submits te form the slug field in database remains empty..
here is the add method from my articleController
public function add(){
$article = $this->Articles->newEntity(); //gffdgfd
if ($this->request->is('post')){
$this->Articles->patchEntity($article, $this->request->data());
if($this->Articles->save($article)){
$this->Flash->success(__('Your Article has been saved!'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Cannot save article! Please try again!!'));
}
$this->set('article', $article);
}
and my add.ctp
<h1>Add Article</h1>
<?php
echo $this->Form->create($article);
echo $this->Form->control('user_id', ['type' => 'hidden', 'value'=> 1 ]);
echo $this->Form->control('published', ['type' => 'hidden', 'value'=> 1 ]);
echo $this->Form->control('title');
echo $this->Form->control('slug');
echo $this->Form->control('body', ['rows' => 5 ]);
echo $this->Form->button(__('Save Article'), ['class' => 'button', 'style' => 'margin-right:10px; margin-left:10px']);
echo $this->Html->link('Back', ['action' => 'index'], ['class' => 'button']);
echo $this->Form->end();
?>
If slug field is present in your request data, then you should check if this field is accessible for assignment in your entity. Look at file src/Model/Entity/Article.php, on top of class body you will have an array named $_accessible - check if your slug field is present, and if not, set it to true:
protected $_accessible = [
/* other fields */
'slug' => true
];
Please check more about assignment of properties in docs: CakePHP 3 Entities - Mass Assignment

how to save select option value in database on cakephp

I wanna save a selected option in database in cakephp.
here is my add.ctp code
<?php
$options = array('0' => 'male', '1' => 'female');
echo $this->Form->select('gender', $options, array('escape' => false,'id'=>'gender'));
?>
and this is my action :
$user=$this->Users->newEntity();
if($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
print_r($user);
$this->Users->save($user);
}
But when I run it just the value 1 saved on database even I choose male.
please help.
The type of gender on database was bit I changed it to INT and every thing works correctly.

Basic CakePHP: Unable to get the id (Edit Method)

This my database:
http://gyazo.com/c6a86127d6f91aae947cf45ee535cecd
Example:
http://gyazo.com/c23fec3fabb7e4504c42453980fbc372
When I press the edit button , they able to retrieve the data however the page show me empty field instead of the field that have old data.
Secondly, unable to undate because they keep send empty id_field back to controller.
p.s. add,edit,delete method work totally fine.
Below are my code:
Model
<?php
App::uses('AppModel', 'Model');
class EventDate extends AppModel {
public $useTable = 'eventdate';
public $primaryKey = 'eventDate_id';
public $validate = array(
'event_date' => array(
'rule' => array('date','ymd'),
'message' => 'Enter a valid date in YY-MM-DD format.',
'required' => true,
'allowEmpty' => false
)
);
}
Controller
public function edit($id = null) {
//Retrieve from database
$post = $this->EventDate->findByEventdateId($id);
$this->set('edate', $post) ;
// debug($post);
//Without Id
if (!$id) {
throw new NotFoundException(__('Invalid Event Date'));
}
//If Not Exist the id
if (!$post) {
throw new NotFoundException(__('Invalid Event Date'));
}
//After press the submit
if ($this->request->is(array('post','put'))) {
$this->EventDate->eventDate_id = $id;
debug($_POST);
if ($this->EventDate->save($this->request->data)) {
$this->Session->setFlash(__('The Event has been saved.'));
return $this->redirect(array('action' => 'index'));}
else
{$this->Session->setFlash(__('The Event could not be saved. Please, try again.'));}
}
//Set the data same as retrieved
if (!$this->request->data) { $this->request->data = $post;}
}
edit.ctp
<h2>Edit Event</h2>
<?php
echo $this->Form->create('eventdate');
//echo $this->Form->input('eventDate_id', array('type' => 'hidden'));
echo $this->Form->hidden('eventDate_id');
echo $this->Form->input('event_date',array(
'label' => 'Event Date',
'type' => 'text',
'id' => 'datepicker'));
echo $this->Form->end('Save Post');
?>
Below link is the debug($_Post) been shown:
http://gyazo.com/5e569e6cc6b3026fc8896c315197a938
Should be:
echo $this->Form->create('EventDate'); // notice the capital CamelCase
Side note: The info that displays in the fields will be out-of-date, since you 1) get the data from the DB and set to var, THEN do the save based on posted data.
Another side note: There are quite a few things that you're doing that are non-standard and not consistent w/ the recommended conventions. Cleaning that up will make it easier to work with AND easier to receive help.

CakePHP drop down box from associated model

I have a simple api that allows customers to book vehicles. In my reservations controller i have a function which is to add a reservation. Here is the code:
Controller
function add() {
if($this->request->is('post')) {
if($this->Reservation->save($this->data)) {
$this->Session->setFlash('The Reservation was successfully added!');
$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash('The Reservation was not added.');
}
}
$this->set('title_for_layout','Add Reservation');
}
Here is what i have in my add view for a reservation.
View
<?php
echo $this->Form->create('Reservation', array('action'=>'add'));
echo $this->Form->input('customer_id', array( 'type' => 'text' ) );
echo $this->Form->input('vehicle_id', array( 'type' => 'text' ) );
echo $this->Form->input('date');
echo $this->Form->end('Add Reservation');
?>
But because i am adding a new reservation and i want a dropdown box for vehicle ids and one for customer ids how can i do this?
I think i have linked the models by putting this into the customers and vehicles models:
var $hasMany = array( 'Reservation' => array( 'className' => 'Reservation' ) );
Could anyone point me into the right direction so that a dropdown box would appear with a list of vehicle and customer IDs on the add reservation page.
In your add function in controller, use
$vehicle = $this->Reservation->Vehicle->find('list', array('fields' =>array('Vehicle.id','Vehicle.name')));
$this->set('vehicle', $vehicle);
In your view,use
<?php echo $this->Form->input('vehicle_id', array('type' => 'select',
'options' => $vehicle)); ?>
Use the same thing for customers also and you will get list of customers and vehicles in dropdown.

how to combine two HABTM saves in one form in CakePHP?

I have two models Business and User. They are related by a HABTM relationship.
Everything is working with the baked controllers, models and views.
Now I'm trying to combine the two models in one form so the user can enter a business name with is user info.
Here's the form :
Form->create('User'); ?>
Form->input('Business.name', array('label' => __('Business name')));
echo $this->Form->input('User.email');
echo $this->Form->input('User.firstname');
echo $this->Form->input('User.lastname');
echo $this->Form->input('User.password');
echo $this->Form->input('User.phone_cell', array('type' => 'text'));
echo $this->Form->input('User.phone_home', array('type' => 'text'));
echo $this->Form->input('User.phone_work', array('type' => 'text'));
?>
Form->end(__('Submit')); ?>
The only way I was able to make it work was to save the User first and then get the user id and save the business after by adding the user array with the new id.
if ($this->User->save($this->request->data)) {
$this->request->data['User'] = array('User' => array(0 => $this->User->id));
if ($this->User->Business->save($this->request->data)) {
// User saved
} else {
// User not saved
}
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
I tried the saveAll method without success. Is is possible to optimize this the CakePHP way for a single save ?
Thanks
I was able to get it to work myself with a couple models named User and Group. Here's some snips from my code to show how I did it:
UsersController.php
public function edit($id = null)
{
$this->User->id = $id;
if ($this->request->is('get')) {
//On page load load the user data
$this->request->data = $this->User->read();
} else {
//Saving
if ($this->User->save($this->data)) {
//....snipped...
} else {
$this->Session->setFlash('Unable to update the user.');
}
}
//Build $groups array for form
// Only admins can assign admin rights
if ($this->isMember('Admin')) {
$this->set('groups',$this->User->Group->find('list'));
} else {
$this->set('groups',$this->User->Group->find('list',array(
'conditions' => array(
'Group.name !=' => 'Admin'
)
)));
}
//...more snipping...
}
edit.ctp (View)
echo $this->Form->create('User', array('action' => 'edit'));
echo $this->Form->input('User.username');
echo $this->Form->input('Group',array(
'type' => 'select',
'multiple' => true,
'label' => "Group (Select multiple entries with CTRL)",
'size' => count($groups)
)
);
//More snipping
With that example to work from, how are you validating that the Business.name entered is valid and can be matched to the HABTM relation? Mine forces a selection list in this case. My Model is extremely simple so I didn't include that.
What are your outputs to debug($this->data); vs. debug($this->request->data)?

Resources