Cakephp Model error - cakephp

I am facing a strange problem while creating edit functionality in cakephp 2.1
Error genreated:
Illegal offset type [CORE\Cake\Model\Model.php, line 2689]
My edit.ctp file is
<?php echo $this->Form->create('Task');?>
<fieldset>
<legend>Edit Task</legend>
<?php
echo $this->Form->hidden('id');
echo $this->Form->input('title');
echo $this->Form->input('done');
?>
</fieldset>
<?php echo $this->Form->end('Save');?>
Model: Task.php
<?php
class Task extends AppModel {
var $name = 'Task';
}
?>
Controller :TasksController.php
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html', 'Form');
function index() {
$this->set('tasks', $this->Task->find('all'));
}
function add() {
if (!empty($this->data)) {
$this->Task->create();
if($this->Task->save($this->data)){
$this->Session->setFlash('The Task has been saved');
$this->redirect(array('action'=>'index'),null,true);
}else{
$this->Session->setFlash('Task not saved.Try again.');
}
}
}
function edit($id = null) {
if (!$id) {
$this->Session->setFlash('Invalid Task');
$this->redirect(array('action' => 'index'), null, true);
}
if (empty($this->data)) {
$this->data = $this->Task->find(array('id' => $id));
} else {
if ($this->Task->save($this->data)) {
$this->Session->setFlash('The Task has been saved');
$this->redirect(array('action' => 'index'), null, true);
} else {
$this->Session->setFlash('The Task could not be saved.Please, try again.');
}
}
}
}
?>

I think your find() method is erroneous:
$this->data = $this->Task->find(array('id' => $id));
change to
$this->data = $this->Task->find('all', array('conditions' => array('id' => $id)));
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html

In order to prepopulate the data on the form you need to do the following:
<?php echo $this->Form->create('Task');?>
<fieldset>
<legend>Edit Task</legend>
<?php
echo $this->Form->hidden('id', array('value' => $this->data[0]['Task']['id']));
echo $this->Form->input('title', array('value' => $this->data[0]['Task']['title']));
echo $this->Form->input('done', array('value' => $this->data[0]['Task']['done']));
//var_dump($this->data[0]['Task']['id']);
?>
</fieldset>
<?php echo $this->Form->end('Save');?>
<?php echo $this->Html->link('List All Tasks', array('action'=>'index')); ?><br />
<?php echo $this->Html->link('Add Task', array('action'=>'add')); ?><br />
<?php echo $this->Html->link('List Done Tasks', array('action'=>'index')); ?><br />
<?php echo $this->Html->link('List Pending Tasks', array('action'=>'index')); ?><br />

Related

CakePHP-3.0 plugin form validation error message and entered data

I have created a CommentManager plugin for adding comments in my posts. Adding the comment form in Posts/view.ctp file and the comment form action is redirecting to CommentManager/Comments/add.
The comments are saving properly but when saving empty form, that doesn't shows the validation error messages which i have written in CommentsTable and also the entered data has gone from the form.
CommentManager/src/Controller/CommentsController/add
public function add()
{
$ccomment = $this->Comments->newEntity($this->request->data);
if ($this->request->is('post')) {
$newData = ['post_id' => $this->request->params['pass'][0]];
$ccomment = $this->Comments->patchEntity($ccomment, $newData);
if ($this->Comments->save($ccomment)) {
$this->Flash->success('The comment has been saved.');
return $this->redirect($_SERVER['HTTP_REFERER']);
} else {
$this->Flash->error('The comment could not be saved. Please, try again.');
}
}
$this->set(compact('ccomment'));
return $this->redirect($_SERVER['HTTP_REFERER']);
}
CommentManager/src/Model/Table/CommentsTable
public function validationDefault(Validator $validator) {
return $validator
->notEmpty('body', 'Body contents required.')
->notEmpty('email', 'An email is required.')
->add('email', [
'format' => [
'rule' => [
'custom',
'/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'
],
'message' => 'Enter a valid email.'
]
]);
}
src/Template/Posts/view.ctp
<?php echo $this->Html->link('Back', ['action' => 'index']) ?>
<?php echo $this->element('check_login'); ?>
<br/>
<?php $img_path = DS.'webroot'.DS.'images'.DS.$post->image; ?>
<img src="<?php echo empty($post->image)?'':$img_path; ?>">
<h2><?php echo $post->title; ?></h2>
<p><?php echo $post->body; ?></p>
<p><small><?php echo $post->created->format('d M Y'); ?></small></p>
<h3>Comments:</h3>
<?php foreach ($comments as $comment) { ?>
<p><?php echo $comment->body; ?></p>
<?php } ?>
<?php
echo $this->Form->create(null, ['url' => ['plugin' => 'CommentManager', 'controller' => 'Comments', 'action' => 'add', $post->id]]);
echo $this->Form->input('body', ['type' => 'textarea', 'rows' => '5', 'cols' => '5']);
echo $this->Form->input('email');
echo $this->Form->button('Save');
echo $this->Form->end();
?>
Don't call newEntity() with an empty array. Inste of
$ccomment = $this->Comments->newEntity($this->request->data);
Do:
$ccomment = $this->Comments->newEntity();
And in in the call to patchEntity() pass the $this->request->data

edit 2 models with one view and controller cakephp

I have 2 models. Typology and TypologyPicture. and 2 controllers Typologies and TypologyPictures. I want to edit both typology and typologyPcture from one controller.
<?php echo $this->Form->create('TypologyPicture', array('type'=>'file')); ?>
<legend><?php echo __('Edit Typology Picture'); ?></legend>
<?php echo $this->Form->input('id'); ?>
<!-- Here is the first part for the update Typolohgy -->
<?php echo $this->Form->input('Typology.item_id',array('empty'=>true)); ?>
<?php echo $this->Form->input('Typology.title'); ?>
<?php echo $this->Form->input('Typology.description');?>
<?php echo $this->Form->input('Typology.thumbnail',array('type'=>'file')); ?>
<?php echo $this->Form->input('Typology.typology_category_id',array('empty'=>true)); ?>
<?php echo $this->Form->input('Typology.typology_condition_id',array('empty'=>true)); ?>
<?php echo $this->Form->input('Typology.price',array('placeholder'=>'Price')); ?>
<!-- Here is the second part for the update Typpology Picture -->
<?php echo $this->Form->input('pic_path', array('label'=>'Picture','type'=>'file')); ?>
<?php echo $this->Form->end(__('Submit')); ?>
This is the view. which contain the field for typology (item_id|title|description|thumbnial|typology_category_id|typology_condition_id)
and the field for typologypictures (pic_path)
The controller (that is at TypologyPicturesController) is:
public function edit($id = null) {
if (!$this->TypologyPicture->exists($id)) {
throw new NotFoundException(__('Invalid typology picture'));
}
if ($this->request->is(array('post', 'put'))) {
if(empty($this->data['TypologyPicture']['pic_path']['name'])){
unset($this->request->data['TypologyPicture']['pic_path']);
}
if ($this->TypologyPicture->saveAll($this->request->data)) {
$this->Session->setFlash(__('The typology picture has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The typology picture could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('TypologyPicture.' . $this->TypologyPicture->primaryKey => $id));
$this->request->data = $this->TypologyPicture->find('first', $options);
$opt = array('conditions' => array('Typology.id' => $this->request->data['TypologyPicture']['typology_id']));
$this->request->data = $this->Typology->find('first', $opt);
}
if ( AuthComponent::user('role')==='admin' ||AuthComponent::user('role')==='superadmin' ){ //if the user is admin or superadmin, show all on dropdown
$items = $this->Typology->TypologyItem->find('list');
} else {// else if the user is author, show only item created by him.
$items = $this->Typology->TypologyItem->find('list', array('conditions' => array('TypologyItem.user_id' => AuthComponent::user('id'))));
}
$typologyCategories = $this->Typology->TypologyCategory->find('list');
$typologyConditions = $this->Typology->TypologyCondition->find('list');
$users = $this->Typology->TypologyUser->find('list');
$this->set(compact('items', 'typologyCategories', 'typologyConditions', 'users'));
if ( AuthComponent::user('role')==='admin' ||AuthComponent::user('role')==='superadmin' ){
$typologies = $this->TypologyPicture->ItemTypologyPicture->find('list');
} else {
$typologies = $this->TypologyPicture->ItemTypologyPicture->find('list', array('conditions' => array('ItemTypologyPicture.user_id' => AuthComponent::user('id'))));
}
$this->set(compact('typologies'));
}
And when i try to edit, it opens the form, the fields are filled properly, but wheni press save there is new row inserted at typologyPicture and no change at all to Typology.
So what i want is that when the user press submit only the correspondings rows are updated and not to insert new rows.....

form data not saving and not update image files and filed name in multiple tables

in this editdrprofile.ctp file not retrieves gender field value and when am click save Drprofile link in editprofile page no action donne page refreshing no image uploaded nothing changed
app/Controller/DashboardsController.php
public function index() {
$this-> loadModel('Drprofile');
$this->set('variable', $this->Drprofile->find('all', array('conditions' => array('Drprofile.user_id' => $this->Auth->user('id')))));
}
public function editdrprofile($id = null) {
$this-> loadModel('Drprofile');
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Drprofile->findByuser_id($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('Drprofile', 'put'))) {
$this->Drprofile->user_id = $id;
// $this->set('posts', $this->carrier->find('all'));
if($this->request->is('post')){
Configure::read();
// pr($this->data);
$this->Carrier->create();
$filename = null;
if (
!empty($this->request->data['Drprofile']['image']['tmp_name'])
&& is_uploaded_file($this->request->data['Drprofile']['image']['tmp_name'])
) {
// Strip path information
$filename = basename($this->request->data['Drprofile']['image']['name']);
move_uploaded_file(
$this->data['Drprofile']['image']['tmp_name'],
WWW_ROOT . DS . 'documents' . DS . $filename
);
//$this->data['Carrier']['Resume'] = $filename;
}
//pr($filename);
// Set the file-name only to save in the database
$this->request->data['Drprofile']['image'] = $filename;
pr($this->data);
if ($this->Drprofile->save($this->request->data)) {
// ...
/*if ($this->Carrier->save($this->request->data)) {
if ($this->Carrier->save($this->data)) {
*/
$this->Session->setFlash(__('Your Details has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to add your Details'));
}
}
/*pr_('$this->Drprofile->user_id = $id');
if ($this->Drprofile->save($this->request->data)) {
//$this->Drprofile->save($this->request->data);
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));*/
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
in model
app/model/Drprofile.php
<?php class Drprofile extends AppModel {
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
?>
in view/dashboards/index.ctp
<?php
foreach ($variable as $post1):
?>
<table>
<tr><h3>Doctor Profile</h3></tr>
<tr> <td>TTTTTTTTTTTTTTTTTTTTTTTTTTTT</td> <td><table>
<tr><td>Name</td><td><?php echo $post1['User']['fullname'];?></td></tr>
<tr><td>Email</td><td><?php echo $post1['User']['email'];?></td></tr>
<tr><td>Mobile</td><td><?php echo $post1['User']['contactnumber'];?></td></tr>
<tr><td>Gender</td><td><?php echo $post1['User']['gender'];?></td></tr>
<tr><td>D.O.b</td><td><?php echo $post1['Drprofile']['dob'];?></td></tr>
<tr><td>Experience</td><td><?php echo $post1['Drprofile']['exp'];?></td></tr>
</table></td></tr>
</table>
<?php
echo $this->Html->link(
'Edit Profile', array('action' => 'editdrprofile', $post1['Drprofile']['user_id'])
);
?>
<?php
endforeach; ?>
app/view/editdrprofile.ctp
<h1>Edit Post</h1>
<?php
echo $this->Form->create('Drprofile');
?>
<table>
<tr><h3>Edit profile</h3></tr>
<tr><td>Name</td><td><?php echo $this->Form->text('User.fullname'); ?></td></tr>
<tr><td>Email</td><td><?php echo $this->Form->text('User.email'); ?></td></tr>
<tr><td>Mobile</td><td><?php echo $this->Form->text('User.contactnumber'); ?></td></tr>
<tr><td>Gender</td><td><?php
$options=array('M'=>'Male','F'=>'Female');
$attributes=array('legend'=>false);
echo $this->Form->radio('User.gender',$options,$attributes);
?></td></td></tr>
<tr><td>D.O.b</td><td><?php echo $this->Form->text('dob'); ?></td></tr>
<tr><td>Experience</td><td><?php echo $this->Form->select('exp', array('options' => array('1 year','2 years ','3 years','4 years','5-10 years'))); ?></td></tr>
<tr><td><?php echo $this->Form->input('drprofile.Resume', array('between'=>'<br />','type'=>'file'));?></td></tr>
<tr><td><?php echo $this->Form->end('Save Drprofile');?></td></tr>
<?php /*?><?php echo $this->Form->input('id', array('type' => 'hidden'));?><?php */?>
</table>
First thing you are doing this in Dashboards controller, and you are creating data for Drprofile. If you in the end you want to do it in DashboardsController then you should change your from to this:
echo $this->Form->create('Drprofile', array(
'url' => array('controller' => 'dashboards', 'action' => 'editdrprofile')
));
This way you are telling form what action to use. But I would suggest you move that to DprofilesController and edit that data there.
One more thing, you closed your form there and you place $this->Form->input for id after it, change that.

How to echo Users' Comments for individual Events

Hi all Iam using Cakephp 2.x, I need to output individual users' comments for each individual event. Each user has many events and many comments. I have Events, Comments and Users models and want to allow users to post and view comments on each event view.ctp. If anyone could give any starting tips to implement this functionality it would be much appreciated.
I have tried to output the comments model index table in the events view.ctp, but the table is not populated with the comments from the database, but the comments view.ctp does in fact populate the table with the comments. I have used the $this->loadModel('Comments'); function in the events controller.
<div class="events view">
<?php echo $this->Html->css('viewevent'); ?>
<?php echo $this->element('maintitlegen'); ?>
<div style="padding-top: 160px">
<h2><?php echo $event['Event']['name']; ?></h2>
<dl>
<dt><?php echo __('Event Image'); ?></dt>
<dd>
<?php echo $this->Html->image('/uploads/event/filename/thumb/small/'.$event['Event']['filename']); ?>
</dd>
<dt><?php echo __('Date'); ?></dt>
<dd>
<?php echo h($event['Event']['date']); ?>
</dd>
<dt><?php echo __('Time'); ?></dt>
<dd>
<?php echo h($event['Event']['time']); ?>
</dd>
<dt><?php echo __('Description'); ?></dt>
<dd>
<?php echo h($event['Event']['description']); ?>
</dd>
<dt><?php echo __('Dresscode'); ?></dt>
<dd>
<?php echo h($event['Event']['dresscode']); ?>
</dd>
<dt><?php echo __('Slogan'); ?></dt>
<dd>
<?php echo h($event['Event']['slogan']); ?>
</dd>
<dt><?php echo __('Price'); ?></dt>
<dd>
<?php echo h($event['Event']['price']); ?>
</dd>
<dt><?php echo __('Offers'); ?></dt>
<dd>
<?php echo h($event['Event']['offers']); ?>
</dd>
</dl>
<!--<?php foreach ($users as $user): ?>
<?php echo $user['Comment']['comment']; ?>
<?php endforeach; ?>-->
<!--<?php echo $ucomment['Comment']['comment']; ?>-->
<?php echo $this->Form->create('Comment', array('controller' => 'comments', 'action' => 'add')); ?>
<?php echo ('Add Comment'); ?>
<?php echo $this->Form->input('comment'); ?>
<?php echo $this->Form->end('Submit'); ?>
</div>
<div class="comments index">
<h2><?php echo ('Comments'); ?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('comment'); ?></th>
<th><?php echo $this->Paginator->sort('created'); ?></th>
<th><?php echo $this->Paginator->sort('modified'); ?></th>
<th><?php echo $this->Paginator->sort('user_id'); ?></th>
<th><?php echo $this->Paginator->sort('event_id'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php
foreach ($comments as $comment): ?>
<tr>
<td><?php echo h($comment['Comment']['id']); ?> </td>
<td><?php echo h($comment['Comment']['comment']); ?> </td>
<td><?php echo h($comment['Comment']['created']); ?> </td>
<td><?php echo h($comment['Comment']['modified']); ?> </td>
<td>
<?php echo $this->Html->link($comment['User']['name'], array('controller' => 'users', 'action' => 'view', $comment['User']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link($comment['Event']['name'], array('controller' => 'events', 'action' => 'view', $comment['Event']['id'])); ?>
</td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $comment['Comment']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $comment['Comment']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $comment['Comment']['id']), null, __('Are you sure you want to delete # %s?', $comment['Comment']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
));
?> </p>
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
?>
</div>
</div>
</div>
////////////////////////////////User model///////////////////////////////////////////////
<?php
class User extends AppModel {
public $name = 'User';
public $displayField = 'name';
public $validate = array(
'name'=>array(
'Please enter your name.'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your name.'
)
),
'username'=>array(
'That username has already been taken'=>array(
'rule'=>'isUnique',
'message'=>'That username has already been taken.'
),
'Valid email'=>array(
'rule'=>array('email'),
'message'=>'Please enter a valid email address'
)
),
'email'=>array(
'Valid email'=>array(
'rule'=>array('email'),
'message'=>'Please enter a valid email address'
)
),
'password'=>array(
'Not empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please enter your password'
),
'Match passwords'=>array(
'rule'=>'matchPasswords',
'message'=>'Your passwords do not match'
)
),
'password_confirmation'=>array(
'Not empty'=>array(
'rule'=>'notEmpty',
'message'=>'Please confirm your password'
)
)
);
public function matchPasswords($data) {
if ($data['password'] == $this->data['User']['password_confirmation']) {
return true;
}
$this->invalidate('password_confirmation', 'Your passwords do not match');
return false;
}
public function beforeSave($options = array()) {
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
public $hasMany = array(
'Event' => array(
'className' => 'Event',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
public $hasOne = array(
'Profile' => array(
'className' => 'Profile',
'foreignKey' => 'user_id',
'dependent' => true));
var $actsAs = array(
'MeioUpload.MeioUpload' => array('filename'=>array(
'thumbsizes'=>array(
'small'=>array(
'width'=>'75',
'height'=>'75',
'forceAspectRatio'=>'C'
)))));
}
?>
///////////////////////////////////// Users Controller///////////////////////////////////
<?php
class UsersController extends AppController {
public $name = 'Users';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function isAuthorized($user) {
if ($user['role'] == 'admin') {
return true;
}
// if (in_array($this->action, array('delete'))) {
// if ($user['id'] != $this->request->params['pass'][0]) {
// return false;
// }
// }
return true;
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Your username/password combination was incorrect');
}
}
}
// public function logout() {
// $this->redirect($this->Auth->logout());
// }
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->User->find('all'));
}
public function view($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException('Invalid user');
}
if (!$id) {
$this->Session->setFlash('Invalid user');
$this->redirect(array('action' => 'index'));
}
$this->set('user', $this->User->read());
}
public function add() {
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('Now create your profile!');
$this->Auth->login();
$this->redirect(array('controller'=> 'profiles', 'action' => 'add'));
} else {
$this->Session->setFlash('Your account cannot be created. Please try again.');
}
}
// if (!empty($user)){
// $this->request->data['Profile']['user_id'] = $this->User->id;
// $this->User->Profile->save($this->request->data);
// }
}
public function edit($id = null) {
$this->User->id = $id;
$user = $this->User->read();
if($user['User']['id'] != $this->Auth->user('id')){
$this->redirect(array('controller' => 'events','action' => 'index'));
}
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('get')) {
$this->request->data = $user;
} else {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Your account has been updated'));
$this->redirect(array('controller' => 'events', 'action' => 'index'));
} else {
$this->Session->setFlash(__('Your account cannot be saved. Please try again.'));
}
}
}
public function delete($id = null) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if (!$id) {
$this->Session->setFlash('Invalid id for user');
$this->redirect(array('action'=>'index'));
}
if ($this->User->delete($id)) {
$this->Session->setFlash('User deleted');
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash('User was not deleted');
$this->redirect(array('action' => 'index'));
}
}
?>
I think it is safe to assume your comment table has at least the following columns:
id
user_id
event_id
comment (or name)
The view you display in the OP is the view for the events.view method. But you do not show the even model or controller. So I am not certain if you need help with the events controller or if you are trying to display event data in the users controller. The way to get all of the comments for the view you show in the OP is to pull all of the comments from the model like so:
$this->set('comments', $this->Event->Comment->find('all', array('conditions' => array('event_id' => $event_id))));
If you want the user data to be displayed along with it, you will need to either set recursive = 1 or write a join to join the user data.

how to match input field before save it in cakephp

when user enter the full url..i want to save only youtube id... pregmatch examine and extract video id and then it will be saved into database..the problem is how to make this pregmatch check and extract youtube id before save the full url
thanks for helping
// this is add() function in videos_controller
function add() {
if (!empty($this->data)) {
$this->Video->create();
if ($this->Video->save($this->data)) {
$this->Session->setFlash(__('The Video has been saved', true));
$this->redirect(array('action' => 'admin_index'));
} else {
$this->Session->setFlash(__('The Video could not be saved. Please, try again.', true));
}
}
$vcats = $this->Video->Vcat->find('list');
$this->set(compact('vcats'));
}
// this is add.ctp file
<div class="videos form">
<?php // echo $this->Form->create('Image');?>
<?php echo $form->create('Video'); ?>
<fieldset>
<legend><?php __('Add Video'); ?></legend>
<?php
echo $this->Form->input('vcat_id');
echo $this->Form->input('title');
$url= $this->Form->input('link');
echo $url
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true)); ?>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Videos', true), array('action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('List Vcats', true), array('controller' => 'vcats', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Vcat', true), array('controller' => 'vcats', 'action' => 'add')); ?> </li>
</ul>
</div>
// we get the unique video id from the url by matching the pattern but where i put this code to match before save
preg_match("/v=([^&]+)/i", $url, $matches);
$id = $matches[1];
Here
function add() {
if (!empty($this->data)) {
$this->Video->create();
$url = $this->data['Video']['link'];
/*assuming you have a column `id` in your `videos` table
where you want to store the id,
replace this if you have different column for this*/
preg_match("/v=([^&]+)/i", $url, $matches);
$this->data['Video']['id'] = $matches[1];
//rest of the code
}
}
I guess a better place for it is in the Model's beforeSave or beforeValidate method:
class Video extends AppModel {
...
public function beforeSave() {
if (!empty($this->data[$this->alias]['link'])) {
if (preg_match("/v=([^&]+)/i", $this->data[$this->alias]['link'], $matches)) {
$this->data[$this->alias]['some_id_field'] = $matches[1];
}
}
return true;
}
...
}

Resources