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
Related
I'm using the cakephp uploader plugin by Miles Johnson. I like the plugin and I've got it working to be able to upload photos for a photo model.
The problem I'm running into is that when I try to edit an existing record, instead of replacing the photo associated with the record I'm editing a new record is created. The new record has all the same information with the exception of the new photo that's been uploaded.
Here's how the photo model looks:
'Uploader.Attachment' => array(
'imgPath' => array(
// 'name' => '', // Name of the function to use to format filenames
'baseDir' => '', // See UploaderComponent::$baseDir
'uploadDir' => 'files/uploads/', // See UploaderComponent::$uploadDir
'dbColumn' => 'imgPath', // The database column name to save the path to
'maxNameLength' => 60, // Max file name length
'overwrite' => false, // Overwrite file with same name if it exists
'stopSave' => true, // Stop the model save() if upload fails
'allowEmpty' => true, // Allow an empty file upload to continue
'transforms' => array( // What transformations to do on images: scale, resize, etc
array(
'method' => 'resize',
'width' => 50,
'height' => 50,
'append' => '_thumb',
'dbColumn' => 'imgPathThumb',
)
)
)
)
This is the photo admin edit view form:
<?php echo $this->Html->script('ckeditor/ckeditor');?>
<?php echo $this->Form->create('Photo', array('type' => 'file'));?>
<fieldset>
<legend><?php echo __('Admin Edit Photo'); ?></legend>
<?php
echo $this->Form->input('title');
echo $this->Form->input('caption', array('class'=>'ckeditor'));
echo $this->Form->input('imgPath', array('type' => 'file'));
echo $this->Form->input('alt_tag');
echo $this->Form->input('type', array( 'label' => 'Choose a type of photo', 'options' => array(
'gallery'=>'gallery',
'news'=>'news',
'post'=>'post',
)));
echo $this->Form->input('active', array( 'label' => 'Make active', 'options' => array('yes'=>'yes','no'=>'no' )));
echo $this->Form->input('gallery_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
This is the controller admin edit code:
public function admin_edit($id = null) {
$this->layout = 'admin';
if (!$this->Photo->exists($id)) {
throw new NotFoundException(__('Invalid photo'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Photo->save($this->request->data)) {
$this->Session->setFlash(__('The photo has been saved.'), 'success');
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The photo could not be saved. Please, try again.'), 'error');
}
} else {
$options = array('conditions' => array('Photo.' . $this->Photo->primaryKey => $id));
$this->request->data = $this->Photo->find('first', $options);
}
$galleries = $this->Photo->Gallery->find('list');
$this->set(compact('galleries'));
}
Have I overlooked something obvious?
Cheers, Paul
When You editing record, You must set ID of this record.
Add to form $this->Form->input('id') or set ID in controller before save() action
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;
}
I have a page with a list of books, and every row has a checkbox. (I'm using cakephp 1.2).
I want to let the user to save multiple books.
For now I have this checkbox in my view (in a cycle, where I get the list of all books):
<?php echo $form->input('salva', array('value' => $cdBiblio['CdBiblio']['codiceBiblio'], 'label' => '', 'type' => 'checkbox')); ?>
This form:<?php echo $form->create('cd_biblios', array('action' => 'save')); ?>
And this button:
<?php echo $form->end('Add All');?>
In the controller, I have something like this for debugging:
debug($this->data);
foreach($this->data['cd_biblios']['salva'] as $item) {
debug($item);
}
But it's not working.
I noticed that it takes only the last book id of the list with debug($this->data); and if I check more than 1 book, it show 0 or the last book id, for example:
Array (
[cd_biblios] => Array
(
[salva] => 0
) )
SOLVED:
In the view I use Danial's code.
In the controller I use this code:
if(!empty($this->data)) {
$item=$this->data;
debug($item);
$dim=count($item['Model']['field']);
$i=0;
for ($i=0;$i<$dim;$i++)
if ($item['Model']['field'][$i]!=0)
{
$data = $this->Session->read('libri');
$data[] = $item['Model']['field'][$i];
$this->Session->write('libri', $data);
}
$this->Session->setFlash(__('I libri sono stati salvati', true));
$this->redirect($this->referer());
}
In View:
<?php
foreach($array as $each_elem) {
echo $form->checkbox(
'Model.field',
array(
'id'=>'abcd_'.$each_elem['Model']['id'],
'value' => $each_elem['Model']['id'],
'hiddenField' => false,
'name' => 'data[Model][field][]',
'label' => false,
'div' => false,
));
}
?>
On submit the form, you will get the checked values in controller in $this->request->data
You have a conception problem.
Your checkboxes must be inside a form, because they are input tags. So, to send those values to the controller you'll need to submit that form. In your code, i see that "Add All" is just a link. And a link won't submit the form.
Change your link to a button :)
Hope this helps
I have a cakephp 1.3 app which get's a person's consent to participate in a study. I'm trying to link inclusion criteria and exclusion criteria for the study on the Add study page. The HABTM relationship is setup and working(If there's only one way to select them) What I'm trying to do now is display the current Inclusion Criteria as a list of checkboxes the person adding the study can select, but I also want a field where new criteria can be entered as a comma seperated list. Right now it will save the checkboxes, but I want it to also add the text entered in the field as well. Screen showing the Add study as it sits now is below. I don't really know how I would go about doing that. Is there a way to do this or will I have to take the data entered, sort through it and then add it to $this->data[inclusion field data]? An example would be nice. :) I've added the code I have so far below the image.
Controller:
/**
* Add a study.
*/
function add() {
if (!empty($this->data)) {
//get the inclusions from the text data
//Sort through the comma seperated list and add it to $this->data['Study']['Inclusions']???
$this->Study->create();
if ($this->Study->save($this->data)) {
$this->Session->setFlash(__('The study has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The study could not be saved. Please, try again.', true));
}
}
$this->set('inclusions', $this->Study->Inclusion->find('list', array(
'fields' => array('id', 'name'),
'order' => 'Inclusion.name',
'recursive' => 0,
)));
$this->set('exclusions', $this->Study->Exclusion->find('list', array(
'fields' => array('id', 'name'),
'order' => 'Exclusion.name',
'recursive' => 0,
)));
$this->set('forms', $this->Study->Form->find('list', array('order' => 'Form.name','recursive' => 0,)));
}
View:
<div class="studies form">
<?php echo $this->Form->create('Study', array('type' => 'file'));?>
<fieldset>
<legend><?php __('Add Study'); ?></legend>
<?php
echo $this->Form->input('studyname', array('label'=>'Study Name','required' => true));
echo $this->Form->input('studynumber', array('label'=>'Study Number','required' => true));
echo $this->Form->input('file', array('label'=>'Select Electronic Consent','type' => 'file'));
echo $this->Form->input('consent_form_date');
?>
<fieldset class="inclusion">
<legend><?php __('Inclusions'); ?></legend>
<div class="IncExc">
<?php
echo $this->Form->input('Inclusion',array(
'label' => false,
'type' => 'select',
'multiple' => 'checkbox',
'options' => $inclusions,
'selected' => $html->value('Inclusion.Inclusion'),
));
?>
</div>
<?php
echo $form->input('Inclusion.inclusions',array(
'type' => 'text',
'label' => __('Add New Inclusions',true),
'after' => __('Seperate each new Inclusion with a comma. Eg: family, sports, icecream',true)
));
?>
</fieldset>
<fieldset>
<legend><?php __('Exclusions'); ?></legend>
<div class="IncExc">
<?php
echo $this->Form->input('Exclusion',array(
'label' => false,
'type' => 'select',
'multiple' => 'checkbox',
'options' => $exclusions,
'selected' => $html->value('Exclusion.Exclusion'),
));
?>
</div>
</fieldset>
<fieldset style="width: 700px;">
<legend><?php //__('Forms'); ?></legend>
<?php /*
echo $this->Form->input('Form',array(
'label' => false,
'type' => 'select',
'multiple' => 'checkbox',
'options' => $forms,
'selected' => $html->value('Form.Form'),
));
*/ ?>
</fieldset>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
You are trying to do pretty much the same as he wanted to do: Saving tags into a database table in CakePHP
What you have to do is:
Check if the manual inclusion field is empty or not. If the field is empty ignore it and go to step 5
If the field is not empty, split it at comma or whatever sign you want to use as a seperator. You can now validate it if you want to.
Use all the inclusions of step 3 and save them in your custom or real inclusion table. You should keep track of those custom entries in some way, so you don't mess them up with those you provided. Save all the ids generated while saving within an array.
Merge the collected ids of step 3 with those you got from the form which were given by you.
Save all collected and given data to database
The answere in the post given above including the code there can be used to do that. You should get along with it pretty well if you read the whole post + code comments ;)
If you have any further questions, just ask ;)
Greetings
func0der
I am using cakephp2.0 and want to integrate comment plugin but i got nothing .I was using commentDc plugin but its not working as my requirements.Because i am integreating my users login system with xenforo and commentDc plugin use Auth component so its not working properly.
Please let me know is there any simple comment plugin which i can integrate and modify as my needs.
Thanks,
Here's how I set up comments:
Comments table fields:
id
parent_type, matches the model name of the parent
parent_id
content
user_id, the sender
In any model that you want to be commentable, at this your associations:
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'parent_id',
'conditions' => array('Comment.parent_type' => 'question')
)
);
This is a view element:
<?php
/*
set variables:
$data : data of the parent
$type : the type of the parent
*/
if(!isset($name)) {
$name = 0;
}
foreach($data['Comment'] as $comment){
echo '<div class="comment">'.$comment['content'].
' - '.$this->Html->link($comment['User']['username'],array('controller'=>'users','action'=>'view',$comment['User']['id']))
.'</div>';
}
echo $this->Form->create(null, array('url' => '/comments/add','id'=>'qCommentForm'));
echo $this->Form->input('Comment.parent_id', array('type'=>'hidden','value'=>$data[$type]['id']));
echo $this->Form->input('Comment.parent_type', array('type'=>'hidden','value'=>$type));
echo $this->Form->textarea('Comment.content',array('div'=>'false','class'=>'small','label'=>false));
echo $this->Form->submit(__('Leave comment'),array('div'=>'false','class'=>'small'));
echo $this->Form->end();
?>
Then, in the view view for your model, add this (assuming you named the element comment.ctp:
<?php echo $this->element('comment',array('data'=>$modelData,'type'=>'MyModel')) ?>