Setting custom $this->request->data without breaking rest of form? - cakephp

I have an add() view for Lessons - in it I have a form:
<?php echo $this->Form->create('Lesson'); ?>
<fieldset>
<legend><?php echo __('Add Lesson'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('course_id', array('selected' => $this->request->data['named']['belongsToCourse']));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
It seems that when I set $this->request->data['named']['belongsToCourse'] in the controller, it somehow made it so that I am not saving the $this->Form->input('name');
How do I set the course_id without breaking the $this->request->data which should include the new lesson's name?
Here's the error I get when trying to save. Because it thinks I'm saving a duplicate name '':
Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name'
Here is the action add():
public function add() {
$this->request->data = $this->request->params;
if ($this->request->is('post')) {
$courseID = $this->request->data['named']['belongsToCourse'];
$this->Lesson->create();
if ($this->Lesson->save($this->request->data)) {
$this->Session->setFlash(__('The lesson has been saved.'));
return $this->redirect(array('controller' => 'courses', 'action' => 'view', $courseID));
} else {
$this->Session->setFlash(__('The lesson could not be saved. Please, try again.'));
}
}
//debug(func_get_args());
$courses = $this->Lesson->Course->find('list');
$this->set(compact('courses'));
//$this->Form->input('course_id') = $belongsToCourse;
}

Related

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.....

edit post is not working in cakephp

I am learning Cakephp framwork. I am having problem while I am trying to update database record.
This is Controller code for edit post....
$this->loadModel('Post');
if($this->request->is('put')):
$this->Post->id = $this->params['id'];
if($this->Post->save($this->request->data)):
$this->Session->setFlash(__('Page has been edited'));
$this->redirect('/User/index');
endif;
else:
$this->set('postinfo', $this->Post->findById($this->params['id']));
endif;
}
This is view/edit.ctp file
echo $this->Form->update('Post', array(
'method' => 'put'
));
echo $this->Form->input('title',array('type' => 'text','value'=>$postinfo['Post']['title']));
echo $this->Form->input('body', array('type' => 'textarea','value' => $postinfo['Post']['body']));
echo $this->Form->submit('Submit', array('class'=>'btn btn-primary'));
echo $this->Form->end();
But this code does not update record in database...I tried everything from book.cakephp.org tutorial and other tutorials related to cakephp..
I hope I'll get some help from you guys :)
If this is PostController, than you don't need to call the $this->loadModel('Post'); function.
In view you need a hidden field with id of post.
Controller code for edit post
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash('Unable to update your post.');
}
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
view/edit.ctp file
<h1>Edit Post</h1>
<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->end('Save Post');
?>

Redirecting to a different controller view in Cakephp

I have to 2 models that are related ItQuery and ItQueryComment. When a user adds a ItQuery other users should be able to comment on it. What i am trying to achieve is when other users add comments on a query they should be redirect to the view of the query not the index page for the it_query_comments
here is my code for my comments add view
<?php echo $this->Form->create('ItQueryComment'); ?>
<fieldset>
<legend><?php echo __('Add It Query Comment'); ?></legend>
<?php
echo $this->Form->input('it_query_id');
echo $this->Form->input('comment');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
and here is my add function in the controller
public function add() {
if ($this->request->is('post')) {
$this->ItQueryComment->create();
if ($this->ItQueryComment->save($this->request->data)) {
$this->Session->setFlash(__('The it query comment has been saved'));
$this->redirect(array('controller' => 'it_queries','action' => 'view', $itQuery['ItQuery']['id']));
} else {
$this->Session->setFlash(__('The it query comment could not be saved. Please, try again.'));
}
}
$itQueries = $this->ItQueryComment->ItQuery->find('list');
$this->set(compact('itQueries'));
}
If anyone could show me how to do this, that would be awesome. Thanks in advance
try the following
$this->redirect(array(
'controller' => 'it_queries',
'action' => 'view',
$this->request->data['ItQuery']['id'])
);

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;
}
...
}

Add a user in Cakephp authentication tutorial

There is a problem when I write add() function for UsersController.
public function add(){
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('The new user has been saved.');
$this->redirect(array('action' => 'test'));
}
}
$this->set('title_for_layout', 'Register');
}
This is add view ctp.
<?php
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Save User');
?>
There's always a internal error when I try to access to users/add. Anyone know how to deal with this problem? Thanks.
Have you tried testing for $this->data instead of $this->request->is('post')? It might not matter, but that's typically the way it is done.
Also, for saving, you should most likely (unless you are setting userid manually) do something like:
$this->User->create();
$this->User->save($this->data);
So your add function should look something like:
public function add(){
if ($this->data) {
$this->User->create();
if ($this->User->save($this->data)) {
$this->Session->setFlash('The new user has been saved.');
$this->redirect(array('action' => 'test'));
}
}
$this->set('title_for_layout', 'Register');
}
And you probably want your view to be something like:
<?php echo $form->create('User', array('action' => 'add')); ?>
<?php echo $form->input("username", array('label' => 'Username')) ?>
<?php echo $form->input("password",array("type"=>"password", 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>

Resources